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

Telegram Bot无法发送消息:coroutine 'Bot.send_message'未被await问题

问题排查与解决方法

问题根源

你的代码失效是因为python-telegram-bot库被自动升级到了v13.x及以上版本——该版本彻底切换为异步API,原有的同步方法(如sendMessage)已变为协程函数,直接调用会触发未await的警告,且无法实际执行消息发送。Anaconda更新时可能自动升级了这个依赖库,导致原有同步写法失效。

另外,ChatGPT给出的方案报错是因为Spyder的IPython内核默认已运行一个事件循环,asyncio.run()不允许在已存在的事件循环中嵌套调用。


解决方案

方案1:降级库版本(保留原有同步写法)

如果不想修改代码,直接降级到支持同步API的旧版本:

pip install python-telegram-bot==12.8

安装完成后,你的原有代码即可正常运行。

方案2:适配异步API(兼容新版本)

针对Spyder的环境特性,调整代码如下:

import telegram
import asyncio

TOKEN = "123"
chat_id = "345"

async def send(message, chat_id, token=TOKEN):
    bot = telegram.Bot(token=token)
    # 使用await调用异步方法
    await bot.send_message(chat_id=chat_id, text=message)

message = "Hello world!"
# 利用Spyder已存在的事件循环执行协程
loop = asyncio.get_event_loop()
loop.run_until_complete(send(message, chat_id))

或者,在Spyder的IPython控制台中,可直接简化为:

import telegram

TOKEN = "123"
chat_id = "345"

async def send(message, chat_id, token=TOKEN):
    bot = telegram.Bot(token=token)
    await bot.send_message(chat_id=chat_id, text=message)

message = "Hello world!"
# 直接使用await执行协程
await send(message, chat_id)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:42:45