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

Python Telegram Bot:如何实现自定义键盘与标准键盘切换

Python Telegram Bot 实现键盘切换的正确方法

要实现「自定义键盘→标准键盘→自定义键盘」的切换流程,核心是主动管理键盘的显示与移除,以下是具体实现方案:

核心逻辑

  • 初始状态发送带自定义键盘的消息
  • 用户选择“Enter a number”时,用ReplyKeyboardRemove移除自定义键盘,让用户使用系统标准键盘输入
  • 收到有效数字后,回复提示并重新发送带自定义键盘的消息,恢复菜单

完整代码示例

from telegram import Update, ReplyKeyboardMarkup, ReplyKeyboardRemove
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes

# 定义自定义菜单键盘
main_keyboard = [["Enter a number", "Other Option"]]
main_markup = ReplyKeyboardMarkup(main_keyboard, resize_keyboard=True)

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 启动机器人时发送初始自定义键盘
    await update.message.reply_text("请选择操作:", reply_markup=main_markup)

async def handle_user_input(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_msg = update.message.text

    # 用户选择输入数字的分支
    if user_msg == "Enter a number":
        # 移除自定义键盘,切换到系统标准键盘
        await update.message.reply_text("请输入一个数字:", reply_markup=ReplyKeyboardRemove())
        # 标记用户当前状态为等待输入数字
        context.user_data["waiting_for_num"] = True
    # 处理用户输入的数字
    elif context.user_data.get("waiting_for_num"):
        if user_msg.isdigit():
            await update.message.reply_text(f"你输入的数字是:{user_msg}")
            # 回复后重新显示自定义键盘
            await update.message.reply_text("请继续选择操作:", reply_markup=main_markup)
            # 重置状态
            context.user_data["waiting_for_num"] = False
        else:
            await update.message.reply_text("请输入有效的数字!")
    # 其他未匹配的输入,重新提示并显示自定义键盘
    else:
        await update.message.reply_text("请选择菜单中的选项:", reply_markup=main_markup)

if __name__ == "__main__":
    # 替换为你的机器人Token
    BOT_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"
    app = ApplicationBuilder().token(BOT_TOKEN).build()

    # 注册命令和消息处理器
    app.add_handler(CommandHandler("start", start))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_user_input))

    app.run_polling()

关键细节说明

  1. 状态跟踪:用context.user_data记录用户当前的操作状态(是否在等待输入数字),避免不同用户的操作互相干扰
  2. 键盘移除:必须使用ReplyKeyboardRemove()主动移除自定义键盘,Telegram不会自动清除之前的键盘设置,发送不带reply_markup的消息无效
  3. one_time_keyboard的局限:该参数仅让键盘在点击后暂时隐藏,用户再次输入时会重新显示,无法实现切换到系统标准键盘的需求
  4. 键盘恢复:收到有效数字后,重新发送带main_markup的消息即可恢复自定义键盘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:45:23