我试图为我的学校创建一个简单的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

推荐答案

实际的错误是

运行时错误:事件循环已关闭

因此,python-Telegram-bot库默认使用asyncio库并关闭事件循环,在捕获TimedOut异常后不能再次使用它.只需告诉库不要关闭事件循环,将其更改为:

application.run_polling()

对此:

application.run_polling(close_loop=False)

编辑: 您可以包装以进行try --除了Run_Polling()调用之外,不需要包装整个代码.祝好运!

Python相关问答推荐

aiohTTP与pytest的奇怪行为

双情节在单个图上切换-pPython

螺旋桨图上意外颠倒的次y轴

Python:根据创建时间合并两个收件箱

隐藏QComboBox的指示器(qdarkstyle)

Ibis中是否有一个ANY或ANY_UTE表达,可以让我比较子查询返回的一组值中的值?

收件箱转换错误- polars.exceptions. ComputeHelp- pandera(0.19.0b3)带有polars

使文本输入中的文本与标签中的文本相同

如何在图片中找到这个化学测试条?OpenCV精明边缘检测不会绘制边界框

为什么tkinter框架没有被隐藏?

ModuleNotFound错误:没有名为Crypto Windows 11、Python 3.11.6的模块

需要计算60,000个坐标之间的距离

如何在Django基于类的视图中有效地使用UTE和RST HTIP方法?

当我try 在django中更新模型时,模型表单数据不可见

使用Python和文件进行模糊输出

如何使regex代码只适用于空的目标单元格

Maya Python脚本将纹理应用于所有对象,而不是选定对象

在方法中设置属性值时,如何处理语句不可达[Unreacable]";的问题?

如何获取Python synsets列表的第一个内容?

交替字符串位置的正则表达式