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

Telegram Bot重启后发送消息失败问题求助(python-telegram-bot)

问题解决方案

核心原因分析

  • application.bot.send_message是异步方法,直接调用不添加await会触发协程未执行的警告,异步函数必须通过await或放入事件循环才能正常执行。
  • 单独用asyncio.run()启动事件循环发送通知,会导致该循环关闭后,python-telegram-bot自身依赖的全局事件循环也被破坏,后续Bot无法正常运行。

正确实现方式

方案一:在Bot启动的异步流程中发送通知

将发送通知的逻辑整合到Bot初始化的异步流程里,复用python-telegram-bot自带的事件循环:

import asyncio
from telegram.ext import ApplicationBuilder

# 从SQLite获取需要通知的用户ID列表(替换为你的实际查询逻辑)
def get_notify_users():
    return [123456, 789012]

async def send_restart_alert(application):
    user_ids = get_notify_users()
    for user_id in user_ids:
        try:
            await application.bot.send_message(chat_id=user_id, text="Bot已重启,所有闹钟配置已加载完成!")
        except Exception as e:
            print(f"给用户{user_id}发送通知失败: {str(e)}")

async def main():
    # 初始化Bot应用
    application = ApplicationBuilder().token("你的Bot令牌").build()

    # 加载数据库中的闹钟配置(你的原有逻辑)
    # load_alarm_configs_from_db()

    # 发送重启通知
    await send_restart_alert(application)

    # 启动Bot
    await application.run_polling()

if __name__ == "__main__":
    asyncio.run(main())

方案二:用Bot内置任务管理发送通知

如果需要在Bot启动后异步发送通知(比如加载配置耗时较长),可以使用Bot的内置任务机制:

import asyncio
from telegram.ext import ApplicationBuilder, ContextTypes

def get_notify_users():
    return [123456, 789012]

async def send_restart_alert(context: ContextTypes.DEFAULT_TYPE):
    user_ids = get_notify_users()
    for user_id in user_ids:
        try:
            await context.bot.send_message(chat_id=user_id, text="Bot已重启,所有闹钟配置已加载完成!")
        except Exception as e:
            print(f"给用户{user_id}发送通知失败: {str(e)}")

async def main():
    application = ApplicationBuilder().token("你的Bot令牌").build()

    # 加载闹钟配置
    # load_alarm_configs_from_db()

    # 创建后台任务发送通知,无需手动管理事件循环
    application.create_task(send_restart_alert(application.context))

    await application.run_polling()

if __name__ == "__main__":
    asyncio.run(main())

关键注意事项

  • 所有调用Telegram Bot API的异步方法,必须在同一个事件循环中执行,不能单独启动新的事件循环。
  • 发送通知时务必添加异常捕获,避免单个用户发送失败导致整个Bot启动流程中断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 11:21:06