How to Build and Deploy a python-telegram-bot v20 Webhook (2024)

/ #Python
How to Build and Deploy a python-telegram-bot v20 Webhook (1)
Chua Hui Shun
How to Build and Deploy a python-telegram-bot v20 Webhook (2)

The python-telegram-bot v20 release introduced major structural changes. According to the documentation,

“All networking and I/O-related logic now works via coroutine functions (i.e. async def ... functions). In particular, all methods of the telegram.Bot class that make requests to the Bot API are now coroutine functions and need to be await-ed.” — python-telegram-bot v20 change logs

The process of transitioning from python-telegram-bot version 13 to version 20 turned out to be more complex than I had originally anticipated. Converting synchronous def functions to async def and adding await to new coroutines was fairly easy. But the main difficulty was finding detailed documentation on how to build and deploy python-telegram-bot v20 webhooks in a production setting.

This article explains why and how I migrated from:

  1. python-telegram-bot v13 → v20
  2. Flask → FastAPI
  3. Gunicorn → Gunicorn + Uvicorn

Why Upgrade from v13 to v20?

v13.x and older are no longer supported by the python-telegram-bot dev team. If Telegram API introduces any new features, they will only be available on v20 and above.

Why Use a Webhook and Not Polling?

Most examples provided by the python-telegram-bot dev team use Application.run_polling. But webhooks are generally recommended over polling for most Telegram bot use cases, because polling requires your bot to constantly make requests to Telegram’s servers, which can consume significant resources. On the other hand, webhooks offer extended functionality, update faster, and scale better.

The Challenge of using Flask with python-telegram-bot v20

Using a WGSI like Flask with python-telegram-bot v20 is awkward.

Flask, a WSGI (Web Server Gateway Interface), is synchronous and can handle only one request at a time. But you can still run async functions in Flask using asyncio.run(), as in the custom webhook bot example provided by the python-telegram-bot dev team.

asyncio.run() starts an event loop and executes the given coroutine until it completes. If there are any asynchronous tasks running before or after the request is handled, those tasks will be executed in a separate event loop.

# Code snippet from https://docs.python-telegram-bot.org/en/v20.6/examples.customwebhookbot.htmlwebserver = uvicorn.Server( config=uvicorn.Config( app=WsgiToAsgi(flask_app), port=PORT, use_colors=False, host="127.0.0.1", ))async with application: await application.start() await webserver.serve() # start bot's webserver await application.stop()

However, this implementation is slightly awkward because Flask is intrinsically incompatible with async globals.

Examples in the documentation are not suitable for production environments.

Using asyncio.run() as an entry point in production is usually not recommended. The asyncio.run() function is designed for development and testing purposes, and it may not provide the same level of robustness and reliability as production servers like Gunicorn or UWSGI.

These production servers offer many additional features, such as logging, monitoring, and health checks, which are essential for ensuring the stability and security of a production application.

If you want to deploy your bot in production, it’s much cleaner to use an ASGI (Asynchronous Server Gateway Interface) with an ASGI web server implementation.

How to Do It — Migration and Deployment

From Flask (WSGI) to FastAPI (AGSI)

Migrating a Flask application to an ASGI is straightforward. I chose FastAPI because I found a comprehensive migration tutorial here. The syntaxes of both frameworks are quite similar, which means you won’t have to make too many code changes.

# From python-telegram-bot v20application = ( Application.builder() .updater(None) .token(<your-bot-token>) # replace <your-bot-token> .read_timeout(7) .get_updates_read_timeout(42) .build())# From FastAPI@asynccontextmanagerasync def lifespan(app: FastAPI): async with application: await application.start() yield await application.stop()

Quart appears to be a feasible alternative, but it does not offer support for deployments using Uvicorn, which is the webserver implementation I was adapting from the script provided by the python-telegram-bot team.

A working example

The following code shows a minimal example that uses FastAPI to build a python-telegram-bot v20 webhook. This bot will respond with “starting…” when it receives the /start command.

