I’m working on a Telegram bot and encountering an issue with the run_polling() method. When I execute my bot function, it seemingly halts everything, preventing any subsequent code from running. Here’s my current implementation:
I’ve explored various methods to terminate the polling, but nothing proves successful. The core problem is that any code placed after start_telegram_bot() fails to execute due to the polling locking the program in that loop. What’s the correct way to exit the polling so that other parts of my code can run?
The problem is that run_polling() blocks by design. Don’t try to exit from it - instead, run run_polling(stop_signals=None) in a separate thread or switch to async with run_polling() wrapped in an asyncio task. I ran into the same issue building a bot that needed to do other stuff at the same time. What worked for me was restructuring to use Application.run_polling() with proper signal handling, or building a custom polling loop with start_polling() and idle() separately. That gives you way more control over stopping the bot. You could also try run_webhook() if it fits your setup - webhooks don’t block like polling does.
Your shutdown logic has problems that stop proper termination. The issue is run_polling() runs forever until it gets signals like SIGTERM or SIGINT. Don’t manually call bot_app.stop() in your shutdown handler - use Application.stop_running() instead since it gracefully exits the polling loop. Also ditch the Updater.shutdown() call - it’s deprecated in newer versions. Just modify your shutdown handler to call await bot_app.stop_running() after sending the message. This tells the app to finish its current polling cycle and exit cleanly so any code after run_polling() can actually run. I had the same blocking issues until I switched to this method.
you’re kinda mixing up the shutdown logic. the run_polling() method blocks by design - that’s totally normal. if you need code to run after the bot stops, try using a try/finally block or the post_stop callback param. or just wrap everything in asyncio for better control!