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

Python RuntimeWarning报错求助:协程sendToBot未被等待

问题

重新安装Python环境后,出现如下RuntimeWarning报错:

RuntimeWarning: coroutine 'sendToBot' was never awaited
  sendToBot(message + " --",bot_id ,chat_id)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

对应的代码片段:

async def sendToBot(message,bot_id,chat_id):
    bot = telegram.Bot(token=bot_id)
    chat_id=chat_id 
    try:
        await bot.sendMessage(chat_id=chat_id, text=message)
        time.sleep(5)
    except Exception as Err:
        print("Error, bot_id : " + bot_id + " channel_id : " + chat_id)
        print(Err)

之前版本代码可正常运行,但无法恢复旧代码,询问如何解决,是否需要安装旧版telegram-bot?

解决方案

不需要安装旧版telegram-bot,问题出在异步函数的调用和使用方式上,修复步骤如下:

  • 正确调用异步协程函数:sendToBot是用async定义的异步协程,直接调用只会创建协程对象不会执行,必须用await触发执行:

    • 如果调用它的代码本身也是异步函数,直接在调用前加await:
      await sendToBot(message + " --", bot_id, chat_id)
      
    • 如果是在同步代码里调用,需要通过事件循环运行:
      import asyncio
      asyncio.run(sendToBot(message + " --", bot_id, chat_id))
      
  • 替换同步休眠为异步延迟:异步函数里使用time.sleep会阻塞整个事件循环,导致其他异步任务无法执行,应该换成asyncio.sleep:
    修改代码中的time.sleep(5)为:

    await asyncio.sleep(5)
    

    记得在代码顶部导入asyncio模块。

内容的提问来源于stack exchange,提问作者Oktorio R.P

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 02:02:19