How do I stop someone spamming inline keyboard of my telegram bot?

Viewed 920

I want to freeze the keyboard buttons for 4 seconds, I don't want to delete the keyboard or make it unuseful forever.The only way I know of acheiving this is storing the time of the consecutive clicks on my database and then using if statement.

if (click_2_time - click_1_time) < 4 : 
   pass
else: 
    //Do sensitive and irreversible operations

^The problem with this is that I am going to have many inline keyboards across multiple groups and using this logic becomes very complicated to keep track of individual keyboards.

Please help me out with an easier solution.

1 Answers

You can store the last timestamp a user has clicked on an inline button inside the button's callback_data.

For example if callback_data: show_message, if user clicks on the button, edit the inline keyboard of the message and change callback_data to show_message:1594922033.

1594922033 is unix timestamp.

Considering 1 clicks allowed per 5 seconds, you're going to split the callback_data by : and then if length of the split equals to 1 then process the request add the timestamp and update message keyboard else if the length is 2, take the second item which is the timestamp and compare it to current timestamp, if their difference is less than 5 seconds you're gonna show an error or just ignore the request. Else you're going to update the timestamp and the keyboard for the message.

current_timestamp = datetime.datetime.now().timestamp()
callback = ...
data = callback.split(":")
if data.len() == 1:
    callback = callback + ":" + str(current_timestamp)
    # process data[0]
    # update message keyboard with current_timestamp
else:
    timestamp = int(data[1])
    if current_timestamp - timestamp > 5:
        # ignore the request or respond with error
    else:
        callback = data[0] + ":" + str(current_timestamp)
        # process data[0]
        # update message keyboard

You're using the keyboard button's callback_data field as your storage this way.

But you have to make sure the length of callback_data does not exceed 64 bytes, according to the documentation.

Related