R
R
ramazan2017-04-26 11:35:19
Bots
ramazan, 2017-04-26 11:35:19

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))

You can receive messages about adding/removing a bot to chats using Flask's route and telegram.update.Update.de_json():
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)

Is it possible to receive messages about adding/removing a bot to chats without using it? If so, how?
If you use CommandHandlers and Flask's routes at the same time, then CommandHandlers stop working, apparently because @app.route intercepts messages like this:
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)

1. Is it possible to receive messages about adding/removing a bot to chats without using it? If so, how?
2. How to make sure that commands from the user are not intercepted by @app.route?
3. Are there other ways to receive messages about adding / deleting a bot from / to chats and convenient processing of commands from the user?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sl4n, 2018-10-17
@sl4n

@app.route('/' + config.TOKEN, methods=['POST'])
def webhook():
update = telegram.update.Update.de_json(request.get_json(force=True), bot)
dp.process_update (update)
return "OK"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question