How to Easily Enable Webhook Mode for Python Telegram Bots


I created a Telegram bot(@wordsquad_bot) using python-telegram-bot framework. There are 2 modes to run the bot:

  • polling: single-threaded, can’t scale out, good for development environment
  • webhook: can scale and load-balance, needs public IP, DNS, etc, good for production environment

Since my bot has got almost all features and run stably for a while, I decided to setup webhook for it. I came across a few articles and did a bit of troubleshooting myself so here’s probably the easiest way to turn on webhook in 2022.

import os
from telegram.ext import Updater
...

TOKEN = os.environ["BOT_TOKEN"]
PROD = os.environ.get("PROD", "false")
DOMAIN = os.environ.get("DOMAIN", "wordsquad.mydomain.com")

def main() -> None:
	updater = Updater(TOKEN)
    ...
	if PROD == 'true':
    	# enable webhook
        updater.start_webhook(listen="0.0.0.0", port=8000, url_path=TOKEN, webhook_url=f'https://{DOMAIN}/{TOKEN}')
        # remember to setup reverse proxy/CDN so traffic is forwarded from https://{DOMAIN}/{TOKEN} to this app at port 8000
    else:
        # enable polling if it's local development
        # will need a different TOKEN for this purpose 
        updater.start_polling()

🙂