当用户点击它时,由于某种原因,最后一个的 id
消息返回给机器人
这不是预期的行为,如果您发送 3 条包含内联按钮键盘的不同消息,则单击任何按钮后,将创建一个新的 callbackquery 更新,其中包含用户单击其按钮的消息 ID好。您应该检查一下以确保。
你需要的是callback_data:
InlineKeyboardButton 有 callback_data 字段。这是专门为您的目的而存在的,您可以将 apartment_id 放在 callback_data 中,然后当用户单击任何按钮时,您还将收到 callback_data 并且您将知道用户单击了哪个 apartment_id开。
你没有提到你使用哪个库,但是在 python 中的一个库上查看这个example。
def start(update: Update, context: CallbackContext) -> None:
keyboard = [
[
InlineKeyboardButton("Option 1", callback_data='1'),
InlineKeyboardButton("Option 2", callback_data='2'),
],
[InlineKeyboardButton("Option 3", callback_data='3')],
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('Please choose:', reply_markup=reply_markup)
def button(update: Update, context: CallbackContext) -> None:
query = update.callback_query
# CallbackQueries need to be answered, even if no notification to the user is needed
# Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
query.answer()
query.edit_message_text(text="Selected option: {}".format(query.data))
def main():
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CallbackQueryHandler(button))
在示例中,如果用户单击第一个按钮Option 1,则button 函数内的query 将为“1”。如果他们点击第二个按钮Option 2,那么您将收到2 作为query。现在,您可以存储每个公寓的 ID,而不是 1 和 2。如果您有多种用途的按钮,您可以使用以下短语来区分它们:apartment_id:1 或 close_button。在处理更新时,您可以通过: 拆分查询,如果split[0] 是apartment_id,那么您将处理split[2],否则您将知道用户点击了其他按钮。
所以callback_data 是一个有限的数据库作为此类问题的解决方案。