我尝试为我的学校创建一个简单的 Telegram 机器人(以便学生可以在 Telegram 中接收时间表更新)。我为此使用 python-telegram-bot 。这是我从官方教程中获取的代码:
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()
它工作正常,但我们没有那么好的互联网连接,我的机器人有时会崩溃并出现 telegram.error.TimedOut。
所以我决定使用无限循环和 try- except 来重新连接:
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')
但是我没有一次又一次地尝试,而是在第二次尝试时遇到了这个错误:
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
实际错误是
运行时错误:事件循环已关闭
因此 python-telegram-bot 库使用 asyncio 库并默认关闭事件循环,并且在捕获 TimedOut 异常后无法再次使用它。只需告诉库不要关闭事件循环,更改此:
application.run_polling()
对此:
application.run_polling(close_loop=False)