Skip to content

Instantly share code, notes, and snippets.

@leandrotoledo
Last active March 23, 2024 18:17
Show Gist options
  • Save leandrotoledo/8fb59b7d559bf2748d2d164d7529ab87 to your computer and use it in GitHub Desktop.
Save leandrotoledo/8fb59b7d559bf2748d2d164d7529ab87 to your computer and use it in GitHub Desktop.
Creating a simple Echo Telegram Bot using Google Cloud Functions in 5 minutes
Requirements:
  • Google Cloud Platform with Billing enabled.
  • Bot created using the @BotFather on Telegram.
  • Bot Token issued by the @BotFather.
2) On the Navigation Menu, go to Cloud Functions.
3) Click on Create Function.
4a) In this form, the important fields are:
  • Name: webhook
  • Trigger: HTTP
  • Runtime: Python 3.7
  • URL: Copy this URL, you will use it later
4b) On MAIN.PY tab, replace with:
import telegram

bot = telegram.Bot('<REPLACE WITH BOT TOKEN>')

def webhook(request):
    if request.method == "POST":
        update = telegram.Update.de_json(request.get_json(force=True), bot)
        chat_id = update.message.chat.id

        bot.sendMessage(chat_id=chat_id, text=update.message.text)
    return True
4c) On REQUIREMENTS.TXT tab, add:

python-telegram-bot

4d) Finally, on Function to execute, change it to webhook.
5) Go ahead and click on Create.
6) Open a different tab on your browser, and type this URL, make sure to replace the Token and URL.

https://api.telegram.org/bot<REPLACE WITH BOT TOKEN>/setWebhook?url=<REPLACE WITH FUNCTION URL>

If you did it correctly you should get the following:

{"ok":true,"result":true,"description":"Webhook was set"}

7) That's it! Go talk to your Bot and it will echo back your message.
Bonus Tip

Alternatively you can use the gcloud command. Assuming you have src/main.py and src/requirements.txt, gcloud authenticated and with a Project ID set, you'd simply:

$ cd src
$ gcloud functions deploy webhook2 --runtime python37 --trigger-http
import telegram
bot = telegram.Bot('<REPLACE WITH BOT TOKEN>')
def webhook(request):
if request.method == "POST":
update = telegram.Update.de_json(request.get_json(force=True), bot)
chat_id = update.message.chat.id
bot.sendMessage(chat_id=chat_id, text=update.message.text)
return True
python-telegram-bot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment