o
    @jZ                     @  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mZmZmZm	Z	 d dl
mZ d dlmZmZmZmZmZmZm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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*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z< ddl=m>Z> e3dddddZ?G dd  d e>Z@dS )!    )annotationsN)CancelledErrorEventFutureLock)suppress)AnyAsyncGeneratorDictListOptionalSetUnion   )loggers)Bot)TelegramAPIError)FSMContextMiddleware)BaseEventIsolationBaseStorage)DisabledEventIsolationMemoryStorage)FSMStrategy)
GetUpdatesTelegramMethod)TelegramType)UpdateUser)UNSET
UNSET_TYPE)UpdateTypeLookupError)BackoffBackoffConfig   )	UNHANDLEDSkipHandler)TelegramEventObserver)ErrorsMiddleware)UserContextMiddleware)Routerg      ?g      @g?g?)	min_delay	max_delayfactorjitterc                      sL  e Zd ZdZdejdddddd fddZdeddZdfddZdgddZ	dhdid!d"Z
edjd$d%Zedkd'd(Zejdld*d(Zdmd/d0Zdnd2d3Zed4edfdod<d=Zdpd>d?ZedqdBdCZ	DdrdsdFdGZd4dDedfdtdIdJZdmdKdLZ	MdudvdRdSZdwdTdUZdxdXdYZdZdDeedDdDd[dyd`daZdZdDeedDdDd[dydbdcZ  ZS )z
Dispatcherz
    Root router
    NF)storagefsm_strategyevents_isolationdisable_fsmnamer/   Optional[BaseStorage]r0   r   r1   Optional[BaseEventIsolation]r2   boolr3   Optional[str]kwargsr   returnNonec                  s   t t| j|d |rt|tstdt|j 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
        )r3   z4FSM storage should be instance of 'BaseStorage' not update)router
event_name)r/   strategyr1   N)superr.   __init__
isinstancer   	TypeErrortype__name__r&   r;   	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/   r0   r1   r2   r3   r8   	__class__ l/var/www/www-root/data/www/ai-bot.pdev.uz/venv/lib/python3.10/site-packages/aiogram/dispatcher/dispatcher.pyr@   &   s0   zDispatcher.__init__itemstrc                 C  s
   | j | S NrL   )rR   rW   rU   rU   rV   __getitem__d   s   
zDispatcher.__getitem__keyvaluec                 C  s   || j |< d S rY   rZ   )rR   r\   r]   rU   rU   rV   __setitem__g      zDispatcher.__setitem__c                 C  s   | j |= d S rY   rZ   )rR   r\   rU   rU   rV   __delitem__j   s   zDispatcher.__delitem__defaultOptional[Any]c                C  s   | j ||S rY   )rL   get)rR   r\   ra   rU   rU   rV   rc   m   r_   zDispatcher.getr   c                 C  s   | j jS rY   )rI   r/   rR   rU   rU   rV   r/   p   s   zDispatcher.storageOptional[Router]c                 C  s   dS )z}
        Dispatcher has no parent router and can't be included to any other routers or dispatchers

        :return:
        NrU   rd   rU   rU   rV   parent_routert   s   zDispatcher.parent_routerr)   c                 C  s   t d)z
        Dispatcher is root Router then configuring parent router is not allowed

        :param value:
        :return:
        z1Dispatcher can not be attached to another Router.)RuntimeError)rR   r]   rU   rU   rV   rf   }   s   botr   r;   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:
        Frh   contextNi  z/Update id=%s is %s. Duration %d ms by bot id=%dhandledznot handled)asyncioget_running_looptimerh   r   model_validate
model_dumpr;   wrap_outer_middlewaretriggerrL   r$   r   eventinfo	update_idid)
rR   rh   r;   r8   looprk   
start_timeresponsefinish_timedurationrU   rU   rV   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:
        rh   ri   rh   r;   NrU   )r   ro   _feed_webhook_update)rR   rh   r;   r8   parsed_updaterU   rU   rV   feed_raw_update   s   zDispatcher.feed_raw_update   polling_timeoutintbackoff_configr"   allowed_updatesOptional[List[str]]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errorrC   rD   warning
next_delaycounterrv   asleeprt   resetru   offset)clsrh   r   r   r   backoffget_updatesr8   failedupdateser;   rU   rU   rV   _listen_updates   sF   
zDispatcher._listen_updatesc              
     sv   z|j }|j}W n ty& } ztd|jdd t 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_unsetN)event_update)update_typers   rU   )

event_typers   r    warningswarnmodel_dump_jsonRuntimeWarningr%   r;   propagate_event)rR   r;   r8   r   rs   r   rU   rU   rV   rG      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   rs   r   rT   rD   )r   rh   r   r   rU   rU   rV   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  |tuW S  tyE } 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rh   r   >Cause exception while process update id=%d by bot id=%d
%s: %sT)r|   rA   r   r   r$   r   r   rs   	exceptionru   rv   rT   rD   )rR   rh   r;   r   r8   ry   r   rU   rU   rV   _process_update(  s"   
zDispatcher._process_updatehandle_as_tasksc                   s   |  I dH }tjd|j|j|j zE| j||||d2 z+3 dH W }| jd||d|}	|rDt	
|	}
| 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 )zg
        Internal polling process

        :param bot:
        :param kwargs:
        :return:
        Nz"Run polling for bot @%s id=%d - %r)r   r   r   r~   z&Polling stopped for bot @%s id=%d - %rrU   )mer   r   rt   usernamerv   	full_namer   r   rl   create_taskrQ   addadd_done_callbackdiscard)rR   rh   r   r   r   r   r8   userr;   handle_updatehandle_update_taskrU   rU   rV   _pollingD  s0   
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   )	r|   r   r   rs   r   ru   rv   rT   rD   )rR   rh   r;   r8   r   rU   rU   rV   r   k  s   zDispatcher._feed_webhook_update7   Union[Update, Dict[str, Any]]_timeoutfloat&Optional[TelegramMethod[TelegramType]]c                   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 )Nrh   ri   _r   r9   r:   c                    s      s d  d S d S rY   )done
set_result)r   )waiterrU   rV   release_waiter  s   z6Dispatcher.feed_webhook_update.<locals>.release_waiterr~   taskFuture[Any]c              
     s\   t dt z|  }W n ty } z|d }~ww 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   rA   r   rl   ensure_futurer   )r   r   r   )rh   rR   rU   rV   process_response  s   
z8Dispatcher.feed_webhook_update.<locals>.process_response)r   r   r9   r:   rU   )r   r   r9   r:   )rA   r   ro   contextvarscopy_contextrl   rm   create_future
call_laterr   r   r   r   remove_done_callbackcancelr   r   r   )rR   rh   r;   r   r8   ctxrw   r   timeout_handleprocess_updatesr   ry   rU   )rh   rR   r   rV   feed_webhook_update{  sF   





zDispatcher.feed_webhook_updatec                   sB   | j  s
td| 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)rM   lockedrg   rN   rO   rP   waitrd   rU   rU   rV   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)rM   r   r   r   r   r3   rN   rP   )rR   r   rU   rU   rV   _signal_stop_polling  s   
zDispatcher._signal_stop_polling
   r   r   r   r   handle_signalsclose_bot_sessionbots&Optional[Union[List[str], UNSET_TYPE]]r   r   c                  s  |st dd|v rt dj4 I dH X jdu r!t _jdu r*t _ tu r2  j  j  |rjt	 }	t
t |	tjjtj |	tjjtj W d   n1 sew   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 |rKtjdd |D  I dH  n|r]tjdd |D  I dH  w w j  w W d  I dH  dS 1 I dH svw   Y  dS )al  
        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 kwargs: contextual data
        :return:
        z6At least one bot instance is required to start pollingrh   zbKeyword argument 'bot' is not acceptable, the bot instance should be passed as positional argumentN)r   r   zStart pollingc                   s.   g | ]}t jd| d qS ))rh   r   r   r   r   rU   )rl   r   r   .0rh   r   r   r   r   rR   rL   rU   rV   
<listcomp>  s    z,Dispatcher.start_polling.<locals>.<listcomp>)return_whenzPolling stoppedc                 s  s    | ]}|j  V  qd S rY   )r   rK   r   rU   rU   rV   	<genexpr>/  s    z+Dispatcher.start_polling.<locals>.<genexpr>rU   ) 
ValueErrorrM   rN   r   rO   r   resolve_used_update_typesclearrl   rm   r   NotImplementedErroradd_signal_handlersignalSIGTERMr   SIGINTrL   popemit_startupr   r   rt   appendr   r   FIRST_COMPLETEDr   r   gatheremit_shutdownrP   )rR   r   r   r   r   r   r   r   r8   rw   tasksr   pendingr   rU   r   rV   start_polling  s   






  0zDispatcher.start_pollingc          	      O  sT   t t t| j|i |||||||dW  d   S 1 s#w   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 kwargs: contextual data
        :return:
        r   N)r   KeyboardInterruptrl   runr   )	rR   r   r   r   r   r   r   r   r8   rU   rU   rV   run_polling2  s    
$zDispatcher.run_polling)r/   r4   r0   r   r1   r5   r2   r6   r3   r7   r8   r   r9   r:   )rW   rX   r9   r   )r\   rX   r]   r   r9   r:   )r\   rX   r9   r:   rY   )ra   rb   r\   rX   r9   rb   )r9   r   )r9   re   )r]   r)   r9   r:   )rh   r   r;   r   r8   r   r9   r   )rh   r   r;   r}   r8   r   r9   r   )
rh   r   r   r   r   r"   r   r   r9   r   )r;   r   r8   r   r9   r   )rh   r   r   r   r9   r:   )T)
rh   r   r;   r   r   r6   r8   r   r9   r6   )rh   r   r   r   r   r6   r   r"   r   r   r8   r   r9   r:   )r   )
rh   r   r;   r   r   r   r8   r   r9   r   )r9   r:   )r   r   r9   r:   )r   r   r   r   r   r6   r   r"   r   r   r   r6   r   r6   r8   r   r9   r:   ) rD   
__module____qualname____doc__r   USER_IN_CHATr@   r[   r^   r`   rc   propertyr/   rf   setterr|   r   classmethodDEFAULT_BACKOFF_CONFIGr   rG   r   r   r   r   r   r   r   r   r   r   __classcell__rU   rU   rS   rV   r.   !   sl    
>


	
-
9
'
;
ir.   )A
__future__r   rl   r   r   r   r   r   r   r   
contextlibr   typingr   r	   r
   r   r   r   r    r   
client.botr   
exceptionsr   fsm.middlewarer   fsm.storage.baser   r   fsm.storage.memoryr   r   fsm.strategyr   methodsr   r   methods.baser   typesr   r   
types.baser   r   types.updater    utils.backoffr!   r"   event.basesr$   r%   event.telegramr&   middlewares.errorr'   middlewares.user_contextr(   r<   r)   r   r.   rU   rU   rU   rV   <module>   s8    $