
    dhc                       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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l0m1Z1 ddl2m3Z3m4Z4 ddl5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z?  e4dddd      Z@ G d d e?      ZAy)!    )annotationsN)CancelledErrorEventFutureLock)suppress)AnyAsyncGenerator	Awaitable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                  <    e Zd ZdZdej
                  dddd	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZd dZd!dZd"dZ	d#d$d	Z
ed%d
       Zed&d       Zej                  d'd       Zd(dZd)dZededf	 	 	 	 	 	 	 	 	 d*d       Zd+dZed,d       Z	 d-	 	 	 	 	 	 	 	 	 d.dZ	 	 	 	 	 	 d/dZddeddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d0dZd(dZ	 d1	 	 	 	 	 	 	 	 	 d2dZd3dZd4dZddeedddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d5dZddeedddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d5dZ xZ S )6
Dispatcherz
    Root router
    NF)storagefsm_strategyevents_isolationdisable_fsmnamec                  t         t        |   |       |r1t        |t              s!t        dt        |      j                         t        | d      x| _	        | j                  d<   | j                  j                  | j                         | j                  j                  t        |              | j                  j                  t                      t!        |xs
 t#               ||xs
 t%                     | _        |s%| j                  j                  | j&                         | j(                  j                  | j&                  j*                         || _        t/               | _        d| _        d| _        t7               | _        y)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
        )r6   z4FSM storage should be instance of 'BaseStorage' not update)router
event_name)r2   strategyr4   N)superr1   __init__
isinstancer   	TypeErrortype__name__r(   r8   	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)selfr2   r3   r4   r5   r6   kwargs	__class__s          W/var/www/netwell/bot/venv/lib/python3.12/site-packages/aiogram/dispatcher/dispatcher.pyr=   zDispatcher.__init__&   s?   ( 	j$(d(3:g{;FtG}G]G]F^_  2GH2
 	
dnnX. 	T001 	$$%5d%;< 	$$%:%<= (.}!-I1G1I

  KK((2txx~~.-3!V-104<?E!    c                     | j                   |   S NrI   )rO   items     rR   __getitem__zDispatcher.__getitem__d   s    !!$''rS   c                "    || j                   |<   y rU   rV   )rO   keyvalues      rR   __setitem__zDispatcher.__setitem__g   s    "'3rS   c                    | j                   |= y rU   rV   )rO   rZ   s     rR   __delitem__zDispatcher.__delitem__j   s    s#rS   c               :    | j                   j                  ||      S rU   )rI   get)rO   rZ   defaults      rR   r`   zDispatcher.getm   s    !!%%c733rS   c                .    | j                   j                  S rU   )rF   r2   rO   s    rR   r2   zDispatcher.storagep   s    xxrS   c                     y)z}
        Dispatcher has no parent router and can't be included to any other routers or dispatchers

        :return:
        N rc   s    rR   parent_routerzDispatcher.parent_routert   s     rS   c                    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)rO   r[   s     rR   rf   zDispatcher.parent_router}   s     NOOrS   c           	       K   t        j                         }d}|j                         }|j                  |k7  r't	        j
                  |j                         d|i      }	 | j                  j                  | j                  j                  |i | j                  |d|i       d{   }|t        u}||j                         }||z
  dz  }	t        j                  j                  d|j                  |rdnd|	|j                          S 7 a# |j                         }||z
  dz  }	t        j                  j                  d|j                  |rdnd|	|j                          w xY ww)	z
        Main entry point for incoming updates
        Response of this method can be used as Webhook response

        :param bot:
        :param update:
        FbotcontextNi  z/Update id=%s is %s. Duration %d ms by bot id=%dhandledznot handled)asyncioget_running_looptimerj   r   model_validate
model_dumpr8   wrap_outer_middlewaretriggerrI   r&   r   eventinfo	update_idid)
rO   rj   r8   rP   looprm   
start_timeresponsefinish_timedurations
             rR   feed_updatezDispatcher.feed_update   sR     '')YY[
:: **6+<+<+>PSUF	![[>>##(( 3 H i/G))+K#j0D8HMMA  $	- ))+K#j0D8HMMA  $	-s3   AE" AD
 &D'D
 4AE"D
 
AEE"c                z   K   t        j                  |d|i      } | j                  d||d| d{   S 7 w)z
        Main entry point for incoming updates with automatic Dict->Update serializer

        :param bot:
        :param update:
        :param kwargs:
        rj   rk   rj   r8   Nre   )r   rq   _feed_webhook_update)rO   rj   r8   rP   parsed_updates        rR   feed_raw_updatezDispatcher.feed_raw_update   sB      --fuclK.T..W3}WPVWWWWs   2;9;   c                 K   t        |      }t        ||      }i }|j                  j                  r%t	        |j                  j                  |z         |d<   d}	 	  ||fi | d{   }	|rGt        j                  j!                  d	|j                  |j                         |j#                          d}|	D ]  }| |j$                  d
