I’m developing a Telegram bot that suggests movies using the python-telegram-bot
library and IMDbPY
. I switched from synchronous to asynchronous code using asyncio
to handle waiting times more efficiently, but I’m encountering the following error:
RuntimeError: This event loop is already running
Additionally, another error occurs when attempting to close the event loop:
RuntimeError: Cannot close a running event loop
I’m using Python 3.12 and asyncio.run(main())
to start the bot. I’m fairly new to asynchronous programming, so I’m not entirely sure how to handle the event loop properly in this context.
The error occurs when I try to run the bot using await application.run_polling()
. My main function is set up with asyncio.run(main())
. Here’s a simplified version of my code:
import asyncio
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters
from imdb import IMDb
async def main():
application = ApplicationBuilder().token("YOUR_BOT_TOKEN").build()
# Handlers
application.add_handler(CommandHandler("start", init))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, genres_selected))
await application.run_polling() # Issue occurs here
await application.idle()
if __name__ == '__main__':
asyncio.run(main())
I understand that asyncio.run()
creates its own event loop, but I’m unsure how to manage this since ApplicationBuilder
uses asyncio
as well.
How can I properly run the bot without encountering this error? Should I avoid using asyncio.run()
with run_polling()
, or is there a better approach to handle async tasks in this situation?
Any insights would be greatly appreciated!
I tried switching from start_polling()
to run_polling()
because I thought this might solve the issue, but the error persisted. I expected the bot to run normally and start polling for messages, but instead, I received the error about the event loop running multiple times.
I’ve looked into solutions like using asyncio.get_event_loop()
but I’m still running into problems with the event loop management.
run_polling
is not a coroutine function and it should not be used within a coroutine function. Moreover, there is no method Application.idle()
– this looks like the updater.idle()
code that was used in python-telegram-bot
versions 13 and older.
Make your main
function a standard, non-coroutine function and call it without asyncio.run
. Remove the await
in front of application.run_polling
. THat should do the trick.
I strongly recommend reading the official resources provided by the PTB team to get familiar with the library.
Disclaimer: I’m currently the maintainer of python-telegram-bot
.