
    YPi)2                     H   d Z ddlZddlZddlZddlmZmZ ddlmZm	Z	m
Z
mZ 	 ddlmZ dZddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ej4                  dk\  rej6                  Znej:                  ded   fd       Z eed      Z G d dee          Z!y# e$ r dZY tw xY w)zeThis module contains an implementation of the BaseRateLimiter class based on the aiolimiter
library.
    N)AsyncIterator	Coroutine)AnyCallableOptionalUnion)AsyncLimiterTF)	constants)
get_logger)JSONDict)
RetryAfter)BaseRateLimiter)   
   returnc                    K   d  y wN r       R/root/twitch_bot/venv/lib/python3.12/site-packages/telegram/ext/_aioratelimiter.pynull_contextr   1   s     
s   	AIORateLimiter)
class_namec                      e Zd ZdZdZej                  j                  dej                  j                  ddfde	de	de	d	e	d
e
ddfdZddZddZdeee
ef   ddfdZdedeee
ef   dededeeeeeeee   f   f   f   dedeeef   deeeee   f   fdZdedeeeeeeee   f   f   f   dedeeef   dedeeef   dee
   deeeee   f   fdZy) r   ak  
    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 or with
          :paramref:`~telegram.Bot.send_message.allow_paid_broadcast` set to :obj:`True`.

    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.

        .. 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 <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   <   r   overall_max_rateoverall_time_periodgroup_max_rategroup_time_periodmax_retriesr   Nc                 z   t         st        d      |r|rt        ||      | _        nd | _        |r|r|| _        || _        nd| _        d| _        i | _        t        t        j                  j                  d      | _
        || _        t        j                         | _        | j                  j                          y )NzeTo use `AIORateLimiter`, PTB must be installed via `pip install "python-telegram-bot[rate-limiter]"`.max_ratetime_periodr   r"   )AIO_LIMITER_AVAILABLERuntimeErrorr	   r   r   r   r   r
   
FloodLimitPAID_MESSAGES_PER_SECONDr   r    asyncioEventr!   set)selfr$   r%   r&   r'   r(   s         r   __init__zAIORateLimiter.__init__   s     %8   39E)7J:D "&D/*8D ->D##$D &'D#DF*6))BBPQ+
 "-")--/##%r   c                    K   ywzDoes nothing.Nr   r4   s    r   
initializezAIORateLimiter.initialize           c                    K   ywr7   r   r8   s    r   shutdownzAIORateLimiter.shutdown   r:   r;   group_idr	   c                    t        | j                        dkD  r_| j                  j                         j                         D ]4  \  }}||k(  r|j	                  |j
                        s(| j                  |= 6 || j                  vr.t        | j                  | j                        | j                  |<   | j                  |   S )Ni   r*   )	lenr   copyitemshas_capacityr+   r	   r   r   )r4   r>   keylimiters       r   _get_group_limiterz!AIORateLimiter._get_group_limiter   s    
 t##$s* $ 4 4 9 9 ; A A C 2W(?''(8(89,,S1	2 4///-9-- 33.D  * ##H--r   chatgroupallow_paid_broadcastcallback.argskwargsc                    K   dt         t        t        t        t           f   f fd}|r5 j                  4 d {     |        d {   cd d d       d {    S |r j
                  r j
                  n	t               }|r j                  r j                  |      n	t               }	|	4 d {    |4 d {     |        d {   cd d d       d {    cd d d       d {    S 7 7 7 # 1 d {  7  sw Y   y xY w7 [7 R7 E7 77 (# 1 d {  7  sw Y   nxY wd d d       d {  7   y # 1 d {  7  sw Y   y xY ww)Nr   c                  x   K   j                   j                          d {      i  d {   S 7 7 wr   )r!   wait)rK   rJ   rL   r4   s   r   innerz*AIORateLimiter._run_request.<locals>.inner   s;     ))..000!426222 12s   :6:8::)	r   boolr   listr   r   r   r   rF   )
r4   rG   rH   rI   rJ   rK   rL   rP   base_contextgroup_contexts
   `   ```   r   _run_requestzAIORateLimiter._run_request   s:    	3U44>#AB 	3 	3
  (( % %"W}% % % 374;M;M4--T`TbL T11 ''.!^  % % %l % %"W}% % % % %%$% % % %% %$% % % % % % % % % %s  ;EC:ED C<D E C>!AE9D:E=EDEDDDE#D$E(E4D5E<D >E DD	DEEDEED1	%D(&D1	-E4E?E EEEEEendpointdatarate_limit_argsc           	        K   |xs | j                   }d}d}	|j                  d      }
|j                  dd      }|
d}	t        j                  t        t
              5  t        |
      }
ddd       t        |
t              r|
dk  st        |
t              r|
}t        |dz         D ]=  }	 | j                  |	|||||       d{   | j                  j                          c S  y# 1 sw Y   xY w7 .# t        $ r}||k(  rt        j                  d	||
        |j                   j#                         dz   }t        j%                  d|       | j                  j'                          t)        j*                  |       d{  7   Y d}~nd}~ww xY w	 | j                  j                          # | j                  j                          w xY ww)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_idrI   NTr   r"   )rG   rH   rI   rJ   rK   rL   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rangerU   r!   r3   r   _LOGGER	exception_retry_aftertotal_secondsinfoclearr1   sleep)r4   rJ   rK   rL   rV   rW   rX   r(   rH   rG   rZ   rI   iexcrk   s                  r   process_requestzAIORateLimiter.process_request   s    ( &:):):',((9%#xx(>FD   Y7 	#'lG	# w$1GS9Q E{Q' 	.A.!..)=%! /  , ''++-1	.2 C	# 	#  +#%%Dk\_ &  ((6683>H%P''--/mmE***+ + ''++-''++-sz   AGC&(A G)C4C2C4G&C/+G2C44	F=BF FFF0FF0G0GG)r   N)__name__
__module____qualname____doc__	__slots__r
   r/   MESSAGES_PER_SECONDMESSAGES_PER_MINUTE_PER_GROUPfloatra   r5   r9   r=   r   rc   rQ   rF   r   r   r   r   rR   dictrU   r   rn   r   r   r   r   r   9   s   M^I #,"6"6"J"J%& ) 4 4 R R#%!&!& #!& 	!&
 !!& !& 
!&F.5c4+@ .^ .(%% S#t^$% #	%
 3	#sE$$x.:X4Y*Y ZZ[% % S#X% 
tXtH~-	.%:?3	#sE$$x.:X4Y*Y ZZ[? ? S#X	?
 ? 38n? "#? 
tXtH~-	.?r   )"rr   r1   r]   syscollections.abcr   r   typingr   r   r   r   
aiolimiterr	   r-   ImportErrortelegramr
   telegram._utils.loggingr   telegram._utils.typesr   telegram.errorr   telegram.ext._baseratelimiterr   version_infonullcontextr   asynccontextmanagerro   re   ra   r   r   r   r   <module>r      s   &   
 4 1 1"'   . * % 9
 w))L ##d 3  $ X*:
;s_S) s1  "!"s   B B! B!