I try to create a simple Telegram bot for my school (so students could receive schedule updates in Telegram). I use python-telegram-bot for this. Here is the code I took from the official tutorial:
application = telegram.ext.ApplicationBuilder().token(token).build()
incoming_message_handler = telegram.ext.MessageHandler(
telegram.ext.filters.TEXT & (~telegram.ext.filters.COMMAND),
process_incoming_message
)
start_handler = telegram.ext.CommandHandler(
'start',
process_start_command
)
application.add_handler(start_handler)
application.add_handler(incoming_message_handler)
application.run_polling()
It works fine, but we have not that good internet connection and my bot from time to time crashes with telegram.error.TimedOut.
So I decided to use an infinite loop and a try-except to reconnect:
while True:
try:
application = telegram.ext.ApplicationBuilder().token(token).build()
incoming_message_handler = telegram.ext.MessageHandler(
telegram.ext.filters.TEXT & (~telegram.ext.filters.COMMAND),
process_incoming_message
)
start_handler = telegram.ext.CommandHandler(
'start',
process_start_command
)
application.add_handler(start_handler)
application.add_handler(incoming_message_handler)
application.run_polling()
break # exit the infinite loop
except telegram.error.TimedOut:
print('trying again')
But instead of trying again and again and again I get this error on a second try:
Traceback (most recent call last):
File "bot.py", line 24, in __init__
application.run_polling()
File "~/.local/lib/python3.10/site-packages/telegram/ext/_application.py", line 765, in run_polling
return self.__run(
File "~/.local/lib/python3.10/site-packages/telegram/ext/_application.py", line 939, in __run
loop.add_signal_handler(sig, self._raise_system_exit)
File "/usr/lib/python3.10/asyncio/unix_events.py", line 99, in add_signal_handler
self._check_closed()
File "/usr/lib/python3.10/asyncio/base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
sys:1: RuntimeWarning: coroutine 'Updater.start_polling' was never awaited
2
Answers
The actual error is
So python-telegram-bot library uses asyncio library and closes the event-loop by default and you couldn’t use it again after catching TimedOut exception. Just tell the library not to close the event-loop, change this:
to this:
Edited:
And you can wrap to try-except only that run_polling() calling, no need to wrap the whole code. Good luck!
The error message
Event loop is closed
means that you try to run a coroutine on an event loop which is closed. This can happen if you callapplication.run_polling()
multiple times without first closing the event loop.Updated code: