我正在编写一个 Telegram 机器人,为用户提供按钮选择。我想确保用户从其中一个按钮中进行选择,而不是发送自定义短信或贴纸或其他任何内容。有什么方法可以做到这一点吗?据我从文档中可以看出,我不能。
答案是否定的!我将通过让机器人忽略任何文本输入来处理这个问题,直到用户选择按钮选项之一。
我来这里是为了彻底禁用键盘。但到目前为止,我让机器人告诉用户仅从按钮中进行选择(比忽略随机输入恕我直言更好)。
其他答案都是正确的。您无法隐藏键盘。假设您正在为您的机器人使用
python-telegram-bot
模块,下面是一个忽略用户在对话中随机输入的示例,这可能就是您遇到问题的地方:
(版本为 python-telegram-bot==20.7)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(
"ANSWER ME?!.",
reply_markup=ReplyKeyboardMarkup(
[["my", "allowed", "buttons"]], one_time_keyboard=True
),
)
async def handle_first_question(update: Update, context: CallbackContext) -> int:
# handle allowed input
print(update.message.text)
# go to next state, everything went smoothly
return SECOND_STATE
async def handle_wrong_input(update: Update, context: CallbackContext) -> int:
# ask user to press buttons, show buttons again
await update.message.reply_text(
"I didn't understand that. Please use buttons.",
reply_markup=ReplyKeyboardMarkup(
[["my", "allowed", "button", "values"]], one_time_keyboard=True
),
)
# stay in first state until user gave correct answer
return FIRST_STATE
survey_handler = ConversationHandler(
entry_points=[CommandHandler("start", start)],
states={
FIRST_STATE: [
# handler for allowed values
MessageHandler(
# except only valid keys
filters.Regex("^(my|allowed|button|values)$"),
handle_first_question,
),
# handler that handles invalid replies and catches all inputs that were not caught before
MessageHandler(filters.ALL, handle_wrong_input),
],
SECOND_STATE: [...],
},
)
重要的是正则表达式过滤器,它过滤按钮值,后面跟着接受所有其他输入的处理程序。您在对话处理程序中的每个状态都需要这个。