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

Python TeleBot开发Telegram机器人:点击键盘按钮后消息处理器无响应

Python TeleBot 二级消息处理器问题修复

原代码存在的问题

  • 回调处理器@bot.callback_query_handler嵌套在/start的消息处理器内部,TeleBot的装饰器必须全局注册,嵌套写法会导致Bot无法识别这个回调逻辑,所以点击按钮无响应。
  • 变量名笔误:begin.add(namebuttonl)中的namebuttonl应为namebutton。
  • 用户回复处理逻辑错误:嵌套新的message_handler会导致消息处理优先级混乱,无法正确捕获用户点击按钮后的回复。

修复后的完整代码

import telebot
from telebot import types

bot = telebot.TeleBot("你的机器人Token")
name = ""  # 全局变量存储用户输入

@bot.message_handler(content_types=['text'])
def get_text_messages(message):
    if message.text == "/start":
        begin = types.InlineKeyboardMarkup()
        namebutton = types.InlineKeyboardButton(text="Name urself", callback_data="nm")
        begin.add(namebutton)
        bot.send_message(message.from_user.id, "点击按钮开始", reply_markup=begin)

@bot.callback_query_handler(func=lambda call: True)
def handle_callback(call):
    if call.data == "nm":
        # 发送提示消息,并指定下一条消息的处理函数
        msg = bot.send_message(call.from_user.id, "请介绍自己")
        bot.register_next_step_handler(msg, save_user_name)

def save_user_name(message):
    global name
    name = message.text
    bot.send_message(message.from_user.id, f"你输入的内容是:{name}")

bot.polling(none_stop=True, interval=0)

修复逻辑说明

  1. 将回调处理器全局注册,确保Bot能捕获Inline按钮的点击事件。
  2. 使用register_next_step_handler替代嵌套的消息处理器,精准监听用户在点击按钮后的下一条回复。
  3. 修正变量名笔误,确保Inline键盘能正常显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 22:20:09