z   |_         |7 n# t
        $ r}
d}t        j                  j                  dt        |
      j                  |
       t        j                  j                  d|j                  |j                  |j                         |j                          d{  7   Y d}
~
d}
~
ww xY ww)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)timeoutallowed_updates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   int	Exceptionr   
dispatchererrorr@   rA   warning
next_delaycounterrx   asleeprv   resetrw   offset)clsrj   polling_timeoutbackoff_configr   backoffget_updatesrP   failedupdateser8   s               rR   _listen_updateszDispatcher._listen_updates   sY     0 /Z;; ),CKK,?,?/,Q(RF$% #K :6 ::$ ""''HOOFF
 ! :
 &,%5%5%9":; :  ""(()KTRSWM]M]_`a""**W&&OOFF	 nn&&&sP   AF C )C*C .A*F C 	E=#B	E8,E/-E82F 8E==F c                0  K   	 |j                   }|j                  }|j                  |        | j                  d||d| d{   S # t        $ r=}t        j                  d|j                  d       t               t               |d}~ww xY w7 Mw)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_typeru   re   )

event_typeru   r"   warningswarnmodel_dump_jsonRuntimeWarningr'   r8   propagate_event)rO   r8   rP   r   ru   r   s         rR   rD   zDispatcher._listen_update   s     	' ++KLLE 	6*)T))YkYRXYYY % 	'MM $33$3GHJ  -Q&	' Zs3   BA *BBB	B8BBBc                   K   	  ||       d{    y7 # t         $ r?}t        j                  j                  d|j                  j
                  |       Y d}~yd}~ww xY ww)zk
        Simulate answer into WebHook

        :param bot:
        :param result:
        :return:
        NzFailed to make answer: %s: %s)r   r   ru   r   rQ   rA   )r   rj   resultr   s       rR   silent_call_requestzDispatcher.silent_call_request  sQ     	Zf+ 	Z
 MM ?AUAUWXYY	Zs6   A"  A" 	A5AA"AA"Tc                x  K   	  | j                   ||fi | d{   }|r+t        |t              r| j                  ||       d{    |t        uS 7 97 # t
        $ rU}t        j                  j                  d|j                  |j                  |j                  j                  |       Y d}~yd}~ww xY 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rj   r   >Cause exception while process update id=%d by bot id=%d
%s: %sT)r~   r>   r   r   r&   r   r   ru   	exceptionrw   rx   rQ   rA   )rO   rj   r8   call_answerrP   r{   r   s          rR   _process_updatezDispatcher._process_update(  s     	-T--c6DVDDHz(NC..3x.HHH9,, EH  	MM##Q  $$ 	sQ   B:A A,A A	A B:A A 	B7"AB2-B:2B77B:c                n   K   	 | d{   |j                          S 7 # |j                          w xY w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)rO   handle_update	semaphores      rR   _process_with_semaphorez"Dispatcher._process_with_semaphoreD  s/     	 && 's    5    5  25c                  K   |j                          d{   }t        j                  j                  d|j                  |j
                  |j                         d}	||rt        j                  |      }		 | j                  ||||      2 3 d{   }
 | j                  d||
d|}|r|	r>|	j                          d{    t        j                  | j                  ||	            }nt        j                  |      }| j                  j                  |       |j!                  | j                  j"                         | d{    7 77 7 7 6 	 t        j                  j                  d|j                  |j
                  |j                         y# t        j                  j                  d|j                  |j
                  |j                         w xY w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 - %rre   )mer   r   rv   usernamerx   	full_namern   	Semaphorer   r   acquirecreate_taskr   rN   addadd_done_callbackdiscard)rO   rj   r   handle_as_tasksr   r   tasks_concurrency_limitrP   userr   r8   r   handle_update_tasks                rR   _pollingzDispatcher._pollingS  s    . 668^0$--	

 	".?))*ABI	 $ 4 4 /- /	 !5 ! ( (f !5 4 4 VV Vv V" '//111-4-@-@ 88	R.* .5-@-@-O*--112DE&889R9R9Z9Z['''? $( 2 ()!, ##8$--QUQ_Q_G##8$--QUQ_Q_sy   GEAG7F EEE-F EBF EF GEF F F AGAGGc                  K   	  | j                   ||fi | d{   S 7 # t        $ rQ}t        j                  j	                  d|j
                  |j                  |j                  j                  |        d}~ww xY ww)zg
        The same with `Dispatcher.process_update()` but returns real response instead of bool
        Nr   )	r~   r   r   ru   r   rw   rx   rQ   rA   )rO   rj   r8   rP   r   s        rR   r   zDispatcher._feed_webhook_update  st     
	)))#v@@@@@ 	MM##Q  $$ 	s1   A?"  " A?" 	A<AA77A<<A?c                   K   t        |t              st        j                  |di      }t        j                         }t        j                         }|j                         dfd}|j                  ||      }t        j                    j                  d|d|      }	|	j                  ||       d fd}
	 	  d {    |	j                         r2|	j!                         }t        |t"              r6||j                          S |	j                  |       |	j                  |
|       |j                          y 7 {# t        $ r# |	j                  |       |	j                           w xY w# |j                          w xY ww)	Nrj   rk   c                 J    j                         sj                  d        y y rU   )done
set_result)_waiters    rR   release_waiterz6Dispatcher.feed_webhook_update.<locals>.release_waiter  s    ;;=!!$' !rS   r   c                    t        j                  dt               	 | j                         }t        |t              r't        j                  j                  |             y y # t        $ r}|d }~ww xY w)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   rn   ensure_futurer   )taskr   r   rj   rO   s      rR   process_responsez8Dispatcher.feed_webhook_update.<locals>.process_response  sp    MMR  &.1%%d&>&>3v&>&VW 2  s   A% %	A5.A00A5)r   r	   returnNonere   )r   zFuture[Any]r   r   )r>   r   rq   contextvarscopy_contextrn   ro   create_future
call_laterr   r   r   r   remove_done_callbackcancelr   r   r   )rO   rj   r8   _timeoutrP   ctxry   r   timeout_handleprocess_updatesr   r{   r   s   ``          @rR   feed_webhook_updatezDispatcher.feed_webhook_update  sk     &&)**6E3<HF&&('')##%	( >B'.'<'<%D%%G#fGG(
 	)).#)F	X	$ ##% / 6 6 8h7# !!#	  44^D112BC1P !!#' ! 44^D&&(  !!#sN   B<F
E E	E 1E5 >F
$E5 3F
E ,E22E5 5FF
c                  K   | j                   j                         st        d      | j                  r| j                  sy| j                  j                          | j                  j                          d{    y7 w)zd
        Execute this method if you want to stop polling programmatically

        :return:
        zPolling is not startedN)rJ   lockedrh   rK   rL   rM   waitrc   s    rR   stop_pollingzDispatcher.stop_polling  sd      !!((*788  (<(<""'')))s   A6B 8A>9B c                    | j                   j                         sy t        j                  j	                  d|j
                         | j                  sy | j                  j                          y )NzReceived %s signal)rJ   r   r   r   r   r6   rK   rM   )rO   sigs     rR   _signal_stop_pollingzDispatcher._signal_stop_polling  sP    !!((*""#7B  rS   
   r   r   r   r   handle_signalsclose_bot_sessionr   c                 K   |st        d      d|	v rt        d      | j                  4 d{    | j                  t               | _        | j                  t               | _        |t
        u r| j                         }| j                  j                          | j                  j                          |rt        j                         }
t        t              5  |
j                  t        j                  | j                  t        j                         |
j                  t        j                   | j                  t        j                          ddd       | |d| j"                  |	}d|v r|j%                  d        | j&                  dd|d   i| d{    t(        j*                  j-                  d       	 |D cg c].  }t        j.                   | j0                  d||||||d|      0 }}|j3                  t        j.                  | j                  j5                                      t        j4                  |t        j6                  	       d{   \  }}|D ]4  }|j9                          t        t:              5  | d{    ddd       6 t        j<                  |  d{    t(        j*                  j-                  d
       	  | j>                  dd|d   i| d{    |r"t        j<                  d |D          d{    	 | j                  jA                          ddd      d{    y7 # 1 sw Y   xY w7 c c}w 7 7 # 1 sw Y   xY w7 7 7 ^# |r#t        j<                  d |D          d{  7   w w xY w# t(        j*                  j-                  d
       	  | j>                  dd|d   i| d{  7   |rMt        j<                  d |D          d{  7   n*# |r#t        j<                  d |D          d{  7   w w xY w| j                  jA                          w xY w7 # 1 d{  7  sw Y   yxY ww)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 pollingrj   zbKeyword argument 'bot' is not acceptable, the bot instance should be passed as positional argumentN)r   botszStart polling)rj   r   r   r   r   r   )return_whenzPolling stoppedc              3  P   K   | ]  }|j                   j                            y wrU   )r   rH   ).0rj   s     rR   	<genexpr>z+Dispatcher.start_polling.<locals>.<genexpr>W  s     .Sss{{/@/@/B.Ss   $&re   )!
ValueErrorrJ   rK   r   rL   r    resolve_used_update_typesclearrn   ro   r   NotImplementedErroradd_signal_handlersignalSIGTERMr   SIGINTrI   popemit_startupr   r   rv   r   r   appendr   FIRST_COMPLETEDr   r   gatheremit_shutdownrM   )rO   r   r   r   r   r   r   r   r   rP   ry   rI   rj   tasksr   pendingr   s                    rR   start_pollingzDispatcher.start_polling  s    8 UVVF?K 
 %% D	+ D	+  ($)G!##+',w$%'"&"@"@"B##%  &&(//112  ++(A(A6>> ++t'@'@&-- # $$ 	M %!!%(#$##BRBMBBB##O4!+  $2  ''%  #,;,;+9,;4K ,
2 2 W001B1B1G1G1IJK&-ll5gF]F]&^ ^g# #DKKM!.1 #"

# ## nnd+++ ""''(9:U,$,,KbK]KKK(%nn.Sd.STTT$$((*ID	+ D	+ D	+ & C2 !_ ## # ,
 L U )%nn.Sd.STTT )	 ""''(9:U,$,,KbK]KKK(%nn.Sd.STTT )%nn.Sd.STTT )$$((*ID	+ D	+ D	+ D	+s\  -Q#MQ#B(QA3MA
QM#Q=N3M4A&NM+NM M
M N0M-1N5QM3/M/0M34QM1Q2Q#=Q>Q#M		QNM  M*%	N/M31Q3NN
NQ Q>PO
PQ<O?
=QP*	"P%#P*	*QQQ#Q QQ Q#c                   t        t              5  t        j                   | j                  |i |	|||||||d      cddd       S # 1 sw Y   yxY w)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   N)r   KeyboardInterruptrn   runr   )
rO   r   r   r   r   r   r   r   r   rP   s
             rR   run_pollingzDispatcher.run_pollingZ  se    6 '( 	;;"""

 %4$3#1$3#1&7,C
	 	 	s   /A		A)r2   zOptional[BaseStorage]r3   r   r4   zOptional[BaseEventIsolation]r5   boolr6   zOptional[str]rP   r	   r   r   )rW   strr   r	   )rZ   r  r[   r	   r   r   )rZ   r  r   r   rU   )ra   Optional[Any]rZ   r  r   r  )r   r   )r   zOptional[Router])r[   r+   r   r   )rj   r   r8   r   rP   r	   r   r	   )rj   r   r8   zDict[str, Any]rP   r	   r   r	   )
rj   r   r   r   r   r$   r   Optional[List[str]]r   zAsyncGenerator[Update, None])r8   r   rP   r	   r   r	   )rj   r   r   zTelegramMethod[Any]r   r   )T)
rj   r   r8   r   r   r  rP   r	   r   r  )r   zAwaitable[bool]r   zasyncio.Semaphorer   r  )rj   r   r   r   r   r  r   r$   r   r  r   Optional[int]rP   r	   r   r   )7   )
rj   r   r8   zUnion[Update, Dict[str, Any]]r   floatrP   r	   r   z&Optional[TelegramMethod[TelegramType]])r   r   )r   zsignal.Signalsr   r   )r   r   r   r   r   r  r   r$   r   z&Optional[Union[List[str], UNSET_TYPE]]r   r  r   r  r   r	  rP   r	   r   r   )!rA   
__module____qualname____doc__r   USER_IN_CHATr=   rX   r\   r^   r`   propertyr2   rf   setterr~   r   classmethodDEFAULT_BACKOFF_CONFIGr   rD   r   r   r   r   r   r   r   r   r    r   r  __classcell__)rQ   s   @rR   r1   r1   !   sF    *.$/$<$<9=!"<B '<B "	<B
 7<B <B <B <B 
<B|(($4       P P+Z	X   "(>/37:7: 7: &	7:
 -7: 
&7: 7:rZ: Z Z$ =A &59LO	8 , 9J 	 $  " $(>/315:: : 	:
 &: -: "/: : 
:x" RT99 =9IN9_b9	/9v*   " $(>BG#"&15h+h+ h+ 	h+
 &h+ @h+ h+  h+ "/h+ h+ 
h+Z  " $(>BG#"&15(( ( 	(
 &( @( (  ( "/( ( 
(rS   r1   )B
__future__r   rn   r   r   r   r   r   r   r   
contextlibr   typingr	   r
   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*   r9   r+   r  r1   re   rS   rR   <module>r)     s|    "     7 7  S S S   ) 1 > F & 0 '   * 0 2 / 1 / ; &CX[\ a	 a	rS   