0

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:

  1. It is the code snippet from the documentation for heroku, so I do not know whether this works the same for google cloud functions

  2. 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!

Fnguyen
  • 1,159
  • 10
  • 23
  • It's possible that you are ussing the wron GCP tool to manage your boot. Cloud Function is intended to run just one function per script (the simpler/smaller the better). If you want to implement a complete/complex bot you may want to use App Engine. In App Engine you can implement a more complex Bot. – Chris32 Aug 20 '19 at 08:31
  • @ChristianGonzalez That might be the case, and other bots I have hosted on heroku or an AWS EC2 instance. However I wanted to try the concept of webhooks which need an API Gateway and function like Cloud Function. Similarly to AWS Lambda, etc. I have seen some examples of telegram bots working like that, especially to minimize costs for a hobby project. I'd consider an answer showing how to setup free (dep. on traffic of course) webhooks on App Engine. – Fnguyen Aug 20 '19 at 09:18

2 Answers2

2

i did that here's my snippet

from telegram import Bot,Update
from telegram.ext import CommandHandler,Dispatcher
import os

TOKEN = os.getenv('TOKEN')
bot = Bot(token=TOKEN)

dispatcher = Dispatcher(bot,None,workers=0)

def start(update,context):
  context.bot.send_message(chat_id=update.effective_chat.id,text="I am a bot, you can talk to me")


dispatcher.add_handler(CommandHandler('start',start))


def main(request):
  update = Update.de_json(request.get_json(force=True), bot)

  dispatcher.process_update(update)
  return "OK"

# below function to be used only once to set webhook url on telegram 
def set_webhook(request):
  global bot
  global TOKEN
  s = bot.setWebhook(f"{URL}/{TOKEN}") # replace your functions URL,TOKEN
  if s:
    return "Webhook Setup OK"
  else:
    return "Webhook Setup Failed"
iBug
  • 35,554
  • 7
  • 89
  • 134
1

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.

Chris32
  • 4,716
  • 2
  • 18
  • 30
  • Thanks, I have been looking into it a bit more and you might be right, that I was trying to use a hammer with a screw. I'll wait a bit to see if more answers come in but I'm inclined to mark your answer as correct, if you add a bit more from your comment on why cloud function is simply not the right tool here. – Fnguyen Aug 20 '19 at 14:22
  • Cloud Functions are isolated docker containers of a bigger App Engine. So each function will have only a defined url and are minded to run just a main function. In other hand App Engine is a more customizable enviroment where you can define more extenses deployment like a chatbot – Chris32 Aug 20 '19 at 15:03