Flask, change telegram bot token in runtime - python

This is how I start the bot now:
""" Bot logic """
from flask import request
from shopbot_crm import shopbot_crm_bp
import telebot
from telebot import types
from telebot import apihelper
import secrets
from models import db, TgBot
secret = secrets.token_urlsafe(32)
bot = telebot.TeleBot('token', threaded=False)
bot.remove_webhook()
time.sleep(1)
bot.set_webhook(url="https://mywebhook.com/bot_panel/bot/{}".format(secret))
apihelper.ENABLE_MIDDLEWARE = True
#shopbot_crm_bp.route('/bot/{}'.format(secret), methods=["POST"])
def webhook():
bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode("utf-8"))])
return "ok", 200
#shopbot_crm_bp.route('/bot/reload', methods=["GET"])
def bot_reload():
#Can I somehow change the token from here?
#bot.message_handler(content_types=['text'])
def hello(message):
bot.send_message(message.chat.id, 'Hello')
In my application, the user should be able to change the current token to the bot.
Question:
How can I change this token to another and re-create the webhook in runtime?

Related

discord.py output of receiving webhooks from Flask

I am currently working on implementing a game report webhook into my discord bot, so I can send the message with buttons etc., to have a claim system (so using discords webhooks isn't a solution).
How can I run my discord bot and have flask (or every other suitable library) run simultaneously?
If I manage to get that to work, how do I transfer the data to my discord bot?
Here is what I tried:
from flask import Flask, request, Response
from json import loads
app = Flask(import_name='scp:flask')
#app.route('/webhook', methods=['POST'])
async def listener():
data = request.form
x = (loads(data.get("payload_json")))["embeds"][0]["fields"][2:9]
print(f'Data: {x}')
return Response(status=200)
app.run()

Redirect messages automatically in Telegram

I want to make automation that gets a message from a group, that we'll call group A.
And send it into group B.
I should use Telegram API or Telegram BOTs to solve this?
And how i can solve this problem using python?
I was having this same problem and figured this out:
# imports
from telegram import Update
from telegram.ext import *
import telegram
from dotenv import load_dotenv
import os
# get the telegram bot api_key from environment file
load_dotenv()
API_KEY = os.getenv('API_KEY')
# you will need the groub_b_id saved as a global variable or
# in some other document
group_b_id = 1234567890
# create the bot, updater, and dispatcher
bot = telegram.Bot(token=API_KEY)
updater = Updater(API_KEY, use_context=True)
dp = updater.dispatcher
def get_chat_id(update: Update, context: CallbackContext):
# gets the chat_id of the current chat
global bot
chat_id = update.effective_chat.id
bot.send_message(chat_id, "This chat's id is: " + str(chat_id))
def auto_forward(update: Update, context: CallbackContext):
# automatically forwards messages from this chat to
# chat_b
global bot, group_b_id
chat_id = update.effective_chat.id
username = update.effective_message.from_user.name
chat_title = update.effective_message.chat.title
msg_txt = update.effective_message.text
bot.send_message(
group_b_id,
text=f"'{msg_txt}'\nwas just sent in chat {chat_title} by {username}"
)
# sets up the handlers
dp.add_handler(CommandHandler('get_chat_id', get_chat_id))
dp.add_handler(MessageHandler(Filters.text, auto_forward))
# Start the Bot
updater.start_polling()
updater.idle()
just make sure that you add the bot as an admin to both chats and this will work!

Circular import using flask and discord bot

I have these two files:
main.py
import os
import discord
from keep_alive import keep_alive
client = discord.Client()
my_secret = os.environ['Token']
async def SendMeMessage():
user = await client.fetch_user('my id')
await user.create_dm()
await user.dm_channel.send("Someone needs help")
keep_alive()
client.run(my_secret)
keep_alive.py
from flask import Flask
from threading import Thread
#from main import SendMeMessage
app = Flask('')
#app.route('/')
def home():
#SendMeMessage()
return "Hello. I am alive!"
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
And I would like to import SendMemessage. So when someone send get request on flask server, I wanna receive message from my discord bot. I'm stuck on error "circular import", when I implement commented code.
I would move the discord bot code out of main.py, so it no longer depends on an import of keep_alive.
bot.py:
import os
import discord
client = discord.Client()
async def SendMeMessage():
user = await client.fetch_user('my id')
await user.create_dm()
await user.dm_channel.send("Someone needs help")
keep_alive.py:
from flask import Flask
from threading import Thread
from bot import SendMeMessage
app = Flask('')
#app.route('/')
def home():
SendMeMessage()
return "Hello. I am alive!"
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
main.py:
import os
from keep_alive import keep_alive
from bot import client
my_secret = os.environ['Token']
keep_alive()
client.run(my_secret)
This way, bot.py has already been fully imported when keep_alive.py runs, so there is no longer a circular import.

How to make a POST request with a JSON into a Discord bot from a Flask Python app

I have a small discord bot and a small flask project (bot.py and app.py).
On my flask project I have an endpoint that I can receive JSON POST request (i can see the JSON fine). Now the question is how do I send from Flask to my Bot.py this JSON payload so that my bot.py posts it on my Discord channel.
My code:
flask app:
from flask import Flask, json, request,
app = Flask(__name__)
#app.route('/', methods=['GET'])
def index():
return 'working ...'
#app.route('/webhook', methods=['POST'])
def jiraJSON():
if request.is_json:
data = request.get_json()
print(data)
return 'json received', 200
else:
return 'Failed - Not a JSON', 400
if __name__ == '__main__':
app.run()
my bot.py from (https://realpython.com/how-to-make-a-discord-bot-python/)
# bot.py
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(TOKEN)
So I've managed to make it work using Quart and a bot with Discord.py.
This will take a JSON on a webhook and send that JSON to a Discord bot to be posted on a Chanel ID.
import discord
import asyncio
from quart import Quart, request
app = Quart(__name__)
client = discord.Client()
# Setup for Discord bot
#app.before_serving
async def before_serving():
loop = asyncio.get_event_loop()
await client.login('<<<your_discord_bot_token_id>>>')
loop.create_task(client.connect())
#Setup for webhook to receive POST and send it to Discord bot
#app.route('/webhook', methods=['POST'])
async def myJSON():
channel = client.get_channel(<<<your_discord_chanel_ID>>>)
if request.is_json:
data = await request.get_json()
print(data)
await channel.send(data)
return 'json received', 200
else:
return 'Failed - Not a JSON', 400
if __name__ == '__main__':
app.run()

Telegram Bot get as User Input previous message

I'm experiencing a small issue with the library python-telegram-bot.
So this is my code:
from __future__ import unicode_literals
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram.ext import CommandHandler, CallbackQueryHandler, CallbackContext
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup
from telegram import Update
from telegram import Bot
import telegram
import os
import datetime
import sqlite3
import traceback
import re
import data
def start(update, context):
chatid = update.message.chat_id
if data.user_exist(chatid) == True:
update.message.reply_text('Choiche wallet', reply_markup=wallet_handler(chatid, update, context))
if data.user_exist(chatid) == False:
update.message.reply_text('Add wallet')
add_wallet(chatid, update, context)
def wallet_handler(chatid, update, context):
kb = []
for w in data.fetch_wallet(chatid):
s = w[0:10]
kb.append([InlineKeyboardButton(s, callback_data=w)])
kb.append([InlineKeyboardButton('Add Wallet', callback_data='add')])
kb.append([InlineKeyboardButton('Delete Wallet', callback_data='delete')])
return InlineKeyboardMarkup(kb)
def add_wallet(chatid, update, context):
regex = re.compile(r"/^(?:0x)[A-Z0-9]{15}$/")
update.message.reply_text(text='Insert a wallet address please')
address = update.message.text
print(address)
if re.fullmatch(regex, address):
print('okay')
else:
print('nooo')
return
def main():
update= Updater('token', use_context=True)
bot = Bot('token')
disp=update.dispatcher
disp.add_handler(CommandHandler('start', start))
disp.add_handler(MessageHandler(Filters.regex('/^(?:0x)[A-Z0-9]{15}$/'), add_wallet, run_async=True))
update.start_polling()
update.idle()
if __name__=='__main__':
main()
When the user send the /start command, the function user_exist() check a determined condition. If the function returns false, then the bot should wait for user input (triggering the function add_wallet()).
But when I try this code, the add_wallet() function takes as user input the previous message /start and doesn't wait for the user input.
How to fix it? Thanks

Categories

Resources