我试图为我的学校创建一个简单的Telegram机器人(这样学生就可以用Telegram接收时间表更新).我用python-telegram-bot来做这个.以下是我从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()
它工作得很好,但我们没有那么好的互联网连接,我的机器人不时地崩溃与telegram.error.TimedOut.
因此,我决定使用无限循环并try --除了重新连接:
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')
但是,我没有一次又一次地try ,而是在第二次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