-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Closed
Description
pyTelegramBotAPI==4.7.1
Termux 0.118
Python 3.11.0
I have a problem with callback_query date. I am trying to create an antiflood_middleware to avoid too many clicks in a short period of time from a user in an InlineKeyboardButton however the callback_query date is always the same no matter how many times I Click the InlineKeyboardButton even after the limitation time is over.
Or perhaps there is something I am doing wrong.
from telebot.asyncio_handler_backends import BaseMiddleware, CancelUpdate
from telebot.async_telebot import AsyncTeleBot
from telebot.util import quick_markup
import asyncio
TOKEN = ''
bot = AsyncTeleBot(TOKEN)
class SimpleMiddleware(BaseMiddleware):
def __init__(self, limit) -> None:
self.last_time = {}
self.limit = limit
self.update_types = ['callback_query']
# Always specify update types, otherwise middlewares won't work
async def pre_process(self, call, data):
if not call.from_user.id in self.last_time:
# User is not in a dict, so lets add and cancel this function
self.last_time[call.from_user.id] = call.message.date
return
if call.message.date - self.last_time[call.from_user.id] < self.limit:
# User is flooding
await bot.send_message(call.from_user.id, 'You are making request too often')
return CancelUpdate()
self.last_time[call.from_user.id] = call.message.date
async def post_process(self, call, data, exception):
pass
bot.setup_middleware(SimpleMiddleware(5))
def markup():
markup = quick_markup({'A': {'callback_data':'A'},
'B': {'callback_data':'B'}
}, row_width=2)
return markup
@bot.message_handler(commands=['start'])
async def send_welcome(message):
await bot.send_message(message.chat.id, "Choose A or B", reply_markup=markup())
@bot.callback_query_handler(func=lambda call: True)
async def callback_query(call):
if call.data == 'A':
await bot.send_message(call.from_user.id, "Answer is A")
elif call.data == 'B':
await bot.send_message(call.from_user.id, "Answer is B")
asyncio.run(bot.polling(skip_pending=True))
Metadata
Metadata
Assignees
Labels
No labels