o
    "h}                     @   s:  d Z ddlZddlZddlZddlZddlmZmZ ddl	m
Z
 ddlmZ ddlmZmZmZmZmZmZ ddlmZmZmZ ddlmZ dd	lmZ dd
lmZmZ ddlm Z  ddl!m"Z" zddl#m$Z$m%Z% dZ&W n e'yw   dZ&Y nw erddl(m(Z( ddl)m*Z* edddZ+ee,Z-G dd dej.d Z/dS )z]This module contains the class Updater, which tries to make creating Telegram bots intuitive.    N)	CoroutineSequence)Path)TracebackType)TYPE_CHECKINGAnyCallableOptionalTypeVarUnion)
DEFAULT_80
DEFAULT_IPDefaultValue)
get_logger)build_repr_with_selected_attrs)DVType
TimePeriod)TelegramError)network_retry_loop)WebhookAppClassWebhookServerTF)socket)Bot_UpdaterTypeUpdater)boundc                !   @   s  e Zd ZdZdZ				dIddZd	ed
efddZdee	e
  dee
 dee d
dfddZd
efddZed
efddZdJddZdJddZdejddddddfded ed!ed"eee  d#ee d$eeegdf  d
dfd%d&Zded ed!ed#ee d"eee  d'ejd$eeegdf  d
dfd(d)Ze e!d*dddddddd+ddfd,e"e d-e"e d.ed/ee#ee$f  d0ee#ee$f  d!ed1ee d"eee  d#ee d2ee d3ed4ee d5ee#ee$d6f  d
dfd7d8Z%							+		dKd,ed-ed.ed!ed"eee  d/ee#ee$f  d0ee#ee$f  d#ee d1ee d'eej d2ee d3ed4ee d5ee#ee$d6f  d
dfd9d:Z&e'd;ed,ed-ed.ed
ef
d<d=Z(			>		+	dLd?ed1ee d"eee  d#ee d/ee) d@ed2ee d3ed4ee d
dfdAdBZ*dJdCdDZ+dJdEdFZ,dJdGdHZ-dS )Mr   a]  This class fetches updates for the bot either via long polling or by starting a webhook
    server. Received updates are enqueued into the :attr:`update_queue` and may be fetched from
    there to handle them appropriately.

    Instances of this class can be used as asyncio context managers, where

    .. code:: python

        async with updater:
            # code

    is roughly equivalent to

    .. code:: python

        try:
            await updater.initialize()
            # code
        finally:
            await updater.shutdown()

    .. seealso:: :meth:`__aenter__` and :meth:`__aexit__`.

    .. seealso:: :wiki:`Architecture Overview <Architecture>`,
        :wiki:`Builder Pattern <Builder-Pattern>`

    .. versionchanged:: 20.0

        * Removed argument and attribute ``user_sig_handler``
        * The only arguments and attributes are now :attr:`bot` and :attr:`update_queue` as now
          the sole purpose of this class is to fetch updates. The entry point to a PTB application
          is now :class:`telegram.ext.Application`.

    Args:
        bot (:class:`telegram.Bot`): The bot used with this Updater.
        update_queue (:class:`asyncio.Queue`): Queue for the updates.

    Attributes:
        bot (:class:`telegram.Bot`): The bot used with this Updater.
        update_queue (:class:`asyncio.Queue`): Queue for the updates.

    )
__lock__polling_cleanup_cb__polling_task__polling_task_stop_event_httpd_initialized_last_update_id_runningbotupdate_queuer$   r   r%   asyncio.Queue[object]c                 C   sH   || _ || _d| _d| _d| _d | _t | _d | _	t
 | _d | _d S )Nr   F)r$   r%   r"   r#   r!   r    asyncioLock_Updater__lock_Updater__polling_taskEvent!_Updater__polling_task_stop_event_Updater__polling_cleanup_cb)selfr$   r%    r/   H/var/www/html/venv/lib/python3.10/site-packages/telegram/ext/_updater.py__init__o   s   


zUpdater.__init__r.   returnc                    s6   z
|   I dH  W | S  ty   |  I dH   w )a0  
        |async_context_manager| :meth:`initializes <initialize>` the Updater.

        Returns:
            The initialized Updater instance.

        Raises:
            :exc:`Exception`: If an exception is raised during initialization, :meth:`shutdown`
                is called in this case.
        N)
