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

Telegram机器人定时发消息异常:仅停止代码时才发送消息

问题原因与修复方案

你的代码存在两个核心问题:

  1. 仅创建了异步任务,但未启动asyncio事件循环,任务一直处于挂起状态,直到程序终止才会被处理。
  2. 使用同步的time.sleep(60)阻塞线程,彻底剥夺了事件循环运行异步任务的机会。

修复后的代码如下:

import asyncio
import telegram
from datetime import datetime

bot_token = 'xxx'
chat_id = 'xxx'

bot = telegram.Bot(token=bot_token)

async def send_message():
    current_time = datetime.now().strftime('%H:%M:%S')
    current_date = datetime.now().strftime('%d/%m/%Y')
    message = f'الوقت الحالي: {current_time}\nالتاريخ الحالي: {current_date}'
    await bot.send_message(chat_id=chat_id, text=message)

async def main():
    while True:
        await send_message()  # 等待消息发送完成后再执行后续逻辑
        await asyncio.sleep(60)  # 异步休眠,不阻塞事件循环

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

关键改动说明:

  • 新增main异步函数,将循环逻辑放入其中,通过asyncio.run()启动事件循环,确保异步任务能被正常调度执行。
  • 用asyncio.sleep(60)替代time.sleep(60),异步休眠不会阻塞事件循环,让发送消息的任务有机会正常运行。
  • 直接await send_message()替代asyncio.create_task(),确保消息发送完成后再进入休眠,避免任务无意义堆积。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 10:12:02