Python 3.10中telebot callback_query_handler报错的解决方法咨询
解决telebot中callback_query_handler的使用错误
错误原因及修复方案
第一个错误(missing 'self'参数):
你直接通过telebot.TeleBot类调用callback_query_handler装饰器,但这个装饰器是实例方法,必须先创建TeleBot的实例,再通过实例来使用装饰器,不能直接用类调用。正确步骤:
- 先创建TeleBot实例:
import telebot BOT_TOKEN = "你的机器人TOKEN" bot = telebot.TeleBot(BOT_TOKEN)- 通过实例装饰回调函数:
@bot.callback_query_handler(func=lambda call: True) def handle_callback(call): # 处理回调逻辑 bot.answer_callback_query(call.id, text="按钮已触发") bot.send_message(call.message.chat.id, f"你点击了按钮:{call.data}")第二个错误('list' object is not callable):
你误用了callback_query_handlers(复数形式),这个属性是TeleBot实例用来存储所有回调处理器的列表,不是可调用的装饰器函数,必须使用单数形式的callback_query_handler。
完整按钮功能示例
import telebot from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton BOT_TOKEN = "你的机器人TOKEN" bot = telebot.TeleBot(BOT_TOKEN) # 发送带按钮的欢迎消息 @bot.message_handler(commands=['start']) def send_welcome(message): markup = InlineKeyboardMarkup() markup.add(InlineKeyboardButton("测试按钮1", callback_data="btn_test_1")) markup.add(InlineKeyboardButton("测试按钮2", callback_data="btn_test_2")) bot.send_message(message.chat.id, "点击下方按钮测试功能:", reply_markup=markup) # 处理按钮回调 @bot.callback_query_handler(func=lambda call: True) def handle_callback(call): bot.answer_callback_query(call.id, text=f"你触发了{call.data}") bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.id, text=f"已点击按钮:{call.data}") # 启动机器人 bot.polling(none_stop=True)
内容的提问来源于stack exchange,提问作者Аркадий Сергеев
相关产品推荐
相关产品推荐