# main.pyfrom contextlib import asynccontextmanagerfrom http import HTTPStatusfrom telegram import Updatefrom telegram.ext import Application, CommandHandlerfrom telegram.ext._contexttypes import ContextTypesfrom fastapi import FastAPI, Request, Response# Initialize python telegram botptb = ( Application.builder() .updater(None) .token(<your-bot-token>) # replace <your-bot-token> .read_timeout(7) .get_updates_read_timeout(42) .build())@asynccontextmanagerasync def lifespan(_: FastAPI): await ptb.bot.setWebhook(<your-webhook-url>) # replace <your-webhook-url> async with ptb: await ptb.start() yield await ptb.stop()# Initialize FastAPI app (similar to Flask)app = FastAPI(lifespan=lifespan)@app.post("/")async def process_update(request: Request): req = await request.json() update = Update.de_json(req, ptb.bot) await ptb.process_update(update) return Response(status_code=HTTPStatus.OK)# Example handlerasync def start(update, _: ContextTypes.DEFAULT_TYPE): """Send a message when the command /start is issued.""" await update.message.reply_text("starting...")ptb.add_handler(CommandHandler("start", start))

To start the bot, pip install all required dependencies and run the start command: gunicorn main:app -k uvicorn.workers.UvicornWorker.

This code snippet is adapted from a real Telegram bot in production. Check out the source code for @cron_telebot here to see how it is implemented. Feel free to adapt the script to suit your use case.

Conclusion

In this article, we learnt how to build and deploy a python-telegram-bot v20 webhook.

Hope this tutorial helped you. If you enjoyed this article, please follow me on Medium to show your support.

Thank you for reading!

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

How to Build and Deploy a python-telegram-bot v20 Webhook (3)
Chua Hui Shun

Read more posts.

If this article was helpful, .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

ADVERTIsem*nT

How to Build and Deploy a python-telegram-bot v20 Webhook (2024)

References

Top Articles
Old Fashioned Macaroni and Tomatoes - These Old Cookbooks
Canned Coleslaw?! - Farm Bell Recipes
Funny Roblox Id Codes 2023
Golden Abyss - Chapter 5 - Lunar_Angel
Www.paystubportal.com/7-11 Login
Joi Databas
DPhil Research - List of thesis titles
Shs Games 1V1 Lol
Evil Dead Rise Showtimes Near Massena Movieplex
Steamy Afternoon With Handsome Fernando
Which aspects are important in sales |#1 Prospection
Detroit Lions 50 50
18443168434
Zürich Stadion Letzigrund detailed interactive seating plan with seat & row numbers | Sitzplan Saalplan with Sitzplatz & Reihen Nummerierung
Grace Caroline Deepfake
978-0137606801
Nwi Arrests Lake County
Justified Official Series Trailer
London Ups Store
Committees Of Correspondence | Encyclopedia.com
Pizza Hut In Dinuba
Jinx Chapter 24: Release Date, Spoilers & Where To Read - OtakuKart
How Much You Should Be Tipping For Beauty Services - American Beauty Institute
Free Online Games on CrazyGames | Play Now!
Sizewise Stat Login
VERHUURD: Barentszstraat 12 in 'S-Gravenhage 2518 XG: Woonhuis.
Jet Ski Rental Conneaut Lake Pa
Unforeseen Drama: The Tower of Terror’s Mysterious Closure at Walt Disney World
Ups Print Store Near Me
C&T Wok Menu - Morrisville, NC Restaurant
How Taraswrld Leaks Exposed the Dark Side of TikTok Fame
Dashboard Unt
Access a Shared Resource | Computing for Arts + Sciences
Black Lion Backpack And Glider Voucher
Gopher Carts Pensacola Beach
Duke University Transcript Request
Lincoln Financial Field, section 110, row 4, home of Philadelphia Eagles, Temple Owls, page 1
Jambus - Definition, Beispiele, Merkmale, Wirkung
Netherforged Lavaproof Boots
Ark Unlock All Skins Command
Craigslist Red Wing Mn
D3 Boards
Jail View Sumter
Nancy Pazelt Obituary
Birmingham City Schools Clever Login
Thotsbook Com
Vérificateur De Billet Loto-Québec
Funkin' on the Heights
Vci Classified Paducah
Www Pig11 Net
Ty Glass Sentenced
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 5496

Rating: 4.2 / 5 (63 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.