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

基于Python telebot库实现Telegram机器人内联按钮切换新键盘

实现Inline按钮点击切换键盘的解决方案

核心修改逻辑

  • 给第一个InlineKeyboardButton添加回调标识(callback_data),让机器人能识别点击事件
  • 提前定义好点击后要显示的新键盘
  • 编写回调处理函数,响应点击并替换消息的键盘(或发送新消息)

完整可运行代码

import telebot
from telebot import types

# 替换为你的机器人Token
bot = telebot.TeleBot('你的机器人Token')

# 初始启动键盘
initial_markup = types.InlineKeyboardMarkup()
# 给"Почати"按钮加回调标识,用于触发后续逻辑
initial_markup.add(types.InlineKeyboardButton("Почати", callback_data='open_topic_menu'))
# 请替换成实际的指南链接
initial_markup.add(types.InlineKeyboardButton("Show guide", url="https://你的指南地址.com"))

# 点击"Почати"后显示的主题选择键盘
topic_markup = types.InlineKeyboardMarkup()
topic_markup.add(types.InlineKeyboardButton("Технології", callback_data='topic_tech'))
topic_markup.add(types.InlineKeyboardButton("Спорт", callback_data='topic_sport'))
topic_markup.add(types.InlineKeyboardButton("Політика", callback_data='topic_politics'))

@bot.message_handler(commands=['start'])
def send_welcome(message):
    bot.send_message(
        message.chat.id,
        "Бот буде надсилати вам вибірку найголовніших новин на вибрану вами тему у вибраний час",
        reply_markup=initial_markup
    )

# 处理"Почати"按钮的点击事件
@bot.callback_query_handler(func=lambda call: call.data == 'open_topic_menu')
def switch_to_topic_menu(call):
    # 编辑原消息的内容和键盘,切换到主题选择界面
    bot.edit_message_text(
        chat_id=call.message.chat.id,
        message_id=call.message.message_id,
        text="Оберіть тему новин:",
        reply_markup=topic_markup
    )
    # 必须调用此方法,消除客户端按钮加载状态
    bot.answer_callback_query(call.id)

# 可选:处理主题按钮的点击(示例逻辑)
@bot.callback_query_handler(func=lambda call: call.data.startswith('topic_'))
def handle_topic_choice(call):
    topic_map = {
        'topic_tech': 'Технології',
        'topic_sport': 'Спорт',
        'topic_politics': 'Політика'
    }
    selected_topic = topic_map[call.data]
    
    bot.edit_message_text(
        chat_id=call.message.chat.id,
        message_id=call.message.message_id,
        text=f"Ви обрали {selected_topic}! Далі ми налаштуємо час отримання новин."
    )
    bot.answer_callback_query(call.id)

# 启动机器人
bot.infinity_polling()

关键注意点

  • callback_data要保证唯一,避免不同按钮的回调逻辑冲突
  • 处理完回调必须调用bot.answer_callback_query(call.id),否则用户会看到按钮一直处于加载状态
  • 如果需要保留原启动消息,可以把edit_message_text换成bot.send_message()发送新消息并附带新键盘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:22:42