o
    4˜ŽjHf  ã                   @  s”  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlmZmZm	Z	m
Z
 d dlmZmZ d dlmZ d dlmZmZ d dlmZ d dlmZ d d	lmZ d d
lmZmZ d dlmZmZ d dlm Z  d dl!m"Z"m#Z# d dl$m%Z%m&Z& d dl'm(Z(m)Z) d dl*m+Z+ d dl,m-Z-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9 er¸d dl:m;Z; d dl<m=Z= e.ddddd�Z>G dd „ d e9ƒZ?dS )!é    )ÚannotationsN)ÚCancelledErrorÚEventÚFutureÚLock)ÚAsyncGeneratorÚ	Awaitable)Úsuppress)ÚTYPE_CHECKINGÚAny)Úloggers)ÚTelegramAPIError)ÚFSMContextMiddleware)ÚBaseEventIsolationÚBaseStorage)ÚDisabledEventIsolationÚMemoryStorage)ÚFSMStrategy)Ú
GetUpdatesÚTelegramMethod)ÚUpdateÚUser)ÚUNSETÚ
UNSET_TYPE)ÚUpdateTypeLookupError)ÚBackoffÚBackoffConfigé   )Ú	UNHANDLEDÚSkipHandler)ÚTelegramEventObserver)ÚErrorsMiddleware)ÚUserContextMiddleware)ÚRouter)ÚBot)ÚTelegramTypeg      ð?g      @gÍÌÌÌÌÌô?gš™™™™™¹?)Ú	min_delayÚ	max_delayÚfactorÚjitterc                      s\  e Zd ZdZdejddddœdl‡ fdd„Zdmdd„Zdndd„Zdodd„Z	dpdqd!d"„Z
edrd$d%„ƒZedsd'd(„ƒZejdtd*d(„ƒZdud/d0„Zdvd2d3„Zed4edfdwd<d=„ƒZdxd>d?„ZedydBdC„ƒZ	Ddzd{dFdG„Zd|dLdM„Zd4dDeddfd}dQdR„ZdudSdT„Z	Ud~ddZd[„Zd€d\d]„Zd�d`da„ZdbdDeedDdDddcœd‚dhdi„ZdbdDeedDdDddcœd‚djdk„Z‡  Z S )ƒÚ
Dispatcherz
    Root router
    NF)ÚstorageÚfsm_strategyÚevents_isolationÚdisable_fsmÚnamer+   úBaseStorage | Noner,   r   r-   úBaseEventIsolation | Noner.   Úboolr/   ú
str | NoneÚkwargsr   ÚreturnÚNonec                  sÜ   t ƒ j|d� |rt|tƒsdt|ƒj› �}t|ƒ‚t| dd� | _| j	d< | j 
| j¡ | j t| ƒ¡ | j tƒ ¡ t|pAtƒ ||pFtƒ d�| _|sS| j | j¡ | j 
| jj¡ || _tƒ | _d| _d| _tƒ | _dS )a�  
        Root router

        :param storage: Storage for FSM
        :param fsm_strategy: FSM strategy
        :param events_isolation: Events isolation
        :param disable_fsm: Disable FSM, note that if you disable FSM
            then you should not use storage and events isolation
        :param kwargs: Other arguments, will be passed as keyword arguments to handlers
        )r/   z4FSM storage should be instance of 'BaseStorage' not Úupdate)ÚrouterÚ
event_name)r+   Ústrategyr-   N)ÚsuperÚ__init__Ú
isinstancer   ÚtypeÚ__name__Ú	TypeErrorr    r7   Ú	observersÚregisterÚ_listen_updateÚouter_middlewarer!   r"   r   r   r   ÚfsmÚshutdownÚcloseÚworkflow_datar   Ú_running_lockÚ_stop_signalÚ_stopped_signalÚsetÚ_handle_update_tasks)Úselfr+   r,   r-   r.   r/   r4   Úmsg©Ú	__class__© úZ/var/www/kodo/Anonymous/send/lib/python3.10/site-packages/aiogram/dispatcher/dispatcher.pyr<   +   s0   þýzDispatcher.__init__ÚitemÚstrc                 C  s
   | j | S ©N©rH   )rN   rT   rR   rR   rS   Ú__getitem__i   s   
zDispatcher.__getitem__ÚkeyÚvaluec                 C  s   || j |< d S rV   rW   )rN   rY   rZ   rR   rR   rS   Ú__setitem__l   ó   zDispatcher.__setitem__c                 C  s   | j |= d S rV   rW   )rN   rY   rR   rR   rS   Ú__delitem__o   s   zDispatcher.__delitem__Údefaultú
Any | Nonec                C  s   | j  ||¡S rV   )rH   Úget)rN   rY   r^   rR   rR   rS   r`   r   r\   zDispatcher.getr   c                 C  s   | j jS rV   )rE   r+   ©rN   rR   rR   rS   r+   u   s   zDispatcher.storageúRouter | Nonec                 C  s   dS )z}
        Dispatcher has no parent router and can't be included to any other routers or dispatchers

        :return:
        NrR   ra   rR   rR   rS   Úparent_routery   s   zDispatcher.parent_routerr#   c                 C  s   d}t |ƒ‚)z�
        Dispatcher is root Router then configuring parent router is not allowed

        :param value:
        :return:
        z1Dispatcher can not be attached to another Router.)ÚRuntimeError)rN   rZ   rO   rR   rR   rS   rc   ‚   s   Úbotr$   r7   r   c           
      Ë  sà   �t  ¡ }d}| ¡ }|j|krtj| ¡ d|id�}z9| j | jj	|d| i| j
¥|¥d|i¥¡I dH }|tu}|W | ¡ }|| d }	tj d|j|rNdnd	|	|j¡ S | ¡ }|| d }	tj d|j|ridnd	|	|j¡ w )
z£
        Main entry point for incoming updates
        Response of this method can be used as Webhook response

        :param bot:
        :param update:
        Fre   ©ÚcontextÚ
dispatcherNiè  z/Update id=%s is %s. Duration %d ms by bot id=%dÚhandledznot handled)ÚasyncioÚget_running_loopÚtimere   r   Úmodel_validateÚ
model_dumpr7   Úwrap_outer_middlewareÚtriggerrH   r   r   ÚeventÚinfoÚ	update_idÚid)
rN   re   r7   r4   Úloopri   Ú
start_timeÚresponseÚfinish_timeÚdurationrR   rR   rS   Úfeed_update�   sN   €
ÿþýü
ý

ûþ
ûzDispatcher.feed_updateúdict[str, Any]c                 Ë  s0   �t j|d|id�}| jd||dœ|¤ŽI dH S )z¡
        Main entry point for incoming updates with automatic Dict->Update serializer

        :param bot:
        :param update:
        :param kwargs:
        re   rf   ©re   r7   NrR   )r   rm   Ú_feed_webhook_update)rN   re   r7   r4   Úparsed_updaterR   rR   rS   Úfeed_raw_update»   s   €zDispatcher.feed_raw_updateé   Úpolling_timeoutÚintÚbackoff_configr   Úallowed_updatesúlist[str] | NoneúAsyncGenerator[Update, None]c              
   C s   �t |d�}t||d�}i }|jjrt|jj| ƒ|d< d}	 z||fi |¤ŽI dH }	W n2 ty^ }
 z&d}tj dt	|
ƒj
|
¡ tj d|j|j|j¡ | ¡ I dH  W Y d}
~
qd}
~
ww |rqtj d	|j|j¡ | ¡  d}|	D ]}|V  |jd
 |_qsq)z¨
        Endless updates reader with correctly handling any server-side or connection errors.

        So you may not worry that the polling will stop working.
        )Úconfig)Útimeoutr„   Úrequest_timeoutFTNz Failed to fetch updates - %s: %szASleep for %f seconds and try again... (tryings = %d, bot id = %d)z2Connection established (tryings = %d, bot id = %d)r   )r   r   Úsessionrˆ   r‚   Ú	Exceptionr   rh   Úerrorr>   r?   ÚwarningÚ
next_delayÚcounterrt   Úasleeprr   Úresetrs   Úoffset)Úclsre   r�   rƒ   r„   ÚbackoffÚget_updatesr4   ÚfailedÚupdatesÚer7   rR   rR   rS   Ú_listen_updatesÆ   sF   €
ü€óýÝzDispatcher._listen_updatesc              
   Ë  sz   �z|j }|j}W n ty( } ztjd|jdd�› �tdd� tƒ |‚d}~ww |j|d� | j	d	||dœ|¤ŽI dH S )
a  
        Main updates listener

        Workflow:
        - Detect content type and propagate to observers in current router
        - If no one filter is pass - propagate update to child routers as Update

        :param update:
        :param kwargs:
        :return:
        z�Detected unknown update type.
Seems like Telegram Bot API was updated and you have installed not latest version of aiogram framework
Update: T)Úexclude_unseté   ©Ú
stacklevelN)Úevent_update)Úupdate_typerq   rR   )
Ú
event_typerq   r   ÚwarningsÚwarnÚmodel_dump_jsonÚRuntimeWarningr   r7   Úpropagate_event)rN   r7   r4   rŸ   rq   r˜   rR   rR   rS   rC      s"   €

ýú€÷zDispatcher._listen_updateÚresultúTelegramMethod[Any]c              
   Ã  sR   �z
||ƒI dH  W dS  t y( } ztj d|jj|¡ W Y d}~dS d}~ww )zk
        Simulate answer into WebHook

        :param bot:
        :param result:
        :return:
        NzFailed to make answer: %s: %s)r   r   rq   rŒ   rQ   r?   )r“   re   r¦   r˜   rR   rR   rS   Úsilent_call_request  s   €	"€ûzDispatcher.silent_call_requestTÚcall_answerc              
   Ë  s    �z-| j ||fi |¤ŽI dH }|r%t|tƒr*| j||d�I dH  W |tuS W |tuS W |tuS  tyO } ztj d|j|j	|j
j|¡ W Y d}~dS d}~ww )aL  
        Propagate update to event listeners

        :param bot: instance of Bot
        :param update: instance of Update
        :param call_answer: need to execute response as Telegram method (like answer into webhook)
        :param kwargs: contextual data for middlewares, filters and handlers
        :return: status
        N©re   r¦   ú>Cause exception while process update id=%d by bot id=%d
%s: %sT)rz   r=   r   r¨   r‹   r   rq   Ú	exceptionrs   rt   rQ   r?   r   )rN   re   r7   r©   r4   rw   r˜   rR   rR   rS   Ú_process_update0  s*   €òòõû€øzDispatcher._process_updateÚhandle_updateúAwaitable[bool]Ú	semaphoreúasyncio.Semaphorec                 Ã  s"   �z
|I dH W |  ¡  S |  ¡  w )a  
        Process update with semaphore to limit concurrent tasks

        :param handle_update: Coroutine that processes the update
        :param semaphore: Semaphore to limit concurrent tasks
        :return: bool indicating the result of the update processing
        N)Úrelease)rN   r®   r°   rR   rR   rS   Ú_process_with_semaphoreR  s   €
z"Dispatcher._process_with_semaphoreÚhandle_as_tasksÚtasks_concurrency_limitú
int | Nonec                 Ë  s  �|  ¡ I dH }tj d|j|j|j¡ d}	|dur!|r!t |¡}	zX| j	||||d�2 z>3 dH W }
| j
d||
dœ|¤Ž}|rd|	rQ|	 ¡ I dH  t |  ||	¡¡}nt |¡}| j |¡ | | jj¡ q+|I dH  q+6 W tj d|j|j|j¡ dS tj d|j|j|j¡ w )a  
        Internal polling process

        :param bot:
        :param polling_timeout: Long-polling wait time
        :param handle_as_tasks: Run task for each event and no wait result
        :param backoff_config: backoff-retry config
        :param allowed_updates: List of the update types you want your bot to receive
        :param tasks_concurrency_limit: Maximum number of concurrent updates to process
            (None = no limit), used only if handle_as_tasks is True
        :param kwargs:
        :return:
        Nz"Run polling for bot @%s id=%d - %r)r�   rƒ   r„   r|   z&Polling stopped for bot @%s id=%d - %rrR   )Úmer   rh   rr   Úusernamert   Ú	full_namerj   Ú	Semaphorer™   r­   ÚacquireÚcreate_taskr³   rM   ÚaddÚadd_done_callbackÚdiscard)rN   re   r�   r´   rƒ   r„   rµ   r4   Úuserr°   r7   r®   Úhandle_update_taskrR   rR   rS   Ú_pollingc  sR   €ü
ü
ÿ
ìüüzDispatcher._pollingc              
   Ë  sV   �z| j ||fi |¤ŽI dH W S  ty* } ztj d|j|j|jj|¡ ‚ d}~ww )zg
        The same with `Dispatcher.process_update()` but returns real response instead of bool
        Nr«   )	rz   r‹   r   rq   r¬   rs   rt   rQ   r?   )rN   re   r7   r4   r˜   rR   rR   rS   r}   ¥  s   €û€øzDispatcher._feed_webhook_updateé7   úUpdate | dict[str, Any]Ú_timeoutÚfloatú#TelegramMethod[TelegramType] | Nonec                 ‹  s&  �t |tƒstj|dˆ id�}t ¡ }t ¡ }| ¡ ‰d‡fdd„}| ||¡}t 	ˆj
dˆ |d	œ|¤Ž¡}	|	j||d� d‡ ‡fdd„}
zHzˆI d H  W n ty^   |	 |¡ |	 ¡  ‚ w |	 ¡ rt|	 ¡ }t |tƒrs|W | ¡  S n|	 |¡ |	j|
|d� W | ¡  d S W | ¡  d S | ¡  w )Nre   rf   Ú_r   r5   r6   c                    s   ˆ   ¡ sˆ  d ¡ d S d S rV   )ÚdoneÚ
set_result)rÈ   )ÚwaiterrR   rS   Úrelease_waiterÃ  s   ÿz6Dispatcher.feed_webhook_update.<locals>.release_waiterr|   ÚtaskúFuture[Any]c                   s>   t jdtdd� |  ¡ }t|tƒrt ˆjˆ |d�¡ d S d S )NzýDetected slow response into webhook.
Telegram is waiting for response only first 60 seconds and then re-send update.
For preventing this situation response into webhook returned immediately and handler is moved to background and still processing update.r›   rœ   rª   )	r¡   r¢   r¤   r¦   r=   r   rj   Úensure_futurer¨   )rÍ   r¦   )re   rN   rR   rS   Úprocess_responseÎ  s   ú
ÿz8Dispatcher.feed_webhook_update.<locals>.process_response)rÈ   r   r5   r6   rR   )rÍ   rÎ   r5   r6   )r=   r   rm   ÚcontextvarsÚcopy_contextrj   rk   Úcreate_futureÚ
call_laterrÏ   r}   r¾   r   Úremove_done_callbackÚcancelrÉ   r¦   r   )rN   re   r7   rÅ   r4   Úctxru   rÌ   Útimeout_handleÚprocess_updatesrÐ   rw   rR   )re   rN   rË   rS   Úfeed_webhook_updateµ  sF   €
ÿ
ý

ø
ö
þzDispatcher.feed_webhook_updatec                 Ã  sF   �| j  ¡ sd}t|ƒ‚| jr| jsdS | j ¡  | j ¡ I dH  dS )zd
        Execute this method if you want to stop polling programmatically

        :return:
        zPolling is not startedN)rI   Úlockedrd   rJ   rK   rL   Úwait)rN   rO   rR   rR   rS   Ústop_pollingò  s   €

zDispatcher.stop_pollingÚsigúsignal.Signalsc                 C  s6   | j  ¡ sd S tj d|j¡ | jsd S | j ¡  d S )NzReceived %s signal)rI   rÛ   r   rh   r�   r/   rJ   rL   )rN   rÞ   rR   rR   rS   Ú_signal_stop_polling   s   
zDispatcher._signal_stop_pollingé
   ©r�   r´   rƒ   r„   Úhandle_signalsÚclose_bot_sessionrµ   Úbotsúlist[str] | UNSET_TYPE | Nonerã   rä   c                �  s  �|s	d}
t |
ƒ‚d|	v rd}
t |
ƒ‚ˆj4 I dH �šY ˆjdu r%tƒ ˆ_ˆjdu r.tƒ ˆ_ˆ tu r6ˆ ¡ ‰ ˆj ¡  ˆj ¡  |rnt 	¡ }t
tƒ� | tjˆjtj¡ | tjˆjtj¡ W d  ƒ n1 siw   Y  ˆ|dœˆj¥|	¥‰dˆv r�ˆ d¡ ˆjdd|d iˆ¤ŽI dH  tj d¡ z’‡ ‡‡‡‡‡‡fdd	„|D ƒ}| t ˆj ¡ ¡¡ tj|tjd
�I dH \}}|D ]}| ¡  t
tƒ� |I dH  W d  ƒ n1 sÚw   Y  qÀtj|Ž I dH  W tj d¡ z!ˆjdd|d iˆ¤ŽI dH  W |�rtjdd„ |D ƒŽ I dH  n|�r"tjdd„ |D ƒŽ I dH  w w ˆj ¡  n@tj d¡ z!ˆjdd|d iˆ¤ŽI dH  W |�rPtjdd„ |D ƒŽ I dH  n|�rbtjdd„ |D ƒŽ I dH  w w ˆj ¡  w W d  ƒI dH  dS 1 I dH �s{w   Y  dS )a  
        Polling runner

        :param bots: Bot instances (one or more)
        :param polling_timeout: Long-polling wait time
        :param handle_as_tasks: Run task for each event and no wait result
        :param backoff_config: backoff-retry config
        :param allowed_updates: List of the update types you want your bot to receive
               By default, all used update types are enabled (resolved from handlers)
        :param handle_signals: handle signals (SIGINT/SIGTERM)
        :param close_bot_session: close bot sessions on shutdown
        :param tasks_concurrency_limit: Maximum number of concurrent updates to process
            (None = no limit), used only if handle_as_tasks is True
        :param kwargs: contextual data
        :return:
        z6At least one bot instance is required to start pollingre   zbKeyword argument 'bot' is not acceptable, the bot instance should be passed as positional argumentN)rh   rå   éÿÿÿÿzStart pollingc                   s0   g | ]}t  ˆjd|ˆˆˆˆ ˆd œˆ¤Ž¡‘qS ))re   r´   r�   rƒ   r„   rµ   rR   )rj   r¼   rÂ   ©Ú.0re   ©r„   rƒ   r´   r�   rN   rµ   rH   rR   rS   Ú
<listcomp>W  s    õúùÿÿz,Dispatcher.start_polling.<locals>.<listcomp>)Úreturn_whenzPolling stoppedc                 s  s   � | ]}|j  ¡ V  qd S rV   )rŠ   rG   rè   rR   rR   rS   Ú	<genexpr>v  s   € z+Dispatcher.start_polling.<locals>.<genexpr>rR   ) Ú
ValueErrorrI   rJ   r   rK   r   Úresolve_used_update_typesÚclearrj   rk   r	   ÚNotImplementedErrorÚadd_signal_handlerÚsignalÚSIGTERMrà   ÚSIGINTrH   ÚpopÚemit_startupr   rh   rr   Úappendr¼   rÜ   ÚFIRST_COMPLETEDrÖ   r   ÚgatherÚemit_shutdownrL   )rN   r�   r´   rƒ   r„   rã   rä   rµ   rå   r4   rO   ru   ÚtasksrÉ   ÚpendingrÍ   rR   rê   rS   Ústart_polling	  s˜   €ÿ




ýýøþýü
ô
ÿ€ €ÿÿú €ÿÿ0¸zDispatcher.start_pollingc                O  sü   t tƒ�p | j|i |	¤|||||||dœ¤Ž}
zddl}W n ty2   t |
¡ Y W  d  ƒ S w tjdkr\tj	|j
d��}| |
¡W  d  ƒ W  d  ƒ S 1 sVw   Y  n| ¡  t |
¡W  d  ƒ S W d  ƒ dS 1 sww   Y  dS )a¾  
        Run many bots with polling

        :param bots: Bot instances (one or more)
        :param polling_timeout: Long-polling wait time
        :param handle_as_tasks: Run task for each event and no wait result
        :param backoff_config: backoff-retry config
        :param allowed_updates: List of the update types you want your bot to receive
        :param handle_signals: handle signals (SIGINT/SIGTERM)
        :param close_bot_session: close bot sessions on shutdown
        :param tasks_concurrency_limit: Maximum number of concurrent updates to process
            (None = no limit), used only if handle_as_tasks is True
        :param kwargs: contextual data
        :return:
        râ   r   N)é   é   )Úloop_factory)r	   ÚKeyboardInterruptrþ   ÚuvloopÚImportErrorrj   ÚrunÚsysÚversion_infoÚRunnerÚnew_event_loopÚinstall)rN   r�   r´   rƒ   r„   rã   rä   rµ   rå   r4   Úcoror  ÚrunnerrR   rR   rS   Úrun_pollingy  s>   
ÿþ
÷ï
ÿëç"ëzDispatcher.run_polling)r+   r0   r,   r   r-   r1   r.   r2   r/   r3   r4   r   r5   r6   )rT   rU   r5   r   )rY   rU   rZ   r   r5   r6   )rY   rU   r5   r6   rV   )r^   r_   rY   rU   r5   r_   )r5   r   )r5   rb   )rZ   r#   r5   r6   )re   r$   r7   r   r4   r   r5   r   )re   r$   r7   r{   r4   r   r5   r   )
re   r$   r�   r‚   rƒ   r   r„   r…   r5   r†   )r7   r   r4   r   r5   r   )re   r$   r¦   r§   r5   r6   )T)
re   r$   r7   r   r©   r2   r4   r   r5   r2   )r®   r¯   r°   r±   r5   r2   )re   r$   r�   r‚   r´   r2   rƒ   r   r„   r…   rµ   r¶   r4   r   r5   r6   )rÃ   )
re   r$   r7   rÄ   rÅ   rÆ   r4   r   r5   rÇ   )r5   r6   )rÞ   rß   r5   r6   )rå   r$   r�   r‚   r´   r2   rƒ   r   r„   ræ   rã   r2   rä   r2   rµ   r¶   r4   r   r5   r6   )!r?   Ú
__module__Ú__qualname__Ú__doc__r   ÚUSER_IN_CHATr<   rX   r[   r]   r`   Úpropertyr+   rc   Úsetterrz   r   ÚclassmethodÚDEFAULT_BACKOFF_CONFIGr™   rC   r¨   r­   r³   rÂ   r}   rÚ   rÝ   rà   r   rþ   r  Ú__classcell__rR   rR   rP   rS   r*   &   st    ù
>




.û
9ü
"ù
Bü
=
÷s÷r*   )@Ú
__future__r   rj   rÑ   ró   r  r¡   r   r   r   r   Úcollections.abcr   r   Ú
contextlibr	   Útypingr
   r   Úaiogramr   Úaiogram.exceptionsr   Úaiogram.fsm.middlewarer   Úaiogram.fsm.storage.baser   r   Úaiogram.fsm.storage.memoryr   r   Úaiogram.fsm.strategyr   Úaiogram.methodsr   r   Úaiogram.typesr   r   Úaiogram.types.baser   r   Úaiogram.types.updater   Úaiogram.utils.backoffr   r   Úevent.basesr   r   Úevent.telegramr    Úmiddlewares.errorr!   Úmiddlewares.user_contextr"   r8   r#   Úaiogram.client.botr$   Úaiogram.methods.baser%   r  r*   rR   rR   rR   rS   Ú<module>   s>    