You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Telegram Bot的application.start()时MessageHandler无法收消息

Python-Telegram-Bot v20 手动启停轮询时消息无法接收问题

我的需求是收到IFTTT消息时抓拍CCTV画面:

  • 使用application.run_polling()时功能完全正常,但该方法会阻塞主线程,我需要让PTB代码能在特定场景下停止
  • 改用start()和stop()手动控制启停、并在中间加入其他长运行代码后,MessageHandler完全接收不到任何消息

我遇到的情况和另一篇Stack Overflow问题类似,但尝试了其中的解决方案后问题依旧。

备注

  • 我参考了PTB官方文档和自定义Webhook机器人示例编写代码,但没有效果
  • 网上大部分telegram.ext.Updater的示例都是v13版本,无法在v20运行,updater.dispatcher这类写法也不适用于当前版本

不工作的核心代码片段

async def main() -> None:
    application = ApplicationBuilder().token(C_TELEGRAM_LOGIN_TOKEN).build()
    chat_handler = MessageHandler(filters.ALL, on_chat)
    application.add_handler(chat_handler)
    print("Telegram bot initialized, will start polling now.")

    vid_read_thread = Thread(target=start_reading_frames)
    vid_read_thread.start()
    async with application:
        await application.initialize()
        await application.updater.initialize()
        await application.start()
        await application.updater.start_polling()
        print("called application.start()")
        ''' cv2's imread and imshow loop '''
        await application.updater.stop_polling()
        await application.stop()

可正常工作但阻塞主线程的代码

vid_read_thread = Thread(target=start_reading_frames)

application = ApplicationBuilder().token(C_TELEGRAM_LOGIN_TOKEN).build()
chat_handler = MessageHandler(filters.ALL, on_chat)
application.add_handler(chat_handler)
vid_read_thread.start()
application.run_polling()

补充:完整代码中main1()是需要修复的函数,我试过用线程和不用线程两种方式运行start_reading_frames;main2()是当前可用但需要替换的函数。

内容的提问来源于stack exchange,提问作者alok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 03:17:17