Advertisement
arcan3

Webhook Flask + Dispatcher

Jan 24th, 2020
631
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.32 KB | None | 0 0
  1. from flask import Flask, request
  2. import logging
  3. import Scraper
  4. from credentials import bot_token, bot_user_name,URL
  5. import telegram
  6. from telegram.ext import Dispatcher, CommandHandler, MessageHandler, Filters
  7.  
  8.  
  9. app = Flask(__name__)
  10. application = app # hosting requires application in passenger_wsgi
  11.  
  12. TOKEN = bot_token
  13. bot = telegram.Bot(token=TOKEN)
  14.  
  15. def start(bot, update): #Example of callback function for dispatcher when using flask to handle update
  16.     update.message.reply_text('Hi!')
  17.  
  18. def chatid(bot, update): #Example of callback function for dispatcher when using flask to handle update
  19.     update.message.reply_text('Chat id is {}'.format(update.message.chat_id))
  20.    
  21.  
  22. #def start(update, context):
  23. #    context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")
  24. #context cannot be used maybe because need to create updater with use_context=True. Flask is already handling update.
  25. #have to use the above 2 callback functions if you are using flask to handle update
  26. #The above callback function is shown in most example of the website.
  27.  
  28.  
  29. def setup(token): #need to add this function if you are using flask to handle update
  30.     # Create bot, update queue and dispatcher instances
  31.     bot = telegram.Bot(token)
  32.     dispatcher = Dispatcher(bot, None, workers=0)
  33.     ##### Register handlers here #####
  34.     start_handler = CommandHandler('start', start)
  35.     dispatcher.add_handler(start_handler)
  36.     dispatcher.add_handler(CommandHandler('chatid', chatid))
  37.     return dispatcher
  38.  
  39. @app.route("/{}".format(TOKEN), methods=["POST","GET"])
  40. def respond():
  41.     if request.method == "GET":
  42.         return "Working Webhook"
  43.     else:
  44.         try:
  45.             dispatcher=setup(TOKEN) #need to add this line if you are using flask to handle update
  46.             update = telegram.Update.de_json(request.get_json(force=True), bot)
  47.             chat_id = update.message.chat.id
  48.             msg_id = update.message.message_id
  49.             text = update.message.text.encode("utf-8").decode()
  50.             dispatcher.process_update(update) #need to add this line if you are using flask to handle update
  51.             return Response('ok', status=200)    
  52.         finally:
  53.             pass
  54.             return "ok. Wrong Request or Error"
  55.  
  56. if __name__ == "__main__":
  57.     app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement