Answer the question
In order to leave comments, you need to log in
How to use both Flask's view functions and CommandHandlers of python-telegram-bot at the same time?
It is necessary to receive commands from the user, as well as receive information about which chat the bot was added / removed from. A good way to receive messages from the user is to use CommandHandlers. This code works correctly:
import telegram, config
from telegram.ext import Updater, CommandHandler, Filters, MessageHandler
bot = telegram.Bot(config.TOKEN)
def help(bot, update):
update.message.reply_text('...')
def start(bot, update):
update.message.reply_text('...')
def about(bot, update):
update.message.reply_text('...')
if __name__ == '__main__':
updater = Updater(config.TOKEN)
updater.start_webhook(listen='0.0.0.0',
port=config.PORT,
url_path=config.TOKEN,
key=config.CERT_KEY,
cert=config.CERT,
webhook_url='https://{}:{}/{}'.format(config.HOST, config.PORT, config.TOKEN))
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("about", about))
from flask import Flask, request
import telegram, config
bot = telegram.Bot(config.TOKEN)
app = Flask(__name__)
context = (config.CERT, config.CERT_KEY)
@app.route('/' + config.TOKEN, methods=['POST'])
def webhook():
update = telegram.update.Update.de_json(request.get_json(force=True), bot)
# Из update можно получить инфу о добавлении или удалении бота из чата
print(update)
return 'OK'
def setWebhook():
bot.setWebhook(webhook_url='https://%s:%s/%s' % (config.HOST, config.PORT, config.TOKEN),
certificate=open(config.CERT, 'rb'))
if __name__ == '__main__':
setWebhook()
app.run(host='0.0.0.0',
port=config.PORT,
ssl_context=context,
debug=True)
from flask import Flask, request
import telegram, config, time, datetime
from telegram.ext import Updater, CommandHandler, Filters, MessageHandler
bot = telegram.Bot(config.TOKEN)
app = Flask(__name__)
context = (config.CERT, config.CERT_KEY)
# Commands
def help(bot, update):
update.message.reply_text('...')
def start(bot, update):
update.message.reply_text('...')
def about(bot, update):
update.message.reply_text('...')
@app.route('/' + config.TOKEN, methods=['POST'])
def webhook():
update = telegram.update.Update.de_json(request.get_json(force=True), bot)
print(update)
return 'OK'
def setWebhook():
bot.setWebhook(webhook_url='https://%s:%s/%s' % (config.HOST, config.PORT, config.TOKEN),
certificate=open(config.CERT, 'rb'))
if __name__ == '__main__':
updater = Updater(config.TOKEN)
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("about", about))
setWebhook()
app.run(host='0.0.0.0',
port=config.PORT,
ssl_context=context,
debug=True)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question