I need help with connecting a Telegram bot to my Flask web application. I tried using the python-telegram-bot library but ran into problems when deploying to production.
Here’s what I attempted:
First approach: I added the bot directly to my Flask app and used webhooks. This worked fine during development but caused issues in production because I have multiple Gunicorn workers running, and each worker was trying to register its own webhook.
Second approach: I switched to polling and moved the bot to a separate job processor instance. This seemed better at first, but I started getting “Event loop is closed” errors randomly. The bot would work sometimes and fail other times.
Current solution: I ended up creating a separate FastAPI microservice that handles all Telegram communication. This service registers the webhook and talks to my Flask app through API calls.
While the microservice approach is working now, I’m wondering if there’s a simpler way to integrate Telegram bots with Flask applications. Has anyone successfully done this without splitting into separate services?
I’m also curious about:
- Are there non-async Telegram bot libraries that might work better with Flask?
- What’s the best practice for handling webhooks with multiple workers?
- Should I stick with polling or webhooks for production?
Any guidance would be appreciated since I feel like I may have overcomplicated this solution.
Same exact issues here. The webhook registration with multiple workers is a nightmare. I switched to pyTelegramBotAPI (telebot) instead of python-telegram-bot - it’s synchronous so it doesn’t fight with Flask. For production, I run the bot in a separate thread within the same Flask process and use threading.Lock() to stop race conditions. The trick is only handling webhook registration in your main process, not the workers. Check if you’re in the main process by looking at worker ID or using a file lock. This keeps everything in one service without the async headaches.
your microservice approach is solid - don’t overthink it. i’ve run telegram bots with flask for years, and yeah, webhooks + gunicorn workers can be tricky. what works for me: use redis to queue the telegram msgs, then have one worker process them. saves you from all the async headaches.
Had the same issue with my Flask + Telegram bot. Here’s what worked: use webhooks, but don’t let workers register them. I made a startup script that runs once during deployment to set the webhook URL. Workers just handle incoming requests - no registration attempts. Stuck with python-telegram-bot but wrapped everything in a sync interface using asyncio.run() for individual calls. Flask stays synchronous, but you get the full async library features. The trick is treating webhook registration as a deployment step, not something that happens at runtime. Been running stable in production for months.