initialize	Exceptionshutdownr.   r/   r/   r0   
__aenter__   s   zUpdater.__aenter__exc_typeexc_valexc_tbNc                    s   |   I dH  dS )zB|async_context_manager| :meth:`shuts down <shutdown>` the Updater.N)r5   )r.   r8   r9   r:   r/   r/   r0   	__aexit__   s   	zUpdater.__aexit__c                 C   s   t | | jdS )a  Give a string representation of the updater in the form ``Updater[bot=...]``.

        As this class doesn't implement :meth:`object.__str__`, the default implementation
        will be used, which is equivalent to :meth:`__repr__`.

        Returns:
            :obj:`str`
        )r$   )r   r$   r6   r/   r/   r0   __repr__   s   	zUpdater.__repr__c                 C   s   | j S N)r#   r6   r/   r/   r0   running   s   zUpdater.runningc                    s0   | j rtd dS | j I dH  d| _ dS )zInitializes the Updater & the associated :attr:`bot` by calling
        :meth:`telegram.Bot.initialize`.

        .. seealso::
            :meth:`shutdown`
        z$This Updater is already initialized.NT)r!   _LOGGERdebugr$   r3   r6   r/   r/   r0   r3      s   

zUpdater.initializec                    sH   | j rtd| jstd dS | j I dH  d| _td dS )z
        Shutdown the Updater & the associated :attr:`bot` by calling :meth:`telegram.Bot.shutdown`.

        .. seealso::
            :meth:`initialize`

        Raises:
            :exc:`RuntimeError`: If the updater is still running.
        zThis Updater is still running!z-This Updater is already shut down. Returning.NFzShut down of Updater complete)r>   RuntimeErrorr!   r?   r@   r$   r5   r6   r/   r/   r0   r5      s   

zUpdater.shutdowng        
   secondsr   poll_intervaltimeoutbootstrap_retriesallowed_updatesdrop_pending_updateserror_callbackc              
      s   |rt |rtd| j4 I dH Q | jrtd| js"tdd| _z&t  }| j	|||||||dI dH  t
d | I dH  t
d W n tyV   d	| _ w | jW  d  I dH  S 1 I dH sjw   Y  dS )
aO  Starts polling updates from Telegram.

        .. versionchanged:: 20.0
            Removed the ``clean`` argument in favor of :paramref:`drop_pending_updates`.

        .. versionchanged:: 22.0
            Removed the deprecated arguments ``read_timeout``, ``write_timeout``,
            ``connect_timeout``, and ``pool_timeout`` in favor of setting the timeouts via
            the corresponding methods of :class:`telegram.ext.ApplicationBuilder`. or
            by specifying the timeout via :paramref:`telegram.Bot.get_updates_request`.

        Args:
            poll_interval (:obj:`float`, optional): Time to wait between polling updates from
                Telegram in seconds. Default is ``0.0``.
            timeout (:obj:`int` | :class:`datetime.timedelta`, optional): Passed to
                :paramref:`telegram.Bot.get_updates.timeout`. Defaults to
                ``timedelta(seconds=10)``.

                .. versionchanged:: v22.2
                    |time-period-input|
            bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of
                will retry on failures on the Telegram server.

                * < 0 - retry indefinitely
                *   0 - no retries (default)
                * > 0 - retry up to X times

                .. versionchanged:: 21.11
                    The default value will be changed to from ``-1`` to ``0``. Indefinite retries
                    during bootstrapping are not recommended.
            allowed_updates (Sequence[:obj:`str`], optional): Passed to
                :meth:`telegram.Bot.get_updates`.

                .. versionchanged:: 21.9
                    Accepts any :class:`collections.abc.Sequence` as input instead of just a list
            drop_pending_updates (:obj:`bool`, optional): Whether to clean any pending updates on
                Telegram servers before actually starting to poll. Default is :obj:`False`.

                .. versionadded :: 13.4
            error_callback (Callable[[:exc:`telegram.error.TelegramError`], :obj:`None`],                 optional): Callback to handle :exc:`telegram.error.TelegramError` s that occur
                while calling :meth:`telegram.Bot.get_updates` during polling. Defaults to
                :obj:`None`, in which case errors will be logged. Callback signature::

                    def callback(error: telegram.error.TelegramError)

                Note:
                    The :paramref:`error_callback` must *not* be a :term:`coroutine function`! If
                    asynchronous behavior of the callback is wanted, please schedule a task from
                    within the callback.

        Returns:
            :class:`asyncio.Queue`: The update queue that can be filled from the main thread.

        Raises:
            :exc:`RuntimeError`: If the updater is already running or was not initialized.

        zYThe `error_callback` must not be a coroutine function! Use an ordinary function instead. N This Updater is already running!:This Updater was not initialized via `Updater.initialize`!T)rE   rF   rG   rI   rH   readyrJ   zWaiting for polling to startz%Polling updates from Telegram startedF)r'   iscoroutinefunction	TypeErrorr)   r>   rA   r!   r#   r+   _start_pollingr?   r@   waitr4   r%   )r.   rE   rF   rG   rH   rI   rJ   polling_readyr/   r/   r0   start_polling   s>   G

0zUpdater.start_pollingrM   c              
      s   t d j||dd dI d H  t d dtf fdd}dtdd fd	d
}	tjtfdd||p7|	d|jdddd_	d fdd}
|
_
|d urX|  d S d S )NzUpdater started (polling) )rI   webhook_urlrH   zBootstrap doner2   c               
      s   zj jj dI d H } W n! ty     ty1 } ztjd|d W Y d }~dS d }~ww | rTjs>td dS | D ]}j	|I d H  q@| d j
d _dS )NoffsetrF   rH   zcSomething went wrong processing the data received from Telegram. Received data was *not* processed!exc_infoTzYUpdater stopped unexpectedly. Pulled updates will be ignored and pulled again on restart.   )r$   get_updatesr"   r   r4   r?   criticalr>   r%   put	update_id)updatesexcupdaterH   r.   rF   r/   r0   polling_action_cbR  s6   		z1Updater._start_polling.<locals>.polling_action_cbra   c                 S   s   t jd| d d S )Nz-Exception happened while polling for updates.rX   )r?   	exception)ra   r/   r/   r0   default_error_callbackr  s   z6Updater._start_polling.<locals>.default_error_callbackc                          j S r=   r>   r/   r6   r/   r0   <lambda>z      z(Updater._start_polling.<locals>.<lambda>zPolling UpdatesrZ   )
is_running	action_cb	on_err_cbdescriptioninterval
stop_eventmax_retriesz"Updater:start_polling:polling_task)namec                      sT   t d zjjjtjdd dI d H  W d S  ty)   t d Y d S w )NzHCalling `get_updates` one more time to mark all fetched updates as read.r   rC   rV   a-  Error while calling `get_updates` one more time to mark all fetched updates as read: %s. Suppressing error to ensure graceful shutdown. When polling for updates is restarted, updates may be fetched again. Please adjust timeouts via `ApplicationBuilder` or the parameter `get_updates_request` of `Bot`.)	r?   r@   r$   r\   r"   dtm	timedeltar   re   r/   )rH   r.   r/   r0   _get_updates_cleanup  s   

z4Updater._start_polling.<locals>._get_updates_cleanupr2   N)r?   r@   
_bootstrapboolr   r'   create_taskr   r,   r*   r-   set)r.   rE   rF   rG   rI   rH   rM   rJ   rd   rf   ru   r/   rc   r0   rP   :  s8   


 
	zUpdater._start_pollingrT   (   listenporturl_pathcertkeyrU   
ip_addressmax_connectionssecret_tokenunixr   c                    s6  t std|r)d}t|tst|dt|ts#t|d|s)td| j4 I dH ^ | jr8td| js?tdd	| _z3t	
 }| jt|t||||||	||||
|||d
I dH  td | I dH  td W n ty   d| _ w | jW  d  I dH  S 1 I dH sw   Y  dS )a  
        Starts a small http server to listen for updates via webhook. If :paramref:`cert`
        and :paramref:`key` are not provided, the webhook will be started directly on
        ``http://listen:port/url_path``, so SSL can be handled by another
        application. Else, the webhook will be started on
        ``https://listen:port/url_path``. Also calls :meth:`telegram.Bot.set_webhook` as required.

        Important:
            If you want to use this method, you must install PTB with the optional requirement
            ``webhooks``, i.e.

            .. code-block:: bash

               pip install "python-telegram-bot[webhooks]"

        .. seealso:: :wiki:`Webhooks`

        .. versionchanged:: 13.4
            :meth:`start_webhook` now *always* calls :meth:`telegram.Bot.set_webhook`, so pass
            ``webhook_url`` instead of calling ``updater.bot.set_webhook(webhook_url)`` manually.
        .. versionchanged:: 20.0

            * Removed the ``clean`` argument in favor of :paramref:`drop_pending_updates` and
              removed the deprecated argument ``force_event_loop``.

        Args:
            listen (:obj:`str`, optional): IP-Address to listen on. Defaults to
                `127.0.0.1 <https://en.wikipedia.org/wiki/Localhost>`_.
            port (:obj:`int`, optional): Port the bot should be listening on. Must be one of
                :attr:`telegram.constants.SUPPORTED_WEBHOOK_PORTS` unless the bot is running
                behind a proxy. Defaults to ``80``.
            url_path (:obj:`str`, optional): Path inside url (http(s)://listen:port/<url_path>).
                Defaults to ``''``.
            cert (:class:`pathlib.Path` | :obj:`str`, optional): Path to the SSL certificate file.
            key (:class:`pathlib.Path` | :obj:`str`, optional): Path to the SSL key file.
            drop_pending_updates (:obj:`bool`, optional): Whether to clean any pending updates on
                Telegram servers before actually starting to poll. Default is :obj:`False`.

                .. versionadded :: 13.4
            bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of
                will retry on failures on the Telegram server.

                * < 0 - retry indefinitely
                *   0 - no retries (default)
                * > 0 - retry up to X times
            webhook_url (:obj:`str`, optional): Explicitly specify the webhook url. Useful behind
                NAT, reverse proxy, etc. Default is derived from :paramref:`listen`,
                :paramref:`port`, :paramref:`url_path`, :paramref:`cert`, and :paramref:`key`.
            ip_address (:obj:`str`, optional): Passed to :meth:`telegram.Bot.set_webhook`.
                Defaults to :obj:`None`.

                .. versionadded :: 13.4
            allowed_updates (Sequence[:obj:`str`], optional): Passed to
                :meth:`telegram.Bot.set_webhook`. Defaults to :obj:`None`.

                .. versionchanged:: 21.9
                    Accepts any :class:`collections.abc.Sequence` as input instead of just a list
            max_connections (:obj:`int`, optional): Passed to
                :meth:`telegram.Bot.set_webhook`. Defaults to ``40``.

                .. versionadded:: 13.6
            secret_token (:obj:`str`, optional): Passed to :meth:`telegram.Bot.set_webhook`.
                Defaults to :obj:`None`.

                When added, the web server started by this call will expect the token to be set in
                the ``X-Telegram-Bot-Api-Secret-Token`` header of an incoming request and will
                raise a :class:`http.HTTPStatus.FORBIDDEN <http.HTTPStatus>` error if either the
                header isn't set or it is set to a wrong token.

                .. versionadded:: 20.0
            unix (:class:`pathlib.Path` | :obj:`str` | :class:`socket.socket`, optional): Can be
                either:

                * the path to the unix socket file as :class:`pathlib.Path` or :obj:`str`. This
                  will be passed to `tornado.netutil.bind_unix_socket <https://www.tornadoweb.org/
                  en/stable/netutil.html#tornado.netutil.bind_unix_socket>`_ to create the socket.
                  If the Path does not exist, the file will be created.

                * or the socket itself. This option allows you to e.g. restrict the permissions of
                  the socket for improved security. Note that you need to pass the correct family,
                  type and socket options yourself.

                Caution:
                    This parameter is a replacement for the default TCP bind. Therefore, it is
                    mutually exclusive with :paramref:`listen` and :paramref:`port`. When using
                    this param, you must also run a reverse proxy to the unix socket and set the
                    appropriate :paramref:`webhook_url`.

                .. versionadded:: 20.8
                .. versionchanged:: 21.1
                    Added support to pass a socket instance itself.
        Returns:
            :class:`queue.Queue`: The update queue that can be filled from the main thread.

        Raises:
            :exc:`RuntimeError`: If the updater is already running or was not initialized.
        z`To use `start_webhook`, PTB must be installed via `pip install "python-telegram-bot[webhooks]"`.z|You can not pass unix and {0}, only use one. Unix if you want to initialize a unix socket, or {0} for a standard TCP server.r|   r}   zqSince you set unix, you also need to set the URL to the webhook of the proxy you run in front of the unix socket.NrK   rL   T)r|   r}   r~   r   r   rG   rI   rU   rH   rM   r   r   r   r   z#Waiting for webhook server to startzWebhook server startedF)WEBHOOKS_AVAILABLErA   
isinstancer   formatr)   r>   r!   r#   r'   r+   _start_webhook	get_valuer?   r@   rQ   r4   r%   )r.   r|   r}   r~   r   r   rG   rU   rH   rI   r   r   r   r   	error_msgwebhook_readyr/   r/   r0   start_webhook  sb   q


0zUpdater.start_webhookc              
      s  t d |dsd| }t|| j| j|}|d urC|d urCzttjj	}|
|| W n tjyB } ztd|d }~ww d }t|||||| _|	s`| j|rVdndt|||d}	| j|rjt| nd |||	||||dI d H  | jj|
dI d H  d S )	Nz Updater thread started (webhook)/zInvalid SSL Certificatehttpshttpprotocolr|   r}   r~   )r   rq   rI   rU   rH   r   r   r   )rM   )r?   r@   
startswithr   r$   r%   sslcreate_default_contextPurposeCLIENT_AUTHload_cert_chainSSLErrorr   r   r    _gen_webhook_urlr   r   rw   r   
read_bytesserve_forever)r.   r|   r}   r~   rG   rH   r   r   rI   rU   rM   r   r   r   r   appssl_ctxra   r/   r/   r0   r   O  sF   




zUpdater._start_webhookr   c                 C   s   |  d| d| | S )Nz://:r/   r   r/   r/   r0   r     s   zUpdater._gen_webhook_urlr[   rq   bootstrap_intervalc
              	      s   dt ffdd}
dt f fdd}ss0tfdd|
d|d	|d
I d	H  rEtfdd|d|d	|d
I d	H  d	S d	S )zPrepares the setup for fetching updates: delete or set the webhook and drop pending
        updates if appropriate. If there are unsuccessful attempts, this will retry as specified by
        :paramref:`max_retries`.
        r2   c                      s2   t d  rt d jj dI d H  dS )NzDeleting webhook-Dropping pending updates from Telegram server)rI   F)r?   r@   r$   delete_webhookr/   )rI   r.   r/   r0   bootstrap_del_webhook  s   

z1Updater._bootstrap.<locals>.bootstrap_del_webhookc                	      s>   t d rt d jj dI d H  dS )NzSetting webhookr   )urlcertificaterH   r   rI   r   r   F)r?   r@   r$   set_webhookr/   rH   r   rI   r   r   r   r.   rU   r/   r0   bootstrap_set_webhook  s   

	z1Updater._bootstrap.<locals>.bootstrap_set_webhookc                      rg   r=   rh   r/   r6   r/   r0   ri     rj   z$Updater._bootstrap.<locals>.<lambda>zBootstrap delete WebhookN)rk   rl   rn   ro   rp   rq   c                      rg   r=   rh   r/   r6   r/   r0   ri     rj   zBootstrap Set Webhook)rx   r   )r.   rq   rU   rH   rI   r   r   r   r   r   r   r   r/   r   r0   rw     s,    

zUpdater._bootstrapc              	      s   | j 4 I dH . | jstdtd d| _|  I dH  |  I dH  td W d  I dH  dS 1 I dH s<w   Y  dS )zStops the polling/webhook.

        .. seealso::
            :meth:`start_polling`, :meth:`start_webhook`

        Raises:
            :exc:`RuntimeError`: If the updater is not running.
        NzThis Updater is not running!zStopping UpdaterFzUpdater.stop() is complete)r)   r>   rA   r?   r@   r#   _stop_httpd_stop_pollingr6   r/   r/   r0   stop  s   	
.zUpdater.stopc                    s0   | j rtd | j  I dH  d| _ dS dS )z@Stops the Webhook server by calling ``WebhookServer.shutdown()``z4Waiting for current webhook connection to be closed.N)r    r?   r@   r5   r6   r/   r/   r0   r     s   

zUpdater._stop_httpdc                    s   | j rHtd | j  ttj | j I dH  W d   n1 s%w   Y  d| _ | j	  | j
rA| 
 I dH  d| _
dS td dS dS )z&Stops the polling task by awaiting it.z-Waiting background polling task to finish up.NzmNo polling cleanup callback defined. The last fetched updates may be fetched again on the next polling start.)r*   r?   r@   r,   rz   
contextlibsuppressr'   CancelledErrorclearr-   warningr6   r/   r/   r0   r     s    



zUpdater._stop_polling)r$   r   r%   r&   rv   )	NNNNNNr{   NN)NNr[   Nr{   N).__name__
__module____qualname____doc__	__slots__r1   r   r7   r	   typeBaseExceptionr   r;   strr<   propertyrx   r>   r3   r5   rs   rt   floatr   intr   r   r   rS   r'   r+   rP   r   r   r   r   r   r   r   staticmethodr   bytesrw   r   r   r   r/   r/   r/   r0   r   6   s`   +







k
	
j
	

 5
	

C 

	


A
)0r   r'   r   datetimers   r   collections.abcr   r   pathlibr   typesr   typingr   r   r   r	   r
   r   telegram._utils.defaultvaluer   r   r   telegram._utils.loggingr   telegram._utils.reprr   telegram._utils.typesr   r   telegram.errorr   telegram.ext._utils.networkloopr   "telegram.ext._utils.webhookhandlerr   r   r   ImportErrorr   telegramr   r   r   r?   AbstractAsyncContextManagerr   r/   r/   r/   r0   <module>   s6    