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
相关产品推荐
相关产品推荐

