python-telegram-bot遇TimedOut后重启失败:事件循环关闭及协程未等待
Telegram机器人重启失败(Event loop is closed)解决方法
问题根源
第一次因telegram.error.TimedOut崩溃后,asyncio事件循环已被关闭;第二次创建Application时默认复用该已关闭的循环,导致RuntimeError: Event loop is closed错误,同时未完成的协程引发警告。
解决方案:每次重启创建新事件循环
修改代码,在每次重试时手动创建并设置新的asyncio事件循环,避免复用旧循环,同时在每次循环结束后清理资源:
import asyncio import telegram.ext while True: try: # 创建新的事件循环并设置为当前循环 loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) 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 # 机器人正常退出时终止循环 except telegram.error.TimedOut: print('连接超时,正在尝试重新启动...') finally: # 关闭当前事件循环,清理资源 loop.close()
额外优化
- 可以在
run_polling()中添加timeout参数,调整超时时间适配网络条件 - 增加重试次数限制,避免无限循环:比如设置
retry_count = 5,每次重试递减,到0时退出循环
内容的提问来源于stack exchange,提问作者Irina Shishilova
相关产品推荐
相关产品推荐

