1

I want to create inline button which will be available only for user who entered the command which created associated button For example:


@bot.message_handler(commands=['start'])
def start(message):
    markup = types.InlineKeyboardMarkup(row_width=1) 
    b1 = types.InlineKeyboardButton(text='First option', callback_data='option1') 
    markup.add(b1)
    bot.send_message(message.chat.id, 'Hello! Choose an option', reply_markup=markup)


@bot.callback_query_handler(lambda x: True)
def parsing(callback):
    if callback.data == 'option1':
    #If somebody who didn't send the original command tries to click => False

So in this example if user sends /start command, bot sends message with inline button, but I want to implement logic that only the user who sent /start command will be able to press button in corresponding message

I thought that it could be done using global variable with user id, but it seems to be a poor solution

Nikita
  • 21
  • 1

1 Answers1

0

Yes, you can implement this logic with a variable (technically a global variable). But for more accuracy, you can record registered Inline Keyboard Markups from each user.

users = {}


@bot.message_handler(commands=['start'])
def start(message):
    if message.chat.id not in users.keys():
        users[message.chat.id] = []

    users[message.chat.id].append(message.message_id + 1)

    markup = types.InlineKeyboardMarkup(row_width=1) 
    b1 = types.InlineKeyboardButton(text='First option', callback_data='option1') 
    markup.add(b1)
    bot.send_message(message.chat.id, 'Hello! Choose an option', reply_markup=markup)


@bot.callback_query_handler(lambda x: True)
def parsing(callback):
    if callback.message.chat.id in users.keys() and callback.message.message_id in users[callback.message.chat.id]:
        if callback.data == 'option1':
            print('option1') # Test
        #If somebody who didn't send the original command tries to click => False

Note: This way has a bug. If the user enters another command before the Inline Keyboard Markup response, the returned Inline Keyboard Markup will not be interactive.

pourya90091
  • 106
  • 5