I have set up a telegram bot using webhooks in python on google cloud functions. Based on some sample code from the internet I got it to work as a simple echo-bot however the structure is very different to the bots I coded before using long polling:
# main.py
import os
import telegram
def webhook(request):
bot = telegram.Bot(token=os.environ["TELEGRAM_TOKEN"])
if request.method == "POST":
update = telegram.Update.de_json(request.get_json(force=True), bot)
chat_id = update.message.chat.id
# Reply with the same message
bot.sendMessage(chat_id=chat_id, text=update.message.text)
return "ok"
I do not understand how to add any more handlers or different functions to this, especially because cloud functions needs me to name only one function to run from the script (in this case the webhook function).
How can I convert the above logic to the one I am more familiar with below:
import os
TOKEN = "TOKEN"
PORT = int(os.environ.get('PORT', '8443'))
updater = Updater(TOKEN)
# add example handler
def start(update, context):
context.bot.send_message(chat_id=update.message.chat_id, text="Hello, I am dice bot and I will roll some tasty dice for you.")
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
# start webhook polling
updater.start_webhook(listen="0.0.0.0",
port=PORT,
url_path=TOKEN)
updater.bot.set_webhook("https://<appname>.herokuapp.com/" + TOKEN)
updater.idle()
This code has the same structure as long polling so I know how to add additional handlers. However it has two problems:
-
It is the code snippet from the documentation for heroku, so I do not know whether this works the same for google cloud functions
-
This does not produce one function I can call in cloud functions, I tried wrapping all my code above in one big function
webhook
and simply running that but it does not work (and does not produce an error on my google dashboard).
Any help is appreciated!
2
Answers
I found this github telebot repo from yukuku with the setup of a telegram bot on App Engine and the webhook implementation using python. As mentioned before you may want to use App Engine in order to implement your bot with many functions on the same
main.py
file.I just tried and it’s working for me.
i did that here’s my snippet