Advertisement
Andrexxelles

Untitled

Feb 27th, 2021
989
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. import aioredis
  2. from aiogram import types
  3. from aiogram.dispatcher.handler import CancelHandler, current_handler
  4. from aiogram.dispatcher.middlewares import BaseMiddleware
  5.  
  6.  
  7. def anti_flood(key=1):
  8.     def decorator(func):
  9.         setattr(func, 'throttling_key', key)
  10.         return func
  11.  
  12.     return decorator
  13.  
  14.  
  15. class ThrottlingMiddleware(BaseMiddleware):
  16.     def __init__(self):
  17.         super(ThrottlingMiddleware, self).__init__()
  18.  
  19.     async def on_process_message(self, answer: types.Message, data: dict):
  20.         handler = current_handler.get()
  21.         throttling_key = getattr(handler, 'throttling_key', None)
  22.         redis_rate = await aioredis.create_redis_pool(
  23.             'redis://server:port',
  24.             password='secret'
  25.         )
  26.         if not await redis_rate.exists(answer.chat.id):
  27.             await redis_rate.setex(
  28.                 answer.chat.id,
  29.                 throttling_key,
  30.                 value=''
  31.             )
  32.             redis_rate.close()
  33.             await redis_rate.wait_closed()
  34.             return
  35.         else:
  36.             redis_rate.close()
  37.             await redis_rate.wait_closed()
  38.             await answer.answer('test')
  39.             raise CancelHandler
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement