o
    Xzjü|  ã                
   @   sJ  d dl Z d dlZd dlZd dlZd dl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 z	d dlZejZW n eyS Z zdZG dd„ deƒZW Y dZ[ndZ[ww ddlmZmZ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! ej"r‹ddl#m$Z$ ej%ej&gej&f Z'G dd„ dƒZ(G dd„ dƒZ)dS )é    N)Údequec                   @   s   e Zd ZdS )ÚOperationalErrorN)Ú__name__Ú
__module__Ú__qualname__© r   r   úR/var/www/kodo/tsheker/venv/lib/python3.10/site-packages/telethon/client/updates.pyr      s    r   é   )ÚeventsÚutilsÚerrors)ÚEventBuilderÚEventCommon)ÚtypesÚ	functions)ÚGapErrorÚPrematureEndReason)Úget_running_loop)Ú__version__é   )ÚTelegramClientc                	   @   sÆ   e Zd Zd$dd„Zd$dd„Zd$dd„Zddd	efd
d„Z	d%ddded	efdd„Z		d%ddded	ede
fdd„Z		d&dd„Zd$dd„Zd$dd„Zdd„ Zd$dd„Zd$dd„Zd$d d!„Zd$d"d#„ZdS )'ÚUpdateMethodsÚselfr   c                 Ã   s‚   �z7z#| t j ¡ ƒI d H  | jI d H }| jd ur| j‚|W W |  ¡ I d H  S  ty.   Y nw W |  ¡ I d H  d S |  ¡ I d H  w ©N)r   ÚupdatesÚGetStateRequestÚdisconnectedÚ_updates_errorÚ
disconnectÚKeyboardInterrupt)r   Úresultr   r   r   Ú_run_until_disconnected)   s   €
ýÿ"z%UpdateMethods._run_until_disconnectedc                 Ã   s*   �| | _ |r| tj ¡ ƒI dH  dS dS )zº
        Change the value of `receive_updates`.

        This is an `async` method, because in order for Telegram to start
        sending updates again, a request must be made.
        N)Ú_no_updatesr   r   r   )r   Úreceive_updatesr   r   r   Úset_receive_updates6   s
   €ÿz!UpdateMethods.set_receive_updatesc                 C   s\   | j  ¡ r	|  ¡ S zz| j  |  ¡ ¡W W |  ¡  S  ty!   Y nw W |  ¡  dS |  ¡  w )a  
        Runs the event loop until the library is disconnected.

        It also notifies Telegram that we want to receive updates
        as described in https://core.telegram.org/api/updates.
        If an unexpected error occurs during update handling,
        the client will disconnect and said error will be raised.

        Manual disconnections can be made by calling `disconnect()
        <telethon.client.telegrambaseclient.TelegramBaseClient.disconnect>`
        or sending a ``KeyboardInterrupt`` (e.g. by pressing ``Ctrl+C`` on
        the console window running the script).

        If a disconnection error occurs (i.e. the library fails to reconnect
        automatically), said error will be raised through here, so you have a
        chance to ``except`` it on your own code.

        If the loop is already running, this method returns a coroutine
        that you should await on your own code.

        .. note::

            If you want to handle ``KeyboardInterrupt`` in your code,
            simply run the event loop in your code too in any way, such as
            ``loop.run_forever()`` or ``await client.disconnected`` (e.g.
            ``loop.run_until_complete(client.disconnected)``).

        Example
            .. code-block:: python

                # Blocks the current task here until a disconnection occurs.
                #
                # You will still receive updates, since this prevents the
                # script from exiting.
                await client.run_until_disconnected()
        N)ÚloopÚ
is_runningr!   Úrun_until_completer   r   ©r   r   r   r   Úrun_until_disconnectedA   s   
%
üÿz$UpdateMethods.run_until_disconnectedÚeventc                    s   ‡ ‡fdd„}|S )a7  
        Decorator used to `add_event_handler` more conveniently.


        Arguments
            event (`_EventBuilder` | `type`):
                The event builder class or instance to be used,
                for instance ``events.NewMessage``.

        Example
            .. code-block:: python

                from telethon import TelegramClient, events
                client = TelegramClient(...)

                # Here we use client.on
                @client.on(events.NewMessage)
                async def handler(event):
                    ...
        c                    s   ˆ  | ˆ ¡ | S r   )Úadd_event_handler)Úf©r*   r   r   r   Ú	decorator…   s   z#UpdateMethods.on.<locals>.decoratorr   )r   r*   r.   r   r-   r   Úonp   s   zUpdateMethods.onNÚcallbackc                 C   sb   t  |¡}|dur|D ]
}| j ||f¡ qdS t|tƒr!|ƒ }n|s't  ¡ }| j ||f¡ dS )aS  
        Registers a new event handler callback.

        The callback will be called when the specified event occurs.

        Arguments
            callback (`callable`):
                The callable function accepting one parameter to be used.

                Note that if you have used `telethon.events.register` in
                the callback, ``event`` will be ignored, and instead the
                events you previously registered will be used.

            event (`_EventBuilder` | `type`, optional):
                The event builder class or instance to be used,
                for instance ``events.NewMessage``.

                If left unspecified, `telethon.events.raw.Raw` (the
                :tl:`Update` objects with no further processing) will
                be passed instead.

        Example
            .. code-block:: python

                from telethon import TelegramClient, events
                client = TelegramClient(...)

                async def handler(event):
                    ...

                client.add_event_handler(handler, events.NewMessage)
        N)r
   Ú_get_handlersÚ_event_buildersÚappendÚ
isinstanceÚtypeÚRaw)r   r0   r*   Úbuildersr   r   r   r+   ‹   s   
$
zUpdateMethods.add_event_handlerÚreturnc                 C   sl   d}|rt |tƒst|ƒ}t| jƒ}|r4|d8 }| j| \}}||kr2|r*t ||ƒr2| j|= |d7 }|s|S )a©  
        Inverse operation of `add_event_handler()`.

        If no event is given, all events for this callback are removed.
        Returns how many callbacks were removed.

        Example
            .. code-block:: python

                @client.on(events.Raw)
                @client.on(events.NewMessage)
                async def handler(event):
                    ...

                # Removes only the "Raw" handling
                # "handler" will still receive "events.NewMessage"
                client.remove_event_handler(handler, events.Raw)

                # "handler" will stop receiving anything
                client.remove_event_handler(handler)
        r   r   )r4   r5   Úlenr2   )r   r0   r*   ÚfoundÚiÚevÚcbr   r   r   Úremove_event_handler¼   s   
ûz"UpdateMethods.remove_event_handlerú5typing.Sequence[typing.Tuple[Callback, EventBuilder]]c                 C   s   dd„ | j D ƒS )aú  
        Lists all registered event handlers.

        Returns
            A list of pairs consisting of ``(callback, event)``.

        Example
            .. code-block:: python

                @client.on(events.NewMessage(pattern='hello'))
                async def on_greeting(event):
                    '''Greets someone'''
                    await event.reply('Hi')

                for callback, event in client.list_event_handlers():
                    print(id(callback), type(event))
        c                 S   s   g | ]\}}||f‘qS r   r   )Ú.0r*   r0   r   r   r   Ú
<listcomp>ö   ó    z5UpdateMethods.list_event_handlers.<locals>.<listcomp>)r2   r(   r   r   r   Úlist_event_handlersã   s   z!UpdateMethods.list_event_handlersc                 Ã   s   �| j  t ¡ ¡I dH  dS )a�  
        "Catches up" on the missed updates while the client was offline.
        You should call this method after registering the event handlers
        so that the updates it loads can by processed by your script.

        This can also be used to forcibly fetch new updates if there are any.

        Example
            .. code-block:: python

                await client.catch_up()
        N)Ú_updates_queueÚputr   ÚUpdatesTooLongr(   r   r   r   Úcatch_upø   s   €zUpdateMethods.catch_upc                 ƒ   sˆ  �ˆ j du pˆ j ¡  }d ˆ _�z~ˆ jrˆ  ¡ I d H  tƒ }ˆ  ¡ �rŒ|rPˆ jr3ˆ  	| 
¡ ¡I d H  n|rOˆ j ˆ  	| 
¡ ¡¡}ˆ j |¡ | ˆ jj¡ |s5qtˆ jƒˆ jkr’ˆ jt  dtˆ jƒˆ j¡ ˆ  ¡ I d H  ˆ j ‡ fdd„¡ tˆ jƒˆ jkr„t d¡ ˆ jt  dtˆ jƒˆ j¡ ˆ j ¡ }|�r³ˆ jt  d¡ z	ˆ |ƒI d H }W ná tjtjtj t!fyÕ } zˆ jt  dt"|ƒj¡ ˆ j #¡  W Y d }~qd }~w tj$tj%f�y } z,ˆ jt  d	t"|ƒj¡ ˆ j #¡  |�r|ˆ _ˆ  &¡ I d H  W Y d }~W d S W Y d }~qd }~w tj't(f�y@ } z ˆ jt  )d
|¡ ˆ j #¡  |ˆ _ˆ  &¡ I d H  W Y d }~W d S d }~w tj*�ye } zˆ jt  )dt+› d�|¡ ˆ j #¡  W Y d }~qd }~w t,�yŒ } zˆ jt  dt"|ƒj|¡ t- .d¡I d H  W Y d }~qd }~ww ˆ j /|ˆ j¡\}}}	|�r£ˆ jt  d¡ ˆ  0|||	¡I d H }
| 1|
¡ qˆ j 2ˆ j¡}|�r(ˆ jt  d|j3j4¡ z
ˆ |ƒI d H }W �n+ tj$tj%f�y } z4ˆ jt  )d|j3j4t"|ƒj¡ ˆ j 5|t6j7ˆ j¡ |�r|ˆ _ˆ  &¡ I d H  W Y d }~W d S W Y d }~qd }~w tj't(f�yN } z(ˆ jt  )d|j3j4|¡ ˆ j 5|t6j7ˆ j¡ |ˆ _ˆ  &¡ I d H  W Y d }~W d S d }~w tj8tj9tjtjtj t!f�y„ } zˆ jt  )d|j3j4t"|ƒj¡ ˆ j 5|t6j7ˆ j¡ W Y d }~qd }~w tj:tj;f�y¦   ˆ jt  d|j3j4¡ ˆ j 5|t6j<ˆ j¡ Y q tj*�yÓ } z ˆ jt  )dt+› d�|j3j4|¡ ˆ j 5|t6j7ˆ j¡ W Y d }~qd }~w t,�yý } zˆ jt  d|j3j4t"|ƒj|¡ t- .d¡I d H  W Y d }~qd }~ww ˆ j =||ˆ j¡\}}}	|�rˆ jt  d|j3j4¡ ˆ  0|||	¡I d H }
| 1|
¡ qˆ j >¡ }|t?ƒ  @¡  }|dk�r[zt- Aˆ jB C¡ |¡I d H }W n t-jD�yZ   ˆ jt  d¡ Y qw qg }zˆ j E|ˆ j|¡\}}	W n
 tF�yu   Y qw ˆ  0|||	¡I d H }
| 1|
¡ ˆ  ¡ s#W d S W d S  t-jG�yš   Y d S  tH�yÃ } zˆ jt  Idt+› d�¡ |ˆ _ˆ  &¡ I d H  W Y d }~d S d }~ww )NTzAIn-memory entity cache limit reached (%s/%s), flushing to sessionc                    s   | ˆ j jkp| ˆ jjv S r   )Ú_mb_entity_cacheÚself_idÚ_message_boxÚmap)Úidr(   r   r   Ú<lambda>.  rB   z,UpdateMethods._update_loop.<locals>.<lambda>z\in-memory entities exceed entity_cache_limit after flushing; consider setting a larger limitz9In-memory entity cache at %s/%s after flushing to sessionz&Getting difference for account updatesz9Cannot get difference since Telegram is having issues: %sz<Cannot get difference since the account is not logged in: %szJCannot get difference since the account is likely misusing the session: %szNCannot get difference due to unexpected error (this may be a bug in Telethon vz; in that it could be handled better, but it's unlikely): %sz7Cannot get difference since the network is down: %s: %sé   z"Got difference for account updatesz)Getting difference for channel %s updateszKCannot get difference for channel %s since the account is not logged in: %szYCannot get difference for channel %s since the account is likely misusing the session: %sz{Getting difference for channel updates %s caused %s; ending getting difference prematurely until server issues are resolvedzEAccount is now banned in %d so we can no longer fetch updates from itz]Cannot get difference for channel %d due to unexpected error (this may be a bug in Telethon vzFCannot get difference for channel %d since the network is down: %s: %sz%Got difference for channel %d updatesr   z#Timeout waiting for updates expiredz9Fatal error handling updates (this is a bug in Telethon vz, please report it))JÚ_authorizedrJ   Úis_emptyr   Ú	_catch_uprG   r   Úis_connectedÚ_sequential_updatesÚ_dispatch_updateÚpopleftr%   Úcreate_taskÚ_event_handler_tasksÚaddÚadd_done_callbackÚdiscardr9   rH   Ú_entity_cache_limitÚ_logr   ÚinfoÚ_save_states_and_entitiesÚretainÚwarningsÚwarnÚget_differenceÚdebugr   ÚServerErrorÚTimedOutErrorÚFloodWaitErrorÚ
ValueErrorr5   Úend_differenceÚUnauthorizedErrorÚAuthKeyErrorr   ÚTypeNotFoundErrorr   ÚwarningÚRPCErrorr   ÚOSErrorÚasyncioÚsleepÚapply_differenceÚ_preprocess_updatesÚextendÚget_channel_differenceÚchannelÚ
channel_idÚend_channel_differencer   ÚTEMPORARY_SERVER_ISSUESÚ PersistentTimestampOutdatedErrorÚPersistentTimestampInvalidErrorÚChannelPrivateErrorÚChannelInvalidErrorÚBANNEDÚapply_channel_differenceÚcheck_deadlinesr   ÚtimeÚwait_forrD   ÚgetÚTimeoutErrorÚprocess_updatesr   ÚCancelledErrorÚ	ExceptionÚ	exception)r   Úwas_once_logged_inÚupdates_to_dispatchÚtaskÚget_diffÚdiffÚer   ÚusersÚchatsrr   ÚdeadlineÚdeadline_delayÚ	processedr   r(   r   Ú_update_loop  s   €
ü
ý

ý
ü
€
€
€
ÿý
€€ú

þý€
þý€ú
ýý€
þý
ÿýý€
þ€ú


þÿ
 �¦ [€ýzUpdateMethods._update_loopc              	   Ã   s^   �| j  ||¡ t | j tj d ||¡¡¡I d H  dd„ t	 
||¡D ƒ}|D ]}||_q'|S )Nc                 S   s   i | ]}t  |¡|“qS r   )r   Úget_peer_id)r@   Úxr   r   r   Ú
<dictcomp>þ  s    ÿz5UpdateMethods._preprocess_updates.<locals>.<dictcomp>)rH   rs   r   Úmaybe_asyncÚsessionÚprocess_entitiesr   ÚcontactsÚResolvedPeerÚ	itertoolsÚchainÚ	_entities)r   r   rŽ   r�   ÚentitiesÚur   r   r   rr   û  s   €$
ÿz!UpdateMethods._preprocess_updatesc              	   Ã   sâ   �dd„ }|   ¡ roztj| jdd�I d H  W q tjy    Y n tjy*   Y d S  ty2   Y qw |  ¡ I d H  | j 	¡ s@qz	| j 
|ƒ ¡ W n ttjfyV   Y d S w |  ¡ I d H  t | j ¡ ¡I d H  |   ¡ s	d S d S )Nc                   S   s   t  dd¡S )Nlûÿÿÿ         l            )ÚrandomÚ	randranger   r   r   r   rM     s    z/UpdateMethods._keepalive_loop.<locals>.<lambda>é<   )Útimeout)rR   ro   r�   r   rƒ   r…   r†   Ú_clean_exported_sendersÚ_senderÚ_transport_connectedÚ_keepalive_pingÚConnectionErrorr^   r   r—   r˜   Úsave)r   Úrndr   r   r   Ú_keepalive_loop  s4   €ÿÿ
ÿÝzUpdateMethods._keepalive_loopc                 Ã   sü  �d }| j jsz| jdd�I d H  W n	 ty   Y nw t| ||ƒ}| j ¡ D ]6}|D ]1}|tj }|r9| 	|¡ |tj
 }|rE| |¡ |tj }|rQ| |¡ |jr\| |¡I d H  q+q'| jD ]š\}}|t|ƒ }	|	snqa|jsy| | ¡I d H  | |	¡}
t |
¡rˆ|
I d H }
|
s‹qaz	||	ƒI d H  W qa tjy¯   t|dt|ƒƒ}| jt  d|¡ Y qa tjyÏ   t|dt|ƒƒ}| jt  d|t|	ƒj¡ Y  d S  tyû } z!t |t!j"ƒrà|  #¡ rñt|dt|ƒƒ}| jt  $d|¡ W Y d }~qad }~ww d S )NT)Ú
input_peerr   úEEvent handler "%s" already has an open conversation, ignoring new oneú=Event handler "%s" stopped chain of propagation for event %s.úUnhandled exception on %s)%rH   rI   Úget_mern   ÚEventBuilderDictÚ_conversationsÚvaluesr
   Ú
NewMessageÚ_on_new_messageÚMessageEditedÚ_on_editÚMessageReadÚ_on_readÚ_customÚ_check_customr2   r5   ÚresolvedÚresolveÚfilterÚinspectÚisawaitabler   ÚAlreadyInConversationErrorÚgetattrÚreprr\   r   rc   ÚStopPropagationr†   r4   ro   r…   rR   r‡   )r   ÚupdateÚothersÚbuiltÚconv_setÚconvr<   Úbuilderr0   r*   r¿   Únamer�   r   r   r   rT   ,  sr   €ÿ





€ò



þ

þ€ýäzUpdateMethods._dispatch_updatec                 Ã   sL  �| j D ]Ÿ\}}t|tjƒrqt||jƒsq|js!| | ¡I dH  | |¡}t 	|¡r0|I dH }|s3qz	||ƒI dH  W q t
jyW   t|dt|ƒƒ}| jt  d|¡ Y q tjyw   t|dt|ƒƒ}| jt  d|t|ƒj¡ Y  dS  ty£ } z!t|tjƒrˆ|  ¡ r™t|dt|ƒƒ}| jt  d|¡ W Y d}~qd}~ww dS )zO
        Dispatches a single, out-of-order event. Used by `AlbumHack`.
        Nr   r®   r¯   r°   )r2   r4   r
   r6   ÚEventr½   r¾   r¿   rÀ   rÁ   r   rÂ   rÃ   rÄ   r\   r   rc   rÅ   r5   r†   ro   r…   rR   r‡   )r   r*   rË   r0   r¿   rÌ   r�   r   r   r   Ú_dispatch_evento  sF   €



þ

þ€ýãzUpdateMethods._dispatch_eventc              
   Ã   sV   �z
|   ¡ I d H  W d S  ty* } z| jt  dt|ƒ|¡ W Y d }~d S d }~ww )Nz:Error executing high-level request after reconnect: %s: %s)r±   r†   r\   r   rl   r5   r]   rG   r   rm   r‡   )r   r�   r   r   r   Ú_handle_auto_reconnect˜  s   €üÿ€üz$UpdateMethods._handle_auto_reconnect)r   r   r   )r   r   r8   r?   )r   r   r   r!   r$   r)   r   r/   ÚCallbackr+   Úintr>   rC   rG   r“   rr   r¬   rT   rÎ   rÏ   r   r   r   r   r   %   sD    


/ýÿþ
ý4ýÿþý
ý'
ÿ

 q
	
(
C)r   c                   @   s"   e Zd ZdZd	dd„Zdd„ ZdS )
r²   zI
    Helper "dictionary" to return events from types and cache them.
    Úclientr   c                 C   s   || _ || _|| _d S r   )rÒ   rÆ   rÇ   )r   rÒ   rÆ   rÇ   r   r   r   Ú__init__Ê  s   
zEventBuilderDict.__init__c                 C   s€   z| j | W S  ty?   | | j| j| jj¡ }| j |< t|tƒr5| j|_	| jj
|_
| | j¡ | Y S |r;| j|_| Y S w r   )Ú__dict__ÚKeyErrorÚbuildrÆ   rÇ   rÒ   Ú_self_idr4   r   Úoriginal_updaterž   Ú_set_clientÚ_client)r   rË   r*   r   r   r   Ú__getitem__Ï  s   ÿ

ýõzEventBuilderDict.__getitem__N)rÒ   r   )r   r   r   Ú__doc__rÓ   rÛ   r   r   r   r   r²   Æ  s    
r²   )*ro   rÀ   rœ   r¡   Úsysr€   Ú	tracebackÚtypingÚloggingr`   Úcollectionsr   Úsqlite3r   ÚImportErrorr�   r†   Ú r
   r   r   Úevents.commonr   r   Útlr   r   Ú_updatesr   r   Úhelpersr   Úversionr   ÚTYPE_CHECKINGÚtelegramclientr   ÚCallableÚAnyrÐ   r   r²   r   r   r   r   Ú<module>   sF    
€ý     &