o
    LDif                     @  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rd 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dd\d]Zdd`daZdbdDeedDdDddcddhdiZdbdDeedDdDddcddjdk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__ i/var/www/www-root/data/www/77.83.87.30/venv/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}z7| j| jj	|i | j
|d|iI dH }|tu}|W | }|| d }	tjd|j|rLdnd|	|j S | }|| d }	tjd|j|rgd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   contextNi  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   looprh   
start_timeresponsefinish_timedurationrR   rR   rS   feed_update   sL   

	

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   rl   _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   
dispatchererrorr>   r?   warning
next_delaycounterrs   asleeprq   resetrr   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:
        zDetected 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_typerp   rR   )

event_typerp   r   warningswarnmodel_dump_jsonRuntimeWarningr   r7   propagate_event)rN   r7   r4   r   rp   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   rp   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)ry   r=   r   r   r   r   rp   	exceptionrr   rs   rQ   r?   r   )rN   re   r7   r   r4   rv   r   rR   rR   rS   _process_update/  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_semaphoreQ  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   r   rq   usernamers   	full_nameri   	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   _pollingb  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   )	ry   r   r   rp   r   rr   rs   rQ   r?   )rN   re   r7   r4   r   rR   rR   rS   r|     s   zDispatcher._feed_webhook_update7   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 )NzDetected 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   ri   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   rl   contextvarscopy_contextri   rj   create_future
call_laterr   r|   r   r   remove_done_callbackcancelr   r   r   )rN   re   r7   r   r4   ctxrt   r   timeout_handleprocess_updatesr   rv   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   r   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 sw   Y  qt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)r   r   zStart pollingc                   s0   g | ]}t jd| d qS ))re   r   r   r   r   r   rR   )ri   r   r   .0re   r   r   r   r   rN   r   rH   rR   rS   
<listcomp>V  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>u  s    z+Dispatcher.start_polling.<locals>.<genexpr>rR   ) 
ValueErrorrI   rJ   r   rK   r   resolve_used_update_typesclearri   rj   r	   NotImplementedErroradd_signal_handlersignalSIGTERMr   SIGINTrH   popemit_startupr   r   rq   appendr   r   FIRST_COMPLETEDr   r   gatheremit_shutdownrL   )rN   r   r   r   r   r   r   r   r   r4   rO   rt   tasksr   pendingr   rR   r   rS   start_polling  s   






  0z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ImportErrorri   runsysversion_infoRunnernew_event_loopinstall)rN   r   r   r   r   r   r   r   r   r4   coror  runnerrR   rR   rS   run_pollingx  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   rz   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   setterry   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   ri   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>    