async def message_throttled(self, message: types.Message, throttled: Throttled): """ Notify user only on first exceed and notify about unlocking only on last exceed :param message: :param throttled: """ handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" # Calculate how many time is left till the block ends delta = throttled.rate - throttled.delta # Prevent flooding if throttled.exceeded_count <= 10: await message.reply( '�е по�пішай, не в�тигаю читати 😔') # Sleep. await asyncio.sleep(delta) # Check lock status thr = await dispatcher.check_key(key) # If current message is not last with current key - do not send message if thr.exceeded_count == throttled.exceeded_count: await message.reply('В�е, дочитав')
async def callback_throttled(self, cb: types.CallbackQuery, throttled: Throttled): """ Notify user only on first exceed and notify about unlocking only on last exceed """ handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_callback" # Calculate how many time is left till the block ends delta = throttled.rate - throttled.delta # Prevent flooding if throttled.exceeded_count <= 3: await cb.answer('Antiflood: Слишком много запросов.') # Sleep. await asyncio.sleep(delta) # Check lock status thr = await dispatcher.check_key(key) # If current message is not last with current key - do not send message if thr.exceeded_count == throttled.exceeded_count: await cb.answer('Unlocked.')
async def message_throttled(self, message: types.Message, throttled: Throttled): """ Notify user only on first exceed and notify about unlocking only on last exceed """ handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, THROTTLING_KEY, f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 2: await message.reply('Too many requests! Don`t flood, please!') await asyncio.sleep(delta) thr = await dispatcher.check_key(key) if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked. You can continue!')
async def on_process_callback_query(self, cb: types.CallbackQuery, data: dict): """ This handler is called when dispatcher receives a message """ # Get current handler handler = current_handler.get() # Get dispatcher from context dispatcher = Dispatcher.get_current() # If handler was configured, get rate limit and key from handler if handler: limit = getattr(handler, 'throttling_rate_limit', self.rate_limit) key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: limit = self.rate_limit key = f"{self.prefix}_callback" # Use Dispatcher.throttle method. try: await dispatcher.throttle(key, rate=limit) except Throttled as t: # Execute action await self.callback_throttled(cb, t) # Cancel current handler raise CancelHandler()
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" # Calculate how many time is left till the block ends delta = throttled.rate - throttled.delta # # Prevent flooding if throttled.exceeded_count <= 2: await bot.send_message( chat_id=message.chat.id, text= f'Команда {message.text} работает 1 раз в {throttled.rate} секунд' ) await message.delete() # Sleep. await asyncio.sleep(delta) # # Check lock status thr = await dispatcher.check_key(key) # If current message is not last with current key - do not send message if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked.')
async def message_throttled(self, message: types.Message, throttled: Throttled): """ Notify user only on first exceed and notify about unlocking only on last exceed :param message: :param throttled: """ handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" # Calculate how many time is left till the block ends delta = throttled.rate - throttled.delta # Prevent flooding if throttled.exceeded_count <= 2: await message.reply('❗️Слишком много запросов. ' 'Подождите еще несколько секунд перед отправкой следующего сообщения.' '\nВ целях предотвращения флуда, бот перестанет отвечать на ваши сообщения ' 'на некоторое время.') # Sleep. await asyncio.sleep(delta) # Check lock status thr = await dispatcher.check_key(key) # If current message is not last with current key - do not send message if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked.')
async def on_process_message(self, message: types.Message, data: dict): """ This handler is called when dispatcher receives a message :param message: :param data: """ # Get current handler handler = current_handler.get() # Get dispatcher from context dispatcher = Dispatcher.get_current() # If handler was configured, get rate limit and key from handler if handler: limit = getattr(handler, "throttling_rate_limit", self.rate_limit) key = getattr(handler, "throttling_key", f"{self.prefix}_{handler.__name__}") else: limit = self.rate_limit key = f"{self.prefix}_message" # Use Dispatcher.throttle method. try: await dispatcher.throttle(key, rate=limit) except Throttled as t: # Execute action await self.message_throttled(message, t) # Cancel current handler raise CancelHandler()
async def message_throttled(self, message: types.Message, throttled: Throttled): """ Notify user only on first exceed and notify about unlocking only on last exceed :param message: :param throttled: """ handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, "throttling_key", f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" # Calculate how many time is left till the block ends delta = throttled.rate - throttled.delta # Prevent flooding if throttled.exceeded_count <= 2: await message.reply("Too many requests! ") # Sleep. await asyncio.sleep(delta) # Check lock status thr = await dispatcher.check_key(key) # If current message is not last with current key - do not send message if thr.exceeded_count == throttled.exceeded_count: await message.reply("Unlocked.")
async def get_userdata(telegram_id: int) -> User: handler = current_handler.get() if handler: attr = getattr(handler, 'userdata_required', False) if attr: # Setting user user, _ = await User.get_or_create(telegram_id=telegram_id) return user
async def on_process_callback_query(self, msg, data): spec = inspect.getfullargspec(current_handler.get()) if 'user' in spec.args: # set user if handler requires it data['user'] = await self.get_user(msg.from_user) if 'language' in spec.args: # set language if handler requires it data['language'] = await self.get_language(msg.from_user)
async def on_process_message(self, message: types.Message, data: dict): handler = current_handler.get() mess = getattr(handler, 'time', self.mess) if mess is True: time = datetime.utcnow() utctime = time.strftime("%H:%M") if "14:00" <= utctime <= "14:20": await message.answer("Идёт бой, ожидайте") raise CancelHandler()
async def on_process_message(message: types.Message, data: dict): handler = current_handler.get() if handler: handler_name = handler.__name__ msg = AsyncMessage( user_id=str(message.from_user.id), message=message.text, intent=handler_name ) await msg.send()
async def on_process_callback_query(query: types.CallbackQuery, data: dict): handler = current_handler.get() if handler: handler_name = handler.__name__ msg = AsyncMessage( user_id=query.from_user.id, message=query.data, intent=handler_name ) await msg.send()
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() logger.debug( f'@{message.from_user.username}:{message.from_user.id} спамит командой {message.text}' ) limit = getattr(handler, 'throttling_rate_limit', self.rate_limit) delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 2: await message.reply(text=throttled_answers_generator(limit=limit)) await asyncio.sleep(delta)
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 2: await message.reply('Too many requests! ') await asyncio.sleep(delta) thr = await dispatcher.check_key(key) if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked.')
async def on_process_message(self, message: types.Message, data: dict): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: limit = getattr(handler, "throttling_rate_limit", self.rate_limit) key = getattr(handler, "throttling_key", f"{self.prefix}_{handler.__name__}") else: limit = self.rate_limit key = f"{self.prefix}_message" try: await dispatcher.throttle(key, rate=limit) except Throttled as t: await self.message_throttled(message, t) raise CancelHandler()
async def message_throttled(self, query: CallbackQuery, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 25: await query.answer('Слишком быстрые клики!') thr = await dispatcher.check_key(key)
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count == 2: await message.reply('Слишком часто! Давай не так быстро') elif throttled.exceeded_count == 2: await message.reply('Все. Больше не отвечу, пока не пройдет 10 сек') await asyncio.sleep(delta) thr = await dispatcher.check_key(key) if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked.')
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 2: await message.reply('Занадто багато запитів. Зачекайте..') await asyncio.sleep(delta) thr = await dispatcher.check_key(key) if thr.exceeded_count == throttled.exceeded_count: await message.reply('Розблоковано.')
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 2: await message.reply('Слишком много запросов! ') await asyncio.sleep(delta) thr = await dispatcher.check_key(key) if thr.exceeded_count == throttled.exceeded_count: await message.reply(f'Заблокировано на {throttled.rate}')
async def _throttle(self, message: Message, data: dict[str]): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: limit = getattr(handler, 'throttling_rate_limit', self.rate_limit) key = getattr(handler, 'throttling_key', f'{self.prefix}_{handler.__name__}') else: limit = self.rate_limit key = f'{self.prefix}_message' try: await dispatcher.throttle(key, rate=limit) except Throttled as throttled: if throttled.exceeded_count <= 2: await message.reply(_('Too many requests!')) raise CancelHandler()
async def message_throttled(self, message: types.Message, throttled: Throttled, data: dict): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 2: logger.debug(f'{key} - Too many requests!') await asyncio.sleep(delta) thr = await dispatcher.check_key(key) if thr.exceeded_count == throttled.exceeded_count: logger.debug(f'Unlocked.{thr} {throttled}') return True
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 2: await message.reply( f"Эту команду можно использовать только один раз в {throttled.rate} секунд. " f"Разблокируется через {delta} секунд.") await asyncio.sleep(delta) thr = await dispatcher.check_key(key) if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked.')
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count == 2: await message.reply( 'Воу-воу, полехче. Расписание меняется не так часто, как ты тычешь в эту кнопку. Используй то, что ты уже имеешь. ' ) elif throttled.exceeded_count == 3: await message.reply( 'Запрос на обновление расписания заблокирован на 3 часа.') await asyncio.sleep(delta)
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 2: service_message = await message.reply('Too many requests! ') await asyncio.sleep(5) await service_message.delete() await message.delete() try: await message.delete() except Exception as err: pass
async def on_process_callback_query(self, query: CallbackQuery, data: dict): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: limit = getattr(handler, 'throttling_rate_limit', self.rate_limit) key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: limit = self.rate_limit key = f"{self.prefix}_message" try: await dispatcher.throttle(key, rate=limit) except Throttled as t: await self.message_throttled(query, t) raise CancelHandler()
async def message_throttled( self, obj: typing.Union[types.Message, types.CallbackQuery], throttled: Throttled, ): """ Notify user only on first exceed and notify about unlocking only on last exceed :param message: :param throttled: """ handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, "throttling_key", f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" # Calculate how many time is left till the block ends delta = throttled.rate - throttled.delta # Prevent flooding if throttled.exceeded_count <= 2: text = "Ану не спамь!" if isinstance(obj, types.Message): await obj.reply(text) else: await obj.answer(text) # Sleep. await asyncio.sleep(delta) # Check lock status thr = await dispatcher.check_key(key) # If current message is not last with current key - do not send message if thr.exceeded_count == throttled.exceeded_count: text = "Открыто" if isinstance(obj, types.Message): await obj.reply(text) else: await obj.answer(text)
async def on_process_message(self, message: types.Message, data: dict): handler = current_handler.get() dispatcher = Dispatcher.get_current() # If handler was configured, get rate limit and key from handler if handler: limit = getattr(handler, 'throttling_rate_limit', self.rate_limit) key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: limit = self.rate_limit key = f"{self.prefix}_message" # Use Dispatcher.throttle method. try: await dispatcher.throttle(key, rate=limit) except Throttled as t: # Execute action await self.message_throttled(message, t) # Cancel current handler raise CancelHandler()
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 2: await message.reply( "Слишком часто пишешь! Могу растроиться и не отвечать") elif throttled.exceeded_count == 3: await message.reply( "Достаточно. Я помолчу 10 секунд,пока не научишься манерам!") await asyncio.sleep(delta) thr = await dispatcher.check_key(key) if thr.exceeded_count == throttled.exceeded_count: await message.reply("Разблокирован")
async def message_throttled(self, message: types.Message, throttled: Throttled): handler = current_handler.get() dispatcher = Dispatcher.get_current() if handler: key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}") else: key = f"{self.prefix}_message" delta = throttled.rate - throttled.delta if throttled.exceeded_count <= 2: seconds = round(delta) comment = morph.parse('секунда')[0] word = comment.make_agree_with_number(seconds).word await message.reply(f'Много обращений\n' f'Ожидайте {seconds} {word}') await asyncio.sleep(delta) thr = await dispatcher.check_key(key) if thr.exceeded_count == throttled.exceeded_count: await message.reply('Unlocked.')