
    Yi-                     <   S r SSKrSSKrSSKrSSKJrJr  SSKJrJ	r	J
r
Jr   SSKJr  SrSSKJr  SS	KJr  SS
KJr  SSKJr  \R0                  S:  a  \R2                  rO\R6                  S\S   4S j5       r\" \SS9r " S S\\   5      rg! \ a    Sr Nnf = f)zeThis module contains an implementation of the BaseRateLimiter class based on the aiolimiter
library.
    N)AsyncIterator	Coroutine)AnyCallableOptionalUnion)AsyncLimiterTF)
get_logger)JSONDict)
RetryAfter)BaseRateLimiter)   
   returnc                    #    S 7v   g 7fN r       G/app/.venv/lib/python3.13/site-packages/telegram/ext/_aioratelimiter.pynull_contextr   /   s
     
s   	AIORateLimiter)
class_namec                   j   \ rS rSrSrSr     SS\S\S\S\S\S	S
4S jjrSS jr	SS jr
S\\\\4   S	S4S jrS\S\\\\4   S\S\\\\\\\\   4   4   4   S\S\\\4   S	\\\\\   4   4S jrS\S\\\\\\\\   4   4   4   S\S\\\4   S\S\\\4   S\\   S	\\\\\   4   4S jrSrg
)r   7   a  
Implementation of :class:`~telegram.ext.BaseRateLimiter` using the library
`aiolimiter <https://aiolimiter.readthedocs.io/en/stable>`_.

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.

Tip:
    With `Bot API 7.1 <https://core.telegram.org/bots/api-changelog#october-31-2024>`_
    (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.

    .. caution::
        This class currently doesn't take the
        :paramref:`~telegram.Bot.send_message.allow_paid_broadcast` parameter into account.
        This means that the rate limiting is applied just like for any other message.

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 <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 ``30``.
    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 20.
    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``.

)_base_limiter_group_limiters_group_max_rate_group_time_period_max_retries_retry_after_eventoverall_max_rateoverall_time_periodgroup_max_rategroup_time_periodmax_retriesr   Nc                 L   [         (       d  [        S5      eU(       a  U(       a  [        XS9U l        OS U l        U(       a  U(       a  X0l        X@l        OSU l        SU l        0 U l        XPl        [        R                  " 5       U l
        U R                  R                  5         g )NzeTo use `AIORateLimiter`, PTB must be installed via `pip install "python-telegram-bot[rate-limiter]"`.max_ratetime_periodr   )AIO_LIMITER_AVAILABLERuntimeErrorr	   r   r   r   r   r   asyncioEventr    set)selfr!   r"   r#   r$   r%   s         r   __init__AIORateLimiter.__init__   s     %$8   39E):D "&D/*8 ->##$D &'D#DF!,")--/##%r   c                    #    g7fzDoes nothing.Nr   r/   s    r   
initializeAIORateLimiter.initialize           c                    #    g7fr3   r   r4   s    r   shutdownAIORateLimiter.shutdown   r7   r8   group_idr	   c                    [        U R                  5      S:  ag  U R                  R                  5       R                  5        H;  u  p#X!:X  a  M  UR	                  UR
                  5      (       d  M.  U R                  U	 M=     XR                  ;  a+  [        U R                  U R                  S9U R                  U'   U R                  U   $ )Ni   r'   )	lenr   copyitemshas_capacityr(   r	   r   r   )r/   r<   keylimiters       r   _get_group_limiter!AIORateLimiter._get_group_limiter   s    
 t##$s* $ 4 4 9 9 ; A A C?''(8(899,,S1	 !D ///-9-- 33.D  * ##H--r   chatgroupcallback.argskwargsc                 D  #    U(       a  U R                   (       a  U R                   O	[        5       nU(       a"  U R                  (       a  U R                  U5      O	[        5       nU IS h  vN   U IS h  vN   U R                  R                  5       I S h  vN   U" U0 UD6I S h  vN sS S S 5      IS h  vN   sS S S 5      IS h  vN   $  Nc NZ N: N, N N! , IS h  vN  (       d  f       O= fS S S 5      IS h  vN    g ! , IS h  vN  (       d  f       g = f7fr   )r   r   r   rD   r    wait)r/   rF   rG   rH   rI   rJ   base_contextgroup_contexts           r   _run_requestAIORateLimiter._run_request   s      /3t7I7It))P\P^.38L8LD##E*R^R` 	 !=,,))..000!42622	 #/,,===,02	 #/=,,,======s   A(D *C+D .D5C6D9CCC'C(C+D7C8D<D C	D DCCDD C1	 C#!C1	-D4D ?D D DDDD endpointdatarate_limit_argsc           	        #    U=(       d    U R                   nSnSn	UR                  S5      n
U
b  Sn	[        R                  " [        [
        5         [        U
5      n
SSS5        [        U
[        5      (       a  U
S:  d  [        U
[        5      (       a  U
n[        US-   5       H7  n U R                  XXUS9I Sh  vN U R                  R                  5         s  $    g! , (       d  f       N= f N4! [         a  nX:X  a  [        R                  SX|S	9  e UR                   S
-   n[        R#                  SU5        U R                  R%                  5         [&        R(                  " U5      I Sh  vN     SnAOSnAff = f U R                  R                  5         M  ! U R                  R                  5         f = f7f)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`.
Fchat_idNTr      )rF   rG   rH   rI   rJ   z*Rate limit hit after maximum of %d retries)exc_infog?z)Rate limit hit. Retrying after %f seconds)r   get
contextlibsuppress
ValueError	TypeErrorint
isinstancestrrangerO   r    r.   r   _LOGGER	exceptionretry_afterinfoclearr,   sleep)r/   rH   rI   rJ   rQ   rR   rS   r%   rG   rF   rU   iexcrf   s                 r   process_requestAIORateLimiter.process_request   s    ( &:):):',((9%D   Y7'lG 8 w$$1GS9Q9Q E{Q'A.!..XQW /  " ''++-' (( 9 87  +#%%Dk &  #-H%P''--/mmE***+ + ''++-''++-sz   AF?C!AF?)C4=C2>C4 F?!
C/+F?2C44
F >A2E;0E31E;6F ;F  F F? F<<F?)   rV      <   r   )r   N)__name__
__module____qualname____firstlineno____doc__	__slots__floatr]   r0   r5   r:   r   r_   boolrD   r   r   r   r   listdictrO   r   ri   __static_attributes__r   r   r   r   r   7   s   KZI #%%& "#%&& #& 	&
 !& & 
&@.5c4+@ .^ .(33 S#t^$3 3	#sE$$x.:X4Y*Y ZZ[	3
 3 S#X3 
tXtH~-	.3(93	#sE$$x.:X4Y*Y ZZ[9 9 S#X	9
 9 38n9 "#9 
tXtH~-	.9r   ) rr   r,   rY   syscollections.abcr   r   typingr   r   r   r   
aiolimiterr	   r*   ImportErrortelegram._utils.loggingr
   telegram._utils.typesr   telegram.errorr   telegram.ext._baseratelimiterr   version_infonullcontextr   asynccontextmanagerrn   ra   r]   r   r   r   r   <module>r      s   &   
 4 1 1"'  / * % 9
 w))L ##d 3  $ X*:
;^_S) ^/  "!"s   B BB