L i)2HdZddlZddlZddlZddlmZmZddlmZm Z m Z m Z  ddl m Z dZddlmZdd lmZdd lmZdd lmZdd lmZej4d k\r ej6Znej:dedfdZeedZGddee Z!y#e$rdZYtwxYw)zeThis module contains an implementation of the BaseRateLimiter class based on the aiolimiter library. N) AsyncIterator Coroutine)AnyCallableOptionalUnion) AsyncLimiterTF) constants) get_logger)JSONDict) RetryAfter)BaseRateLimiter) returncKdywNrb/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/telegram/ext/_aioratelimiter.py null_contextr1s  s AIORateLimiter) class_nameceZdZdZdZej jdej jddfde de de d e d e d d f d Z ddZ ddZ deee efd dfdZdedeee efdededeeeeeeeefffdedeeefd eeeeeffdZdedeeeeeeeefffdedeeefdedeeefdee d eeeeeffdZy ) rak Implementation of :class:`~telegram.ext.BaseRateLimiter` using the library `aiolimiter `_. Important: If you want to use this class, you must install PTB with the optional requirement ``rate-limiter``, i.e. .. code-block:: bash pip install "python-telegram-bot[rate-limiter]" The rate limiting is applied by combining two levels of throttling and :meth:`process_request` roughly boils down to:: async with group_limiter(group_id): async with overall_limiter: await callback(*args, **kwargs) Here, ``group_id`` is determined by checking if there is a ``chat_id`` parameter in the :paramref:`~telegram.ext.BaseRateLimiter.process_request.data`. The ``overall_limiter`` is applied only if a ``chat_id`` argument is present at all. Attention: * Some bot methods accept a ``chat_id`` parameter in form of a ``@username`` for supergroups and channels. As we can't know which ``@username`` corresponds to which integer ``chat_id``, these will be treated as different groups, which may lead to exceeding the rate limit. * As channels can't be differentiated from supergroups by the ``@username`` or integer ``chat_id``, this also applies the group related rate limits to channels. * A :exc:`~telegram.error.RetryAfter` exception will halt *all* requests for :attr:`~telegram.error.RetryAfter.retry_after` + 0.1 seconds. This may be stricter than necessary in some cases, e.g. the bot may hit a rate limit in one group but might still be allowed to send messages in another group or with :paramref:`~telegram.Bot.send_message.allow_paid_broadcast` set to :obj:`True`. Tip: With `Bot API 7.1 `_ (PTB v27.1), Telegram introduced the parameter :paramref:`~telegram.Bot.send_message.allow_paid_broadcast`. This allows bots to send up to :tg-const:`telegram.constants.FloodLimit.PAID_MESSAGES_PER_SECOND` messages per second by paying a fee in Telegram Stars. .. versionchanged:: 21.11 This class automatically takes the :paramref:`~telegram.Bot.send_message.allow_paid_broadcast` parameter into account and throttles the requests accordingly. Note: This class is to be understood as minimal effort reference implementation. If you would like to handle rate limiting in a more sophisticated, fine-tuned way, we welcome you to implement your own subclass of :class:`~telegram.ext.BaseRateLimiter`. Feel free to check out the source code of this class for inspiration. .. seealso:: :wiki:`Avoiding Flood Limits ` .. versionadded:: 20.0 Args: overall_max_rate (:obj:`float`): The maximum number of requests allowed for the entire bot per :paramref:`overall_time_period`. When set to 0, no rate limiting will be applied. Defaults to :tg-const:`telegram.constants.FloodLimit.MESSAGES_PER_SECOND`. overall_time_period (:obj:`float`): The time period (in seconds) during which the :paramref:`overall_max_rate` is enforced. When set to 0, no rate limiting will be applied. Defaults to ``1``. group_max_rate (:obj:`float`): The maximum number of requests allowed for requests related to groups and channels per :paramref:`group_time_period`. When set to 0, no rate limiting will be applied. Defaults to :tg-const:`telegram.constants.FloodLimit.MESSAGES_PER_MINUTE_PER_GROUP`. group_time_period (:obj:`float`): The time period (in seconds) during which the :paramref:`group_max_rate` is enforced. When set to 0, no rate limiting will be applied. Defaults to ``60``. max_retries (:obj:`int`): The maximum number of retries to be made in case of a :exc:`~telegram.error.RetryAfter` exception. If set to 0, no retries will be made. Defaults to ``0``. ) _apb_limiter _base_limiter_group_limiters_group_max_rate_group_time_period _max_retries_retry_after_event<roverall_max_rateoverall_time_periodgroup_max_rategroup_time_period max_retriesrNczts td|r|rt|||_nd|_|r|r||_||_nd|_d|_i|_ttjjd|_ ||_ tj|_|jjy)NzeTo use `AIORateLimiter`, PTB must be installed via `pip install "python-telegram-bot[rate-limiter]"`.max_rate time_periodrr")AIO_LIMITER_AVAILABLE RuntimeErrorr rrrrr FloodLimitPAID_MESSAGES_PER_SECONDrr asyncioEventr!set)selfr$r%r&r'r(s r__init__zAIORateLimiter.__init__s%8   39E)7J:D "&D  /*8D ->D ##$D &'D #DF*6))BBPQ+ "-")--/ ##%rc Kywz Does nothing.Nrr4s r initializezAIORateLimiter.initializec Kywr7rr8s rshutdownzAIORateLimiter.shutdownr:r;group_idr ct|jdkDr_|jjjD]4\}}||k(r |j |j s(|j|=6||jvr.t |j|j|j|<|j|S)Nir*) lenrcopyitems has_capacityr+r rr)r4r>keylimiters r_get_group_limiterz!AIORateLimiter._get_group_limiters t## $s * $ 4 4 9 9 ; A A C 2 W(?''(8(89,,S1  2 4// /-9-- 33.D  *##H--rchatgroupallow_paid_broadcastcallback.argskwargscKdtttttfffd }|r5j4d{|d{cdddd{S|rj r j n t }|rjrj|n t } | 4d{|4d{|d{cdddd{cdddd{S777#1d{7swYyxYw7[7R7E777(#1d{7swYnxYwdddd{7y#1d{7swYyxYww)NrcxKjjd{id{S77wr)r!wait)rKrJrLr4srinnerz*AIORateLimiter._run_request..inners;))..0 0 0!42622 2 12s:6:8::) rboolr listrrrrrF) r4rGrHrIrJrKrLrP base_context group_contexts ` ``` r _run_requestzAIORateLimiter._run_requests: 3U44>#AB 3 3 (( % %"W} % % %374;M;M4--T`TbLT11''.!^  % % %l % %"W} % % % % % %$ % % % % % %$ % % % % % % % % % %s;EC:E DC<D E C>!AE9D:E=EDE DDD E#D$E( E4D5E<D>EDD DEEDEED1 %D(&D1 -E4 E?EEE E EEendpointdatarate_limit_argsc K|xs |j}d}d} |jd} |jdd} | d} tjtt 5t | } dddt| t r| dkst| tr| }t|dzD]=} |j| || |||d{|jjcSy#1swYxYw7.#t$r} | |k(rtjd || | j j#d z}tj%d ||jj't)j*|d{7Yd} ~ nd} ~ wwxYw |jj #|jjwxYww) a Processes a request by applying rate limiting. See :meth:`telegram.ext.BaseRateLimiter.process_request` for detailed information on the arguments. Args: rate_limit_args (:obj:`None` | :obj:`int`): If set, specifies the maximum number of retries to be made in case of a :exc:`~telegram.error.RetryAfter` exception. Defaults to :paramref:`AIORateLimiter.max_retries`. Fchat_idrINTrr")rGrHrIrJrKrLz*Rate limit hit after maximum of %d retries)exc_infog?z)Rate limit hit. Retrying after %f seconds)r get contextlibsuppress ValueError TypeErrorint isinstancestrrangerUr!r3r _LOGGER exception _retry_after total_secondsinfoclearr1sleep)r4rJrKrLrVrWrXr(rHrGrZrIiexcrks rprocess_requestzAIORateLimiter.process_requests(&:):): ',((9%#xx(>F  D Y 7 #'lG # w $1GS9QE{Q' .A .!..)=%! /,''++-1 .2C # # + #%%Dk\_&((6683> H%P''--/mmE*** ++''++-''++-szAG C&(AG)C4C2C4G&C/+G2C44 F=BF FF F0 FF0G0G  G)rN)__name__ __module__ __qualname____doc__ __slots__r r/MESSAGES_PER_SECONDMESSAGES_PER_MINUTE_PER_GROUPfloatrar5r9r=rrcrQrFrrrr rRdictrUrrnrrrrr9sM^I#,"6"6"J"J%& ) 4 4 R R#% !&!&#!& !& ! !&  !& !&F.5c4+@.^.(%%S#t^$%# % 3 #sE$$x.:X4Y*Y ZZ[ %  %S#X% tXtH~- .%:?3 #sE$$x.:X4Y*Y ZZ[??S#X ?  ? 38n ?"#? tXtH~- .?r)"rrr1r]syscollections.abcrrtypingrrrr aiolimiterr r- ImportErrortelegramr telegram._utils.loggingr telegram._utils.typesr telegram.errorr telegram.ext._baseratelimiterr version_info nullcontextrasynccontextmanagerrorerarrrrrs& 411"' .*%9 w))L## d 3$ X*: ;s_S)s1"!"sBB! B!