如何 select 一条来自其他 telebot 的消息?

How to select one message from others telebot?

我正在为一家房地产中介制作一个机器人。 Bot 发送包含有关公寓信息的消息。 Bot 可以一次发送多条消息供用户选择。如何实现 selecting 其中一条消息的过程?当我在一条消息上制作一个内联按钮时,当用户点击它时,由于某种原因,最后一条消息的 id 返回给机器人,也就是说,如果机器人发送了三条带有“select" 按钮,然后当第一个被点击时,最后一个被返回。我想这样做,例如,用户可以回复一条消息,从而 select 一个特定的消息,但我不明白如何将用户的消息和他回复的消息相关联。我怎样才能做得更好?

when the user clicks on it, then for some reason the id of the last message is returned to the bot

这不是预期的行为,如果您要发送 3 条不同的消息,其中包含内联按钮键盘,则在单击任何按钮后,将创建一个新的 callbackquery 更新,其中包含用户单击的消息 ID也在它的按钮上。你应该检查一下以确保。

你需要的是callback_data:

InlineKeyboardButtoncallback_data 字段。那是专门为你的目的而存在的,你可以将 apartment_id 放在 callback_data 中,然后当用户点击任何按钮时,你也会收到 callback_data 并且你会知道apartment_id 用户点击了哪个。

您没有提到您使用的是哪个库,但请检查 example python 中的一个库。

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 1button 函数中的 query 将为“1”。如果他们点击第二个按钮 Option 2,那么您将收到 2 作为 query。现在,您可以存储每个公寓的 ID,而不是 12。如果您有多种用途的按钮,您可以使用短语来区分它们,例如:apartment_id:1close_button。在处理更新时,您可以按 : 拆分查询,如果 split[0]apartment_id 那么您将处理 split[2] 否则您将知道用户点击了其他按钮。

所以callback_data是一个有限的数据库来解决这类问题。