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)
Top Articles
How BBC zoologist Adam Britton was exposed as a serial animal abuser
Varieties of Religious Experience - Christian Classics Ethereal Library
Used Trucks for Sale in Oneida, TN (with Photos)
Is Jennifer Coffindaffer Married
Orange County's diverse vegan Mexican food movement gains momentum
T800 Kenworth Fuse Box Diagram
Monster Raider Set
Phun.celeb
"Rainbow Family" will im Harz bleiben: Hippie-Camp bis Anfang September geplant
Stellaris Mid Game
John Chiv Words Worth
Maryse Mizanin Nip Slip
Flappy Bird Cool Math Games
Claims Adjuster: Definition, Job Duties, How To Become One
10 Teacher Tips to Encourage Self-Awareness in Teens | EVERFI
Www Craigslist Antelope Valley
Www.jetnet.aa.com
Labcorp Locations Near Me
Massage Parlor Columbus Ohio
Open jazz : podcast et émission en replay | France Musique
One Piece Chapter 1077 Tcb
Bfri Forum
How To Level Up Intellect Tarkov
Pennys Department Store Near Me
Joanna Gaines Reveals Who Bought the 'Fixer Upper' Lake House and Her Favorite Features of the Milestone Project
Fedex Express Ship Center
Union Supply Direct Wisconsin
Gopher Hockey Forum
Sotyktu Pronounce
Parishes Online Bulletins
Lux Nails Mcmurray Pa
Mrballen Political Views
Cnb Pittsburg Ks
10-Day Weather Forecast for Bratislava, Bratislava, Slovakia - The Weather Channel | weather.com
Phunextra
Tapana Telugu Movie Download Kuttymovies
Vogler Funeral Home At Forsyth Memorial Park
Seller Feedback
Strange World Showtimes Near Andover Cinema
Alineaciones De Rcd Espanyol Contra Celta De Vigo
Meg 2: The Trench Showtimes Near Phoenix Theatres Laurel Park
German American Bank Owenton Ky
Ucla Football 247
Ebony Ts Facials
Sparkle Nails Phillipsburg
Steel Punchings For Sale
Art Labeling Activity The Big Picture Of Nutrient Catabolism — I Hate CBT's
Saulr80683
How a fringe online claim about immigrants eating pets made its way to the debate stage
Craigslist Cars By Owner
Kernersville pastor arrested after police find weapons, body armor and fentanyl in his Las Vegas Hotel room
Tetris Google Sites
Latest Posts
Article information

Author: Arielle Torp

Last Updated:

Views: 5947

Rating: 4 / 5 (41 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Arielle Torp

Birthday: 1997-09-20

Address: 87313 Erdman Vista, North Dustinborough, WA 37563

Phone: +97216742823598

Job: Central Technology Officer

Hobby: Taekwondo, Macrame, Foreign language learning, Kite flying, Cooking, Skiing, Computer programming

Introduction: My name is Arielle Torp, I am a comfortable, kind, zealous, lovely, jolly, colorful, adventurous person who loves writing and wants to share my knowledge and understanding with you.