tgadmin/bot/middlewares/throttling.py
2024-07-25 15:19:15 +03:00

31 lines
866 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from cachetools import TTLCache
from typing import Any, Awaitable, Callable, Dict
from aiogram import BaseMiddleware
from aiogram.types import Message, User
class ThrottlingMiddleware(BaseMiddleware):
throt = TTLCache(maxsize=10_000, ttl=1)
async def __call__(
self,
handler: Callable[[Message, Dict[str, Any]], Awaitable[Any]],
event: Message,
data: Dict[str, Any],
) -> Any:
user: User = data["event_from_user"]
if user.id in self.throt:
count = self.throt[user.id] + 1
self.throt[user.id] = count
if count == 4:
return await data['bot'].send_message(user.id, ('Не спамьте!'))
elif count > 3:
return
else:
self.throt[user.id] = 0
return await handler(event, data)