
    i/+                     B   d Z ddlZddlZddlZddlmZmZmZmZm	Z	m
Z
mZmZ 	 ddlmZ dZn# e$ r dZY nw xY wddlmZ ddlmZ dd	lmZ dd
lmZ ej        dk    rej        Znej        ded         fd            Z eed          Z G d dee                   Z dS )zeThis module contains an implementation of the BaseRateLimiter class based on the aiolimiter
library.
    N)AnyAsyncIteratorCallable	CoroutineDictListOptionalUnion)AsyncLimiterTF)
get_logger)JSONDict)
RetryAfter)BaseRateLimiter)   
   returnc                    K   d W V  d S N r       b/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/telegram/ext/_aioratelimiter.pynull_contextr   .   s      





r   AIORateLimiter)
class_namec                      e Zd ZdZdZ	 	 	 	 	 d 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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dS )"r   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.

    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         <   r   overall_max_rateoverall_time_periodgroup_max_rategroup_time_periodmax_retriesr   Nc                 6   t           st          d          |r|rt          ||          | _        nd | _        |r|r|| _        || _        nd| _        d| _        i | _        || _        t          j	                    | _
        | j
                                         d S )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__zAIORateLimiter.__init__   s     % 	8    	& 3 	&9E)7J: : :D "&D 	(/ 	(*8D ->D###$D &'D#DF!,")-//##%%%%%r   c                 
   K   dS zDoes nothing.Nr   r4   s    r   
initializezAIORateLimiter.initialize   
        r   c                 
   K   dS r7   r   r8   s    r   shutdownzAIORateLimiter.shutdown   r:   r   group_idr   c                 X   t          | j                  dk    rZ| j                                                                        D ].\  }}||k    r|                    |j                  r| j        |= /|| 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 9 9 ; ; A A C C 2 2W(??''(899 2,S14///-9- 3. . .D * #H--r   chatgroupcallback.argskwargsc                   K   |r| j         r| j         nt                      }|r| j        r|                     |          nt                      }|4 d {V  |4 d {V  | j                                         d {V   ||i | d {V cd d d           d {V  cd d d           d {V  S # 1 d {V swxY w Y   d d d           d {V  d S # 1 d {V swxY w Y   d S r   )r   r   r   rE   r!   wait)r4   rF   rG   rH   rI   rJ   base_contextgroup_contexts           r   _run_requestzAIORateLimiter._run_request   sc      /3^t7I^t))P\P^P^.3`8L`D##E***R^R`R` 	 ! 	3 	3 	3 	3 	3 	3 	3 	3, 	3 	3 	3 	3 	3 	3 	3 	3)..000000000!42622222222		3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3s6   	C-B0C0
B:	:C=B:	>C
C!Cendpointdatarate_limit_argsc                   K   |p| j         }d}d}	|                    d          }
|
d}	t          j        t          t
                    5  t          |
          }
ddd           n# 1 swxY w Y   t          |
t                    r|
dk     st          |
t                    r|
}t          |dz             D ]}	 | 
                    |	||||           d{V 	 | j                                         c S # t          $ r}||k    rt                              d||	           ||j        d
z   }t                              d|           | j                                         t'          j        |           d{V  Y d}~nd}~ww xY w	 | j                                         # | j                                         w xY wdS )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   r#   )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!   r3   r   _LOGGER	exceptionretry_afterinfoclearr1   sleep)r4   rH   rI   rJ   rP   rQ   rR   r*   rG   rF   rT   iexcrd   s                 r   process_requestzAIORateLimiter.process_request   sf     ( &:):',((9%%D  Y77 	# 	#'llG	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# 	# w$$ 	1GS9Q9Q E{Q'' 	. 	.A.!..UXDQW /         " '++------  + + +##%%Dk\_ &    I#-H%PPP'--///mE**************+ + '++----'++----ts=   A$$A(+A(7C33
F=A=E?:F"?FF""F=)r"   r#   r$   r%   r   )r   N)__name__
__module____qualname____doc__	__slots__floatr[   r5   r9   r<   r
   r]   boolrE   r   r   r   r   r   r   rO   r	   rg   r   r   r   r   r   6   s       > >@I #%%& "#%& && #& 	&
 !& & 
& & & &@      .5c4+@ .^ . . . .(33 S#t^$3 3	#sE$$x.:X4Y*Y ZZ[	3
 3 S#X3 
tXtH~-	.3 3 3 3(93	#sE$$x.:X4Y*Y ZZ[9 9 S#X	9
 9 38n9 "#9 
tXtH~-	.9 9 9 9 9 9r   )!rk   r1   rW   systypingr   r   r   r   r   r   r	   r
   
aiolimiterr   r/   ImportErrortelegram._utils.loggingr   telegram._utils.typesr   telegram.errorr   telegram.ext._baseratelimiterr   version_infonullcontextr   asynccontextmanagerrh   r_   r[   r   r   r   r   <module>rz      s  &       



 W W W W W W W W W W W W W W W W W W W W"''''''  " " "!" / . . . . . * * * * * * % % % % % % 9 9 9 9 9 9
 w)LL #d 3    $# *X*:
;
;
;Q Q Q Q Q_S) Q Q Q Q Qs   - 77