Telegram机器人无法发送消息,报错RuntimeWarning: 协程'Bot.send_message'未被等待
Telegram机器人发送消息报错:RuntimeWarning: coroutine 'Bot.send_message' was never awaited
问题重现
运行代码时出现以下报错,机器人无法发送消息:
RuntimeWarning: coroutine 'Bot.send_message' was never awaited
相关代码:
from telegram import Bot bot_token = 'xxx' chat_id = 'xxx' message = 'TEST' bot = Bot(token=bot_token) bot.send_message(chat_id=chat_id, text=message)
问题原因
从python-telegram-bot v20版本开始,几乎所有API方法都改为异步协程函数。直接调用协程函数不会执行实际逻辑,只会返回一个协程对象,Python因此抛出警告提示你没有等待协程完成。
解决方法
方法1:使用异步函数+await关键字
通过asyncio运行异步函数,在函数内用await等待发送消息的协程完成:
import asyncio from telegram import Bot bot_token = 'xxx' chat_id = 'xxx' message = 'TEST' async def send_telegram_message(): bot = Bot(token=bot_token) await bot.send_message(chat_id=chat_id, text=message) # 运行异步函数 asyncio.run(send_telegram_message())
方法2:使用同步包装器(适合习惯同步代码的场景)
如果不想写纯异步代码,可以用ApplicationBuilder创建应用,通过run_sync方法同步执行异步逻辑:
from telegram.ext import ApplicationBuilder bot_token = 'xxx' chat_id = 'xxx' message = 'TEST' async def send_msg(bot): await bot.send_message(chat_id=chat_id, text=message) # 创建应用并同步运行 app = ApplicationBuilder().token(bot_token).build() app.run_sync(send_msg)
补充说明
如果你的代码基于python-telegram-bot v13或更早版本,同步方法bot.send_message()可以直接使用。但v20+彻底移除了同步API,必须采用异步方式处理。
内容的提问来源于stack exchange,提问作者Angela Argentieri
相关产品推荐
相关产品推荐

