使用Telegram Bot发送消息时遇AttributeError:'Update'无send_message属性
问题分析与解决
错误原因
你的代码中命令回调函数的参数签名不符合python-telegram-bot新版本(v13+)的规范:
- 新版本中,
CommandHandler的回调函数默认参数顺序是(update, context),而非旧版的(bot, update) - 你定义的
start(bot, update)函数里,第一个参数bot实际被传入了Update对象,第二个参数update是Context对象 - 调用
bot.send_message时,本质是在调用Update对象的方法,因此触发AttributeError: 'Update' object has no attribute 'send_message'
解决方案
方案1:使用官方推荐的新版本写法(推荐)
通过context.bot获取Updater内部创建的Bot实例,无需手动实例化Bot:
from telegram.ext import Updater, CommandHandler def start(update, context): # 通过context获取Bot实例 context.bot.send_message(chat_id=update.message.chat_id, text="Hello") updater = Updater(token='TOKEN') dispatcher = updater.dispatcher command_handler = CommandHandler('start', start) dispatcher.add_handler(command_handler) updater.start_polling()
方案2:保留手动创建的Bot实例
修改回调函数的参数名,避免与全局变量bot重名:
from telegram.ext import Updater, CommandHandler from telegram import Bot # 全局Bot实例 bot = Bot(token='TOKEN') def start(update, context): # 使用全局的Bot实例发送消息 bot.send_message(chat_id=update.message.chat_id, text="Hello") updater = Updater(token='TOKEN') dispatcher = updater.dispatcher command_handler = CommandHandler('start', start) dispatcher.add_handler(command_handler) updater.start_polling()
内容的提问来源于stack exchange,提问作者Sangeeth Karasinghe
相关产品推荐
相关产品推荐

