如何在python-telegram-bot中选择菜单选项后获取用户输入
解决Telegram机器人跟踪用户输入状态的问题
要实现选择菜单后接收用户输入并执行对应运算,核心是跟踪用户当前的交互状态,可以利用CallbackContext.user_data来存储每个用户的状态信息。修改后的代码如下:
from telegram import * from telegram.ext import * from requests import * updater = Updater(token="XXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXX") dispatcher = updater.dispatcher fun_one = "Function One" fun_two = "Function Two" # 定义状态常量,标记用户当前需要输入数值的场景 STATE_WAIT_FUN_ONE_NUM = "wait_fun_one_num" STATE_WAIT_FUN_TWO_NUM = "wait_fun_two_num" allowedUsernames = ['XXX'] def startCommand(update: Update, context: CallbackContext): buttons = [[KeyboardButton(fun_one)], [KeyboardButton(fun_two)]] context.bot.send_message( chat_id=update.effective_chat.id, text="Hi", reply_markup=ReplyKeyboardMarkup(buttons) ) # 启动时清除用户状态,避免遗留 context.user_data.clear() def messageHandler(update: Update, context: CallbackContext): chat_id = update.effective_chat.id username = update.effective_chat.username if username not in allowedUsernames: context.bot.send_message(chat_id=chat_id, text="You are not allowed to use this bot") return # 先检查用户是否处于等待输入数值的状态 current_state = context.user_data.get("state") if current_state == STATE_WAIT_FUN_ONE_NUM: # 处理Function One的数值输入 try: num = float(update.message.text) # 这里写Function One的运算逻辑,比如乘以2 result = num * 2 context.bot.send_message(chat_id=chat_id, text=f"Function One结果:{result}") except ValueError: context.bot.send_message(chat_id=chat_id, text="请输入有效的数字!") # 清除状态,回到初始交互 context.user_data.pop("state", None) return elif current_state == STATE_WAIT_FUN_TWO_NUM: # 处理Function Two的数值输入 try: num = float(update.message.text) # 这里写Function Two的运算逻辑,比如平方 result = num ** 2 context.bot.send_message(chat_id=chat_id, text=f"Function Two结果:{result}") except ValueError: context.bot.send_message(chat_id=chat_id, text="请输入有效的数字!") # 清除状态 context.user_data.pop("state", None) return # 如果用户不在等待状态,处理菜单选择 if fun_one in update.message.text: context.bot.send_message(chat_id=chat_id, text="Please enter a number") # 标记用户状态为等待Function One的数值 context.user_data["state"] = STATE_WAIT_FUN_ONE_NUM elif fun_two in update.message.text: context.bot.send_message(chat_id=chat_id, text="Please enter a number") # 标记用户状态为等待Function Two的数值 context.user_data["state"] = STATE_WAIT_FUN_TWO_NUM dispatcher.add_handler(CommandHandler("start", startCommand)) dispatcher.add_handler(MessageHandler(Filters.text, messageHandler)) updater.start_polling()
关键改动说明:
- 状态管理:用
context.user_data存储用户当前的交互状态(比如等待哪个功能的数值输入),每个用户的状态独立,不会互相干扰。 - 优先级判断:消息处理时先检查用户是否处于等待输入状态,优先处理数值输入,再处理菜单选择。
- 输入校验:用
try-except捕获非数字输入,给出明确提示。 - 状态清除:完成运算后清除用户状态,避免下次交互误触发。
内容的提问来源于stack exchange,提问作者Shwan
相关产品推荐
相关产品推荐

