File size: 965 Bytes
054900e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable

from aiogram import BaseMiddleware
from cachetools import TTLCache

from bot.core.config import settings

if TYPE_CHECKING:
    from collections.abc import Awaitable

    from aiogram.types import Chat, TelegramObject


class ThrottlingMiddleware(BaseMiddleware):
    cache: TTLCache[int, Any]

    def __init__(self, rate_limit: float = settings.RATE_LIMIT) -> None:
        self.cache = TTLCache(maxsize=10_000, ttl=rate_limit)

    async def __call__(
        self,
        handler: Callable[[TelegramObject, dict[str, Any]], Awaitable[Any]],
        event: TelegramObject,
        data: dict[str, Any],
    ) -> Any:
        chat: Chat | None = getattr(event, "chat", None)
        if not chat:
            return await handler(event, data)

        if chat.id in self.cache:
            return None
        self.cache[chat.id] = None
        return await handler(event, data)