
    ՟f{G                       U d 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	 ddl
mZ ddlmZ ddlmZmZ ddlmZmZmZmZmZmZmZmZmZmZmZmZ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)m*Z*m+Z+m,Z,m-Z- dd
l.m/Z/ ddl0m1Z1 ddl2m3Z3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? ddl@mAZA ddlBmCZC ddlDmEZE ddlFmGZG ddlHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQ ddlRmSZS er&ddlTmTZT ddlUmVZV ddlWmXZXmYZY ddlZm[Z[ ddl\m]Z] ddl^m_Z_ dZ`eaebd<    e$dd !      Zc ed       Ze e-d      Zfej                  d"k\  reeN   Zhne%ed#deNf   eeN   f   ZheeheN      Zi e/ej      Zk G d$ d%el      Zm G d& d eeJeKeOeLeIeMf   ed          Zny)'z+This module contains the Application class.    N)defaultdict)deepcopy)Path)MappingProxyTypeTracebackType)TYPE_CHECKINGAnyAsyncContextManager	AwaitableCallable	CoroutineDefaultDictDict	GeneratorGenericListMappingNoReturnOptionalSequenceSetTupleTypeTypeVarUnion)Update)
DEFAULT_80
DEFAULT_IPDEFAULT_NONEDEFAULT_TRUEDefaultValue)
get_logger)build_repr_with_selected_attrs)SCTDVTypeODVInput)warn)TelegramError)BasePersistence)ContextTypes)ExtBot)BaseHandler)Updater)was_called_by)TrackingDict)	BDBTCCTCDJQRTUDConversationKeyHandlerCallback)PTBDeprecationWarning)socket)Message)ConversationHandlerJobQueue)InitApplicationBuilder)BaseUpdateProcessor)JobDEFAULT_GROUP_AppTypeApplication)bound      zasyncio.Future[object]c                   8     e Zd ZdZdZddee   ddf fdZ xZS )ApplicationHandlerStopa  
    Raise this in a handler or an error handler to prevent execution of any other handler (even in
    different groups).

    In order to use this exception in a :class:`telegram.ext.ConversationHandler`, pass the
    optional :paramref:`state` parameter instead of returning the next state:

    .. code-block:: python

        async def conversation_callback(update, context):
            ...
            raise ApplicationHandlerStop(next_state)

    Note:
        Has no effect, if the handler or error handler is run in a non-blocking way.

    Args:
        state (:obj:`object`, optional): The next state of the conversation.

    Attributes:
        state (:obj:`object`): Optional. The next state of the conversation.
    )stateNrJ   returnc                 0    t         |           || _        y N)super__init__rJ   )selfrJ   	__class__s     T/var/www/cvtools/html/venv/lib/python3.12/site-packages/telegram/ext/_application.pyrO   zApplicationHandlerStop.__init__   s    ',
    rM   )	__name__
__module____qualname____doc__	__slots__r   objectrO   __classcell__)rQ   s   @rR   rI   rI   h   s,    . I-hv. -$ - -rS   rI   c            #          e Zd ZdZej
                  dk\  rdndZdddedd	d
ee	   de
dddeeeeef      deeeeef   deedgeeedf   f      deedgeeedf   f      deedgeeedf   f      fdZdedefdZdeee      dee   dee   ddfdZdefdZedefd       Zede fd       Z!eded   fd       Z"ed{d        Z#e$de%fd!       Z&e$d|d"       Z'd}d#Z(d}d$Z)d~d&Z*d}d'Z+d}d(Z,d}d)Z-d}d*Z.d}d+Z/d,d-d.e0e0e0e0ddd/e0fd0e1d1e d2e d3e2e1   d4e2e1   d5e2e1   d6e2e1   d7ee3e      d8ee   d9ed:e2e4e       ddfd;Z5e6e7d<ddd=ddddd>d/e0ddfd?e8e   d@e8e    dAedBee9ee:f      dCee9ee:f      d2e dDee   d7ee3e      d8ee   dEee   dFe d9ed:e2e4e       dGee   dHee9ee:dIf      ddf dJZ;	 ddKed:e2e4e       d9eddfdLZ<	 dddMdNe=e>   dOee?   dPee   ddQfdRZ@	 	 	 ddNe=e>   dOee?   dSedPee   ddQf
dTZAdUeBj                  ddfdVZD	 	 ddNe=e>   dOee?   dSede>fdWZEd}dXZFd}dYZGdOe?ddfdZZHdOe?ddfd[ZIeJfd%eKeeef   d\e ddfd]ZLeMfd^e9e9e3eKeeef      eNeKeeef      f   eOe e9e3eKeeef      eNeKeeef      f   f   f   d\e9e ePe    f   ddfd_ZQeJfd%eKeeef   d\e ddfd`ZRdae ddfdbZSdce ddfddZT	 	 	 ddeedf   dgee    dhee    ddfdiZUdddjdOee?   dkedl   ddfdmZV	 ddneeWe       doeeWe       ddfdpZXd}dqZYd}drZZd}dsZ[e\fdte]e?edf   due8e   ddfdvZ^dte]e?edf   ddfdwZ_	 	 ddOee?   dxe`dkedy   dNeeae>      def
dzZby)rC   a  This class dispatches all kinds of updates to its registered handlers, and is the entry
    point to a PTB application.

    Tip:
         This class may not be initialized directly. Use :class:`telegram.ext.ApplicationBuilder`
         or :meth:`builder` (for convenience).

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

    .. code:: python

        async with application:
            # code

    is roughly equivalent to

    .. code:: python

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

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

    This class is a :class:`~typing.Generic` class and accepts six type variables:

    1. The type of :attr:`bot`. Must be :class:`telegram.Bot` or a subclass of that class.
    2. The type of the argument ``context`` of callback functions for (error) handlers and jobs.
       Must be :class:`telegram.ext.CallbackContext` or a subclass of that class. This must be
       consistent with the following types.
    3. The type of the values of :attr:`user_data`.
    4. The type of the values of :attr:`chat_data`.
    5. The type of :attr:`bot_data`.
    6. The type of :attr:`job_queue`. Must either be :class:`telegram.ext.JobQueue` or a subclass
       of that or :obj:`None`.

    Examples:
        :any:`Echo Bot <examples.echobot>`

    .. seealso:: :wiki:`Your First Bot <Extensions---Your-first-Bot>`,
        :wiki:`Architecture Overview <Architecture>`

    .. versionchanged:: 20.0

        * Initialization is now done through the :class:`telegram.ext.ApplicationBuilder`.
        * Removed the attribute ``groups``.

    Attributes:
        bot (:class:`telegram.Bot`): The bot object that should be passed to the handlers.
        update_queue (:class:`asyncio.Queue`): The synchronized queue that will contain the
            updates.
        updater (:class:`telegram.ext.Updater`): Optional. The updater used by this application.
        chat_data (:obj:`types.MappingProxyType`): A dictionary handlers can use to store data for
            the chat. For each integer chat id, the corresponding value of this mapping is
            available as :attr:`telegram.ext.CallbackContext.chat_data` in handler callbacks for
            updates from that chat.

            .. versionchanged:: 20.0
                :attr:`chat_data` is now read-only. Note that the values of the mapping are still
                mutable, i.e. editing ``context.chat_data`` within a handler callback is possible
                (and encouraged), but editing the mapping ``application.chat_data`` itself is not.

            .. tip::

                * Manually modifying :attr:`chat_data` is almost never needed and unadvisable.
                * Entries are never deleted automatically from this mapping. If you want to delete
                  the data associated with a specific chat, e.g. if the bot got removed from that
                  chat, please use :meth:`drop_chat_data`.

        user_data (:obj:`types.MappingProxyType`): A dictionary handlers can use to store data for
            the user. For each integer user id, the corresponding value of this mapping is
            available as :attr:`telegram.ext.CallbackContext.user_data` in handler callbacks for
            updates from that user.

            .. versionchanged:: 20.0
                :attr:`user_data` is now read-only. Note that the values of the mapping are still
                mutable, i.e. editing ``context.user_data`` within a handler callback is possible
                (and encouraged), but editing the mapping ``application.user_data`` itself is not.

            .. tip::

               * Manually modifying :attr:`user_data` is almost never needed and unadvisable.
               * Entries are never deleted automatically from this mapping. If you want to delete
                 the data associated with a specific user, e.g. if that user blocked the bot,
                 please use :meth:`drop_user_data`.

        bot_data (:obj:`dict`): A dictionary handlers can use to store data for the bot.
        persistence (:class:`telegram.ext.BasePersistence`): The persistence class to
            store data that should be persistent over restarts.
        handlers (Dict[:obj:`int`, List[:class:`telegram.ext.BaseHandler`]]): A dictionary mapping
            each handler group to the list of handlers registered to that group.

            .. seealso::
                :meth:`add_handler`, :meth:`add_handlers`.
        error_handlers (Dict[:term:`coroutine function`, :obj:`bool`]): A dictionary where the keys
            are error handlers and the values indicate whether they are to be run blocking.

            .. seealso::
                :meth:`add_error_handler`
        context_types (:class:`telegram.ext.ContextTypes`): Specifies the types used by this
            dispatcher for the ``context`` argument of handler and job callbacks.
        post_init (:term:`coroutine function`): Optional. A callback that will be executed by
            :meth:`Application.run_polling` and :meth:`Application.run_webhook` after initializing
            the application via :meth:`initialize`.
        post_shutdown (:term:`coroutine function`): Optional. A callback that will be executed by
            :meth:`Application.run_polling` and :meth:`Application.run_webhook` after shutting down
            the application via :meth:`shutdown`.
        post_stop (:term:`coroutine function`): Optional. A callback that will be executed by
            :meth:`Application.run_polling` and :meth:`Application.run_webhook` after stopping
            the application via :meth:`stop`.

            .. versionadded:: 20.1

    )rF      )__create_task_tasks__update_fetcher_task__update_persistence_event__update_persistence_lock__update_persistence_task__stop_running_marker
_chat_data&_chat_ids_to_be_deleted_in_persistence&_chat_ids_to_be_updated_in_persistence#_conversation_handler_conversations_initialized
_job_queue_running_update_processor
_user_data&_user_ids_to_be_deleted_in_persistence&_user_ids_to_be_updated_in_persistencebotbot_data	chat_datacontext_typeserror_handlershandlerspersistence	post_initpost_shutdown	post_stopupdate_queueupdater	user_data__weakref__ rP   z$Application[BT, CCT, UD, CD, BD, JQ]rn   rx   zasyncio.Queue[object]ry   	job_queueupdate_processorr?   rt   rq   ru   Nrv   rw   c       
         B   t        t        j                         t        t              j
                  j                         dz        st        dd       || _        || _	        || _
        || _        i | _        i | _        || _        |	| _        |
| _        || _        | j                  j%                         | _        t'        | j                  j(                        | _        t'        | j                  j,                        | _        t1        | j*                        | _        t1        | j.                        | _        d | _        |rt5        |t6              st9        d      || _        t;               | _        t;               | _        t;               | _         t;               | _!        i | _"        d| _#        d| _$        || _%        d | _&        d | _'        tQ        jR                         | _*        tQ        jV                         | _,        t;               | _-        tQ        jR                         | _.        y )Nz_applicationbuilder.pyzE`Application` instances should be built via the `ApplicationBuilder`.   
stacklevelz9persistence must be based on telegram.ext.BasePersistenceF)/r.   inspectcurrentframer   __file__parentresolver'   rn   rx   rq   ry   rs   rr   ru   rv   rw   rj   ro   r   rz   rk   rp   rc   r   rt   
isinstancer)   	TypeErrorsetre   rm   rd   rl   rf   rg   ri   rh   !_Application__update_fetcher_task%_Application__update_persistence_taskasyncioEvent&_Application__update_persistence_eventLock%_Application__update_persistence_lock_Application__create_task_tasks!_Application__stop_running_marker)rP   rn   rx   ry   r}   r~   rt   rq   ru   rv   rw   s              rR   rO   zApplication.__init__&  s   (   "DN$9$9$A$A$CF^$^
 W
 3?<I*1EG  	
  	
  	
  	 "2 ..7790;D<N<N<X<X0Y0;D<N<N<X<X0Y+;DOO+L+;DOO+LBFz+GWXX& AD3@C3@C3@C3  	0
 "'=A"AE&*1--/')0&69e %,]]_"rS   rK   c                    K   	 | j                          d{    | S 7 # t        $ r | j                          d{  7    w xY ww)a  |async_context_manager| :meth:`initializes <initialize>` the App.

        Returns:
            The initialized App instance.

        Raises:
            :exc:`Exception`: If an exception is raised during initialization, :meth:`shutdown`
                is called in this case.
        N)
initialize	ExceptionshutdownrP   s    rR   
__aenter__zApplication.__aenter__w  sG     	//### 	 $ 	--/!!	s.   A    A  A?AAexc_typeexc_valexc_tbc                 @   K   | j                          d{    y7 w)z>|async_context_manager| :meth:`shuts down <shutdown>` the App.N)r   )rP   r   r   r   s       rR   	__aexit__zApplication.__aexit__  s      mmos   c                 0    t        | | j                        S )a"  Give a string representation of the application in the form ``Application[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`
        )rn   )r#   rn   r   s    rR   __repr__zApplication.__repr__  s     .dAArS   c                     | j                   S )z}:obj:`bool`: Indicates if this application is running.

        .. seealso::
            :meth:`start`, :meth:`stop`
        )ri   r   s    rR   runningzApplication.running  s     }}rS   c                 .    | j                   j                  S )a  :obj:`int`: The number of concurrent updates that will be processed in parallel. A
        value of ``0`` indicates updates are *not* being processed concurrently.

        .. versionchanged:: 20.4
            This is now just a shortcut to :attr:`update_processor.max_concurrent_updates
            <telegram.ext.BaseUpdateProcessor.max_concurrent_updates>`.

        .. seealso:: :wiki:`Concurrency`
        )rj   max_concurrent_updatesr   s    rR   concurrent_updateszApplication.concurrent_updates  s     %%<<<rS   zJobQueue[CCT]c                 L    | j                   t        dd       | j                   S )z
        :class:`telegram.ext.JobQueue`: The :class:`JobQueue` used by the
            :class:`telegram.ext.Application`.

        .. seealso:: :wiki:`Job Queue <Extensions---JobQueue>`
        zqNo `JobQueue` set up. To use `JobQueue`, you must install PTB via `pip install "python-telegram-bot[job-queue]"`.r   r   )rh   r'   r   s    rR   r}   zApplication.job_queue  s+     ??"B
 rS   c                     | j                   S )z:class:`telegram.ext.BaseUpdateProcessor`: The update processor used by this
        application.

        .. seealso:: :wiki:`Concurrency`

        .. versionadded:: 20.4
        )rj   r   s    rR   r~   zApplication.update_processor  s     %%%rS   c                      t         rM   )
SystemExitr|   rS   rR   _raise_system_exitzApplication._raise_system_exit  s    rS   c                      ddl m}   |        S )ztConvenience method. Returns a new :class:`telegram.ext.ApplicationBuilder`.

        .. versionadded:: 20.0
        r   ApplicationBuilder)telegram.extr   r   s    rR   builderzApplication.builder  s     	4!##rS   c                 2    | j                   st        d      y )NzBThis Application was not initialized via `Application.initialize`!)rg   RuntimeErrorr   s    rR   _check_initializedzApplication._check_initialized  s       T  !rS   c                   K   | j                   rt        j                  d       y| j                  j	                          d{    | j
                  j	                          d{    | j                  r"| j                  j	                          d{    | j                  sd| _         y| j                          d{    ddl	m
} t        j                  j                  | j                  j                               D ]B  }t!        ||      s|j"                  s|j$                  s*| j'                  |       d{    D d| _         | j(                  j+                          y7 %7 7 7 7 2w)a<  Initializes the Application by initializing:

        * The :attr:`bot`, by calling :meth:`telegram.Bot.initialize`.
        * The :attr:`updater`, by calling :meth:`telegram.ext.Updater.initialize`.
        * The :attr:`persistence`, by loading persistent conversations and data.
        * The :attr:`update_processor` by calling
          :meth:`telegram.ext.BaseUpdateProcessor.initialize`.

        Does *not* call :attr:`post_init` - that is only done by :meth:`run_polling` and
        :meth:`run_webhook`.

        .. seealso::
            :meth:`shutdown`
        z(This Application is already initialized.NTr   r<   )rg   _LOGGERdebugrn   r   rj   ry   rt   _initialize_persistence*telegram.ext._handlers.conversationhandlerr<   	itertoolschainfrom_iterablers   valuesr   
persistentname_add_ch_to_persistencer   clear)rP   r<   handlers      rR   r   zApplication.initialize  s,     MMDEhh!!###$$//111<<,,))+++ $D**,,, 	S !44T]]5I5I5KL 	;G'#67G<N<NSZS_S_11':::	; !""((*- 	$1 , 	- ;sm   A E3E'!E3$E*%-E3E-+E3>E/?AE3E3E3*E3>E1?)E3*E3-E3/E31E3r   c                 t   K   | j                   j                  |j                  |        d {          y 7 	wrM   )rf   updater   )rP   r   s     rR   r   z"Application._add_ch_to_persistence  s.     007711$77	
7s   *86
8c                 d  K   | j                   rt        d      | j                  st        j	                  d       y| j
                  j                          d{    | j                  j                          d{    | j                  r"| j                  j                          d{    | j                  rdt        j	                  d       | j                          d{    | j                  j                          d{    t        j	                  d       d| _        y7 7 7 7 I7 )w)a  Shuts down the Application by shutting down:

        * :attr:`bot` by calling :meth:`telegram.Bot.shutdown`
        * :attr:`updater` by calling :meth:`telegram.ext.Updater.shutdown`
        * :attr:`persistence` by calling :meth:`update_persistence` and
          :meth:`BasePersistence.flush`
        * :attr:`update_processor` by calling :meth:`telegram.ext.BaseUpdateProcessor.shutdown`

        Does *not* call :attr:`post_shutdown` - that is only done by :meth:`run_polling` and
        :meth:`run_webhook`.

        .. seealso::
            :meth:`initialize`

        Raises:
            :exc:`RuntimeError`: If the application is still :attr:`running`.
        z"This Application is still running!z1This Application is already shut down. Returning.Nz/Updating & flushing persistence before shutdownzUpdated and flushed persistenceF)r   r   rg   r   r   rn   r   rj   ry   rt   update_persistenceflushr   s    rR   r   zApplication.shutdown  s     $ <<CDD  MMMNhh!!!$$--///<<,,'')))MMKL))+++""((***MM;<! 	"/ * ,*sZ   AD0D&!D0;D(<-D0)D**8D0"D,#!D0D."D0(D0*D0,D0.D0c                 8  K   | j                   sy| j                   j                  j                  r;| j                  j	                  | j                   j                          d{          | j                   j                  j                  r;| j                  j	                  | j                   j                          d{          | j                   j                  j                  r}| j                   j                          d{   | _	        t        | j                  | j                  j                        s,t        d| j                  j                  j                         | j                   j                  j                  r| j                   j"                  t| j                   j%                          d{   }|Ot        |t&              rt)        |      dk7  rt        d      | j                   j"                  j+                  |       yyyy7 7 U7 7 aw)zHThis method basically just loads all the data by awaiting the BP methodsNzbot_data must be of type r   z)callback_data must be a tuple of length 2)rt   
store_datarz   rk   r   get_user_datarp   rc   get_chat_dataro   get_bot_datar   rq   
ValueErrorrT   callback_datarn   callback_data_cacheget_callback_datatuplelenload_persistence_data)rP   persistent_datas     rR   r   z#Application._initialize_persistence;  s    &&00OO"")9)9)G)G)I#IJ&&00OO"")9)9)G)G)I#IJ&&//"&"2"2"?"?"AADMdmmT-?-?-H-HI /0B0B0K0K0T0T/UV  &&44HH((4$($4$4$F$F$HHO*!/59S=QUV=V$%PQQ,,BB# + 5 5 $J#IA IsL   A H"H#AH=H>AHHB2H6H7AHHHHc                   K   | j                   rt        d      | j                          d| _        | j                  j                          	 | j                  rWt        j                  | j                         d| j                  j                   d      | _        t        j                  d       | j                  r7| j                  j!                          d{    t        j                  d       t        j                  | j#                         d| j                  j                   d	      | _        t        j'                  d
       y7 q# t(        $ r	 d| _         w xY ww)a  Starts

        * a background task that fetches updates from :attr:`update_queue` and processes them via
          :meth:`process_update`.
        * :attr:`job_queue`, if set.
        * a background task that calls :meth:`update_persistence` in regular intervals, if
          :attr:`persistence` is set.

        Note:
            This does *not* start fetching updates from Telegram. To fetch updates, you need to
            either start :attr:`updater` manually or use one of :meth:`run_polling` or
            :meth:`run_webhook`.

        Tip:
            When using a custom logic for startup and shutdown of the application, eventual
            cancellation of pending tasks should happen only `after` :meth:`stop` has been called
            in order to ensure that the tasks mentioned above are not cancelled prematurely.

        .. seealso::
            :meth:`stop`

        Raises:
            :exc:`RuntimeError`: If the application is already running or was not initialized.
        z$This Application is already running!TApplication:z:persistence_updaterr   z%Loop for updating persistence startedNzJobQueue startedz:update_fetcherzApplication startedF)r   r   r   ri   r   r   rt   r   create_task_persistence_updaterrn   idr   r   r   rh   start_update_fetcherr   infor   r   s    rR   r   zApplication.startX  s    2 <<EFF!''--/	181D1D--/'}4HI2. EFoo++---01)0)<)<$$&|DHHKK=-X*D& LL./ .  	!DM	s2   A	E!BE E
A0E 	E!
E EE!c                   K   | j                   st        d      d| _        | j                  j	                          t
        j                  d       | j                  r| j                  j                         r	 | j                  j                          nr| j                  j                  t               d{    t
        j                  d       | j                  j!                          d{    | j                   d{    t
        j                  d	       | j"                  rNt
        j                  d
       | j"                  j%                  d       d{    t
        j                  d       t
        j                  d       t'        j(                  | j*                  ddi d{    | j,                  ri| j.                  r]t
        j                  d       | j0                  j3                          | j.                   d{    | j0                  j	                          t
        j                  d       y# t        $ r#}t
        j                  d|d       Y d}~]d}~ww xY w7 7 7 p7 7 7 qw)a  Stops the process after processing any pending updates or tasks created by
        :meth:`create_task`. Also stops :attr:`job_queue`, if set.
        Finally, calls :meth:`update_persistence` and :meth:`BasePersistence.flush` on
        :attr:`persistence`, if set.

        Warning:
            Once this method is called, no more updates will be fetched from :attr:`update_queue`,
            even if it's not empty.

        .. seealso::
            :meth:`start`

        Note:
            * This does *not* stop :attr:`updater`. You need to either manually call
              :meth:`telegram.ext.Updater.stop` or use one of :meth:`run_polling` or
              :meth:`run_webhook`.
            * Does *not* call :attr:`post_stop` - that is only done by
              :meth:`run_polling` and :meth:`run_webhook`.

        Raises:
            :exc:`RuntimeError`: If the application is not running.
        z This Application is not running!Fz2Application is stopping. This might take a moment.zZFetching updates was aborted due to %r. Suppressing exception to ensure graceful shutdown.Texc_infoNz Waiting for update_queue to joinz(Application stopped fetching of updates.z"Waiting for running jobs to finish)waitzJobQueue stoppedz/Waiting for `create_task` calls to be processedreturn_exceptionsz&Waiting for persistence loop to finishzApplication.stop() complete)r   r   ri   r   r   r   r   r   doneresultBaseExceptioncriticalrx   put_STOP_SIGNALr   joinrh   stopr   gatherr   rt   r   r   r   )rP   excs     rR   r   zApplication.stop  s    . ||ABB""((*IJ %%))..0..557 ''++L999@A'',,...0000@A??MM>?//&&D&111MM,-GHnnd66O$OOO  > >MMBC++//10000++11323; % $$A!%	 %   :.0
 2 	P 1s   A4I97H: #I94I)56I9+I,,I9?I/ AI9I2AI9*I5+AI9I74I9:	I&I!I9!I&&I9,I9/I92I95I97I9c                     | j                   r#t        j                         j                          y| j                  j                          | j                  st        j                  d       yy)a|  This method can be used to stop the execution of :meth:`run_polling` or
        :meth:`run_webhook` from within a handler, job or error callback. This allows a graceful
        shutdown of the application, i.e. the methods listed in :attr:`run_polling` and
        :attr:`run_webhook` will still be executed.

        This method can also be called within :meth:`post_init`. This allows for a graceful,
        early shutdown of the application if some condition is met (e.g., a database connection
        could not be established).

        Note:
            If the application is not running and this method is not called within
            :meth:`post_init`, this method does nothing.

        Warning:
            This method is designed to for use in combination with :meth:`run_polling` or
            :meth:`run_webhook`. Using this method in combination with a custom logic for starting
            and stopping the application is not guaranteed to work as expected. Use at your own
            risk.

        .. versionadded:: 20.5

        .. versionchanged:: 21.2
            Added support for calling within :meth:`post_init`.
        zVApplication is not running and not initialized. `stop_running()` likely has no effect.N)	r   r   get_running_loopr   r   r   rg   r   r   r   s    rR   stop_runningzApplication.stop_running  sS    2 << $$&++-&&**,$$! %rS   g        
   Tpoll_intervaltimeoutbootstrap_retriesread_timeoutwrite_timeoutconnect_timeoutpool_timeoutallowed_updatesdrop_pending_updates
close_loopstop_signalsc                      j                   st        d      ||||ft        fdz  k7  rt        t	        dd      d       dt
        dd	f fd
} j                   j                   j                  |||||||||	|
      |
|      S )a  Convenience method that takes care of initializing and starting the app,
        polling updates from Telegram using :meth:`telegram.ext.Updater.start_polling` and
        a graceful shutdown of the app on exit.

        |app_run_shutdown| :paramref:`stop_signals`.

        The order of execution by :meth:`run_polling` is roughly as follows:

        - :meth:`initialize`
        - :meth:`post_init`
        - :meth:`telegram.ext.Updater.start_polling`
        - :meth:`start`
        - Run the application until the users stops it
        - :meth:`telegram.ext.Updater.stop`
        - :meth:`stop`
        - :meth:`post_stop`
        - :meth:`shutdown`
        - :meth:`post_shutdown`

        A small wrapper is passed to :paramref:`telegram.ext.Updater.start_polling.error_callback`
        which forwards errors occurring during polling to
        :meth:`registered error handlers <add_error_handler>`. The update parameter of the callback
        will be set to :obj:`None`.

        .. include:: inclusions/application_run_tip.rst

        Args:
            poll_interval (:obj:`float`, optional): Time to wait between polling updates from
                Telegram in seconds. Default is ``0.0``.
            timeout (:obj:`int`, optional): Passed to
                :paramref:`telegram.Bot.get_updates.timeout`. Default is ``10`` seconds.
            bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of the
                :class:`telegram.ext.Updater` will retry on failures on the Telegram server.

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

            read_timeout (:obj:`float`, optional): Value to pass to
                :paramref:`telegram.Bot.get_updates.read_timeout`. Defaults to
                :attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.

                .. versionchanged:: 20.7
                    Defaults to :attr:`~telegram.request.BaseRequest.DEFAULT_NONE` instead of
                    ``2``.

                .. deprecated:: 20.7
                    Deprecated in favor of setting the timeout via
                    :meth:`telegram.ext.ApplicationBuilder.get_updates_read_timeout`.
            write_timeout (:obj:`float` | :obj:`None`, optional): Value to pass to
                :paramref:`telegram.Bot.get_updates.write_timeout`. Defaults to
                :attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.

                .. deprecated:: 20.7
                    Deprecated in favor of setting the timeout via
                    :meth:`telegram.ext.ApplicationBuilder.get_updates_write_timeout`.
            connect_timeout (:obj:`float` | :obj:`None`, optional): Value to pass to
                :paramref:`telegram.Bot.get_updates.connect_timeout`. Defaults to
                :attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.

                .. deprecated:: 20.7
                    Deprecated in favor of setting the timeout via
                    :meth:`telegram.ext.ApplicationBuilder.get_updates_connect_timeout`.
            pool_timeout (:obj:`float` | :obj:`None`, optional): Value to pass to
                :paramref:`telegram.Bot.get_updates.pool_timeout`. Defaults to
                :attr:`~telegram.request.BaseRequest.DEFAULT_NONE`.

                .. deprecated:: 20.7
                    Deprecated in favor of setting the timeout via
                    :meth:`telegram.ext.ApplicationBuilder.get_updates_pool_timeout`.
            drop_pending_updates (:obj:`bool`, optional): Whether to clean any pending updates on
                Telegram servers before actually starting to poll. Default is :obj:`False`.
            allowed_updates (List[:obj:`str`], optional): Passed to
                :meth:`telegram.Bot.get_updates`.
            close_loop (:obj:`bool`, optional): If :obj:`True`, the current event loop will be
                closed upon shutdown. Defaults to :obj:`True`.

                .. seealso::
                    :meth:`asyncio.loop.close`
            stop_signals (Sequence[:obj:`int`] | :obj:`None`, optional): Signals that will shut
                down the app. Pass :obj:`None` to not use stop signals.
                Defaults to :data:`signal.SIGINT`, :data:`signal.SIGTERM` and
                :data:`signal.SIGABRT` on non Windows platforms.

                Caution:
                    Not every :class:`asyncio.AbstractEventLoop` implements
                    :meth:`asyncio.loop.add_signal_handler`. Most notably, the standard event loop
                    on Windows, :class:`asyncio.ProactorEventLoop`, does not implement this method.
                    If this method is not available, stop signals can not be set.

        Raises:
            :exc:`RuntimeError`: If the Application does not have an :class:`telegram.ext.Updater`.
        zLApplication.run_polling is only available if the application has an Updater.   z20.6z|Setting timeouts via `Application.run_polling` is deprecated. Please use `ApplicationBuilder.get_updates_*_timeout` instead.r   r   r   rK   Nc                 J    j                  j                  | d              y N)errorr   )r   process_error)r   rP   s    rR   error_callbackz/Application.run_polling.<locals>.error_callbackn  s!    T//c$/GHrS   )
r   r   r   r   r   r   r   r   r   r  updater_coroutiner   r   )ry   r   r   r'   r9   r(   _Application__runstart_polling)rP   r   r   r   r   r   r   r   r   r   r   r   r  s   `            rR   run_pollingzApplication.run_polling  s    V ||^  -,G\O^_L_`%U
 	I 	I$ 	I zz"ll88+"3)+ /) /%9- 9  "%  
 	
rS    r   (   listenporturl_pathcertkeywebhook_url
ip_addressmax_connectionssecret_tokenunixr:   c                     | j                   st        d      | j                  | j                   j                  |||||||	|||
|||      ||      S )ab  Convenience method that takes care of initializing and starting the app,
        listening for updates from Telegram using :meth:`telegram.ext.Updater.start_webhook` and
        a graceful shutdown of the app on exit.

        |app_run_shutdown| :paramref:`stop_signals`.

        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.

        The order of execution by :meth:`run_webhook` is roughly as follows:

        - :meth:`initialize`
        - :meth:`post_init`
        - :meth:`telegram.ext.Updater.start_webhook`
        - :meth:`start`
        - Run the application until the users stops it
        - :meth:`telegram.ext.Updater.stop`
        - :meth:`stop`
        - :meth:`post_stop`
        - :meth:`shutdown`
        - :meth:`post_shutdown`

        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]"

        .. include:: inclusions/application_run_tip.rst

        .. seealso::
            :wiki:`Webhooks`

        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. 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.
            bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of the
                :class:`telegram.ext.Updater` 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`.
            allowed_updates (List[:obj:`str`], optional): Passed to
                :meth:`telegram.Bot.set_webhook`.
            drop_pending_updates (:obj:`bool`, optional): Whether to clean any pending updates on
                Telegram servers before actually starting to poll. Default is :obj:`False`.
            ip_address (:obj:`str`, optional): Passed to :meth:`telegram.Bot.set_webhook`.
            max_connections (:obj:`int`, optional): Passed to
                :meth:`telegram.Bot.set_webhook`. Defaults to ``40``.
            close_loop (:obj:`bool`, optional): If :obj:`True`, the current event loop will be
                closed upon shutdown. Defaults to :obj:`True`.

                .. seealso::
                    :meth:`asyncio.loop.close`
            stop_signals (Sequence[:obj:`int`] | :obj:`None`, optional): Signals that will shut
                down the app. Pass :obj:`None` to not use stop signals.
                Defaults to :data:`signal.SIGINT`, :data:`signal.SIGTERM` and
                :data:`signal.SIGABRT`.

                Caution:
                    Not every :class:`asyncio.AbstractEventLoop` implements
                    :meth:`asyncio.loop.add_signal_handler`. Most notably, the standard event loop
                    on Windows, :class:`asyncio.ProactorEventLoop`, does not implement this method.
                    If this method is not available, stop signals can not be set.
            secret_token (:obj:`str`, optional): Secret token to ensure webhook requests originate
                from Telegram. See :paramref:`telegram.Bot.set_webhook.secret_token` for more
                details.

                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.
        zLApplication.run_webhook is only available if the application has an Updater.)r
  r  r  r  r  r   r   r  r   r  r  r  r  r  )ry   r   r  start_webhook)rP   r
  r  r  r  r  r   r  r   r   r  r  r   r   r  r  s                   rR   run_webhookzApplication.run_webhook  sz    B ||^  zz"ll88!"3%9' /% /) 9  "%#  
 	
rS   r  c                 
   t        j                         }|t        u rFt        j                         dk7  r/t
        j                  t
        j                  t
        j                  f}	 t        |t              s'|xs g D ]  }|j                  || j                           	 |j                  | j!                                | j"                  r |j                  | j#                  |              | j$                  j'                         rt(        j+                  d       	 |j-                          	 | j.                  j0                  r)|j                  | j.                  j3                                | j0                  rK|j                  | j3                                | j4                  r |j                  | j5                  |              |j                  | j7                                | j8                  r |j                  | j9                  |              |r|j-                          y y |j                  |       |j                  | j;                                |j=                          |j-                          	 | j.                  j0                  r)|j                  | j.                  j3                                | j0                  rK|j                  | j3                                | j4                  r |j                  | j5                  |              |j                  | j7                                | j8                  r |j                  | j9                  |              |r|j-                          y y # t        $ r}t        d| d|dd       Y d }~d }~ww xY w# |r|j-                          w w xY w# t>        t@        f$ r t(        jC                  d       Y pw xY w# |r|j-                          w w xY w# |j-                          	 | j.                  j0                  r)|j                  | j.                  j3                                | j0                  rK|j                  | j3                                | j4                  r |j                  | j5                  |              |j                  | j7                                | j8                  r |j                  | j9                  |              |r|j-                          w w # |r|j-                          w w xY wxY w)	NWindowsz3Could not add signal handlers for the stop signals z due to exception `z_`. If your event loop does not implement `add_signal_handler`, please pass `stop_signals=None`.rF   r   zCApplication received stop signal via `stop_running`. Shutting down.z0Application received stop signal. Shutting down.)"r   get_event_loopr   platformsystemsignalSIGINTSIGTERMSIGABRTr   r!   add_signal_handlerr   NotImplementedErrorr'   run_until_completer   ru   r   is_setr   r   closery   r   r   rw   r   rv   r   run_foreverKeyboardInterruptr   r   )rP   r  r   r   loopsigr   s          rR   __runzApplication.__run  s    %%'<'HOO,=,J"MM6>>6>>JL
	lL9'-2 JC++C1H1HIJ	!##DOO$56~~''t(<=))002bc ##%!<<''++DLL,=,=,?@<<++DIIK8~~//t0DE''8%%++D,>,>t,DEJJL / ##$56##DJJL1 ##%!<<''++DLL,=,=,?@<<++DIIK8~~//t0DE''8%%++D,>,>t,DEJJL M # 	El^ T!W %44 	 	L JJL ) ":. 	NMMLM	N( JJL  ##%!<<''++DLL,=,=,?@<<++DIIK8~~//t0DE''8%%++D,>,>t,DEJJL :JJL sw   $7M$ A;N' )C!N A N' /C!O $	N-NNN$'$OO* OO* O'*T	<C!S1T	1TT	r   	coroutiner   r   zasyncio.Task[RT]c                *    | j                  |||      S )a  Thin wrapper around :func:`asyncio.create_task` that handles exceptions raised by
        the :paramref:`coroutine` with :meth:`process_error`.

        Note:
            * If :paramref:`coroutine` raises an exception, it will be set on the task created by
              this method even though it's handled by :meth:`process_error`.
            * If the application is currently running, tasks created by this method will be
              awaited with :meth:`stop`.

        .. seealso:: :wiki:`Concurrency`

        Args:
            coroutine (:term:`awaitable`): The awaitable to run as task.

                .. versionchanged:: 20.2
                    Accepts :class:`asyncio.Future` and generator-based coroutine functions.
                .. deprecated:: 20.4
                    Since Python 3.12, generator-based coroutine functions are no longer accepted.
            update (:obj:`object`, optional): If set, will be passed to :meth:`process_error`
                as additional information for the error handlers. Moreover, the corresponding
                :attr:`chat_data` and :attr:`user_data` entries will be updated in the next run of
                :meth:`update_persistence` after the :paramref:`coroutine` is finished.

        Keyword Args:
            name (:obj:`str`, optional): The name of the task.

                .. versionadded:: 20.4

        Returns:
            :class:`asyncio.Task`: The created task.
        )r*  r   r   )_Application__create_task)rP   r*  r   r   s       rR   r   zApplication.create_taskW  s    L !!If4!PPrS   is_error_handlerc                     t        j                  | j                  |||      |      }| j                  r8| j                  j                  |       |j                  | j                         |S t        dd       |S )N)r*  r   r-  r   zpTasks created via `Application.create_task` while the application is not running won't be automatically awaited!rF   r   )	r   r   "_Application__create_task_callbackr   r   addadd_done_callback'_Application__create_task_done_callbackr'   )rP   r*  r   r-  r   tasks         rR   __create_taskzApplication.__create_task  s     ")!4!4''#FEU (  	"
 <<$$((.""4#C#CD  : rS   r3  c                     | j                   j                  |       t        j                  t        j
                  t        j                        5  |j                          d d d        y # 1 sw Y   y xY wrM   )r   discard
contextlibsuppressr   CancelledErrorInvalidStateError	exception)rP   r3  s     rR   __create_task_done_callbackz'Application.__create_task_done_callback  sS      ((.   !7!79R9RS 	NN	 	 	s   A((A1c                   K   	 t         j                  dk  rTt        |t              rDt	        t        dd             t        j                  |       d {   | j                  |       S | d {   | j                  |       S 7 27 # t        $ r[}t        |t              rt	        dd        |rt        j                  d|	        | j                  |||
       d {  7    d }~ww xY w# | j                  |       w xY ww)NrE   z20.4zZGenerator-based coroutines are deprecated in create_task and will not work in Python 3.12+r   zKApplicationHandlerStop is not supported with handlers running non-blocking.   r   dAn error was raised and an uncaught error was raised while handling the error with an error_handler.r   )r   r   r*  )sysversion_infor   r   r'   r9   r   r   _mark_for_persistence_updater   rI   r   r;  r  )rP   r*  r   r-  r;  s        rR   __create_task_callbackz"Application.__create_task_callback  s    &	=')jI.N)0 %00;;8 --V-<3 #?2 --V-<9 < # 	)%;<a (  "!!@& "   ((iS\(]]] -	0 --V-<sr   D	AB BB D	+B 0B	1B 4D	B 	B 	C/AC*#C&$C**C//C2 2DD	c                   K   	 | j                   j                          d {   }|t        u r| j                   j                          y t        j                  d|       | j                  j                  dkD  r<| j                  | j                  |      |d| j                  j                   d       n| j                  |       d {    7 7 w)NzProcessing update %sr?  r   z:process_concurrent_updater   r   )rx   getr   	task_doner   r   rj   r   r   $_Application__process_update_wrapperrn   r   rP   r   s     rR   __update_fetcherzApplication.__update_fetcher  s     ,,0022F%!!++-MM0&9%%<<q@  11&9!'}4NO !  33F;;;% 2" <s"   CCB&CC	CCc                   K   	 | j                          d {    | j                  j                         st        j	                  d| j                  j                                t        j                  t              5  | j                  j                          d d d        | j                  j                         sy y 7 # 1 sw Y   (xY w# | j                  j                         st        j	                  d| j                  j                                t        j                  t              5  | j                  j                          d d d        n# 1 sw Y   nxY w| j                  j                         sw w xY ww)NzDropping pending update: %s)
_Application__update_fetcherrx   emptyr   r   
get_nowaitr7  r8  r   rH  r   s    rR   r   zApplication._update_fetcher  s    	2'')))''--/;T=N=N=Y=Y=[\((4 2 %%//12 ''--/ *2 2 ''--/;T=N=N=Y=Y=[\((4 2 %%//12 2 2 ''--/si   E=C B=C A!E==B?"E=;E==C ?CE=A"E:-E	E:E!E:8E::E=c                    K   	 | j                   j                  || j                  |             d {    | j                  j                          y 7 # | j                  j                          w xY wwrM   )rj   process_updaterx   rH  rJ  s     rR   __process_update_wrapperz$Application.__process_update_wrapper  s^     	*((77@S@STZ@[\\\'') ]'')s+   A3.A AA A3A A00A3c           
      &  K   | j                          d}d}| j                  j                         D ]#  }	 |D ]  }|j                  |      }||du r|s?	 | j                  j
                  j                  ||       }|j                          d{    |j                  || ||      }|j                  rb|j                  t        u rt        | j                  t               re| j                  j"                  rO| j                  j"                  j                  s/| j%                  ||d| j                  j&                   d|        nd}| d{     n & |r| j/                  |       yy# t        $ r$}t        j                  d||       Y d}~  yd}~ww xY w7 7 S# t(        $ r t        j+                  d	       Y  lt        $ rB}| j-                  ||
       d{  7  rt        j+                  d       Y d}~ Y d}~d}~ww xY ww)a|  Processes a single update and marks the update to be updated by the persistence later.
        Exceptions raised by handler callbacks will be processed by :meth:`process_error`.

        .. seealso:: :wiki:`Concurrency`

        .. versionchanged:: 20.0
            Persistence is now updated in an interval set by
            :attr:`telegram.ext.BasePersistence.update_interval`.

        Args:
            update (:class:`telegram.Update` | :obj:`object` |                 :class:`telegram.error.TelegramError`): The update to process.

        Raises:
            :exc:`RuntimeError`: If the application was not initialized.
        NFzQError while building CallbackContext for update %s. Update will not be processed.r   r   z:process_update_non_blocking:rF  Tz7Stopping further handlers due to ApplicationHandlerStop)r   r   z'Error handler stopped further handlers.r>  )r   rs   r   check_updaterq   contextfrom_updater   r   r   refresh_datahandle_updateblockr    r   rn   r+   defaultsr   r   rI   r   r  rC  )	rP   r   rU  any_blockingrs   r   checkr   r*  s	            rR   rQ  zApplication.process_update  s    $ 	!,,. 3	H2' &G#008E} "#&*&8&8&@&@&L&LVUY&ZG &22444+2+@+@uV]+^I"==5&txx8 HH-- $ 1 1 7 7((%#)".txx{{m <$$+9!.	 )  (,'M&3	j  --V-<	 W  ) 	##,,%D !'), -  #	# 5& ( * WX  ++6+EEEMM"KL Fs   3H F#&E.=F#FB<F#F!F#H.	F7FF#HFF#!F##HHHH	"G%#H	=H	HHgroupc                    ddl m} t        |t              st	        dt        j
                         t        |t              st	        d      t        ||      r|j                  r|j                  rx| j                  st        d|j                   d      | j                  rG| j                  | j                  |      d| j                  j                   d	       t!        d
d       || j"                  vr@g | j"                  |<   t%        t'        | j"                  j)                                     | _        | j"                  |   j+                  |       y)a  Register a handler.

        TL;DR: Order and priority counts. 0 or 1 handlers per group will be used. End handling of
        update with :class:`telegram.ext.ApplicationHandlerStop`.

        A handler must be an instance of a subclass of :class:`telegram.ext.BaseHandler`. All
        handlers
        are organized in groups with a numeric value. The default group is 0. All groups will be
        evaluated for handling an update, but only 0 or 1 handler per group will be used. If
        :class:`telegram.ext.ApplicationHandlerStop` is raised from one of the handlers, no further
        handlers (regardless of the group) will be called.

        The priority/order of handlers is determined as follows:

        * Priority of the group (lower group number == higher priority)
        * The first handler in a group which can handle an update (see
          :attr:`telegram.ext.BaseHandler.check_update`) will be used. Other handlers from the
          group will not be used. The order in which handlers were added to the group defines the
          priority.

        Warning:
            Adding persistent :class:`telegram.ext.ConversationHandler` after the application has
            been initialized is discouraged. This is because the persisted conversation states need
            to be loaded into memory while the application is already processing updates, which
            might lead to race conditions and undesired behavior. In particular, current
            conversation states may be overridden by the loaded data.

        Args:
            handler (:class:`telegram.ext.BaseHandler`): A BaseHandler instance.
            group (:obj:`int`, optional): The group identifier. Default is ``0``.

        r   r   zhandler is not an instance of zgroup is not intzConversationHandler z8 can not be persistent if application has no persistencer   z,:add_handler:conversation_handler_after_initr   zA persistent `ConversationHandler` was passed to `add_handler`, after `Application.initialize` was called. This is discouraged.See the docs of `Application.add_handler` for details.r   r   N)r   r<   r   r,   r   rT   intr   r   rt   r   rg   r   r   rn   r   r'   rs   dictsorteditemsappend)rP   r   r]  r<   s       rR   add_handlerzApplication.add_handlerK  s0   F 	S';/<[=Q=Q<RSTT%%.//g238J8Jw||## *7<<. 9N N      //8'}4`a !  M  !	 %#%DMM%  (;(;(=!>?DMe##G,rS   rs   c                    t        |t              rt        |t              st        d      t        |t              rW|j	                         D ]C  \  }}t        |t
        t        f      st        d| d      |D ]  }| j                  ||        E yt        |t
        t        f      r-|D ]'  }| j                  |t        j                  |             ) yt        d      )a}  Registers multiple handlers at once. The order of the handlers in the passed
        sequence(s) matters. See :meth:`add_handler` for details.

        .. versionadded:: 20.0

        Args:
            handlers (List[:class:`telegram.ext.BaseHandler`] |                 Dict[int, List[:class:`telegram.ext.BaseHandler`]]):                 Specify a sequence of handlers *or* a dictionary where the keys are groups and
                values are handlers.
            group (:obj:`int`, optional): Specify which group the sequence of :paramref:`handlers`
                should be added to. Defaults to ``0``.

        Example::

            app.add_handlers(handlers={
                -1: [MessageHandler(...)],
                1: [CallbackQueryHandler(...), CommandHandler(...)]
            }

        Raises:
            :exc:`TypeError`: If the combination of arguments is invalid.
        zBThe `group` argument can only be used with a sequence of handlers.zHandlers for group z must be a list or tuplezThe `handlers` argument must be a sequence of handlers or a dictionary where the keys are groups and values are sequences of handlers.N)	r   r`  r!   r   rb  listr   rd  	get_value)rP   rs   r]  handler_groupgrp_handlersr   s         rR   add_handlerszApplication.add_handlers  s    > h%j.M`aah%/7~~/? =+|!,u>#&9-H`$abb+ =G$$Wm<=	= 4-0# I  ,*@*@*GHI ] rS   c                     || j                   |   v r<| j                   |   j                  |       | j                   |   s| j                   |= yyy)a  Remove a handler from the specified group.

        Args:
            handler (:class:`telegram.ext.BaseHandler`): A :class:`telegram.ext.BaseHandler`
                instance.
            group (:obj:`object`, optional): The group identifier. Default is ``0``.

        N)rs   remove)rP   r   r]  s      rR   remove_handlerzApplication.remove_handler  sN     dmmE**MM% ''0=='MM%( ( +rS   chat_idc                 r    | j                   j                  |d       | j                  j                  |       y)a  Drops the corresponding entry from the :attr:`chat_data`. Will also be deleted from
        the persistence on the next run of :meth:`update_persistence`, if applicable.

        Warning:
            When using :attr:`concurrent_updates` or the :attr:`job_queue`,
            :meth:`process_update` or :meth:`telegram.ext.Job.run` may re-create this entry due to
            the asynchronous nature of these features. Please make sure that your program can
            avoid or handle such situations.

        .. versionadded:: 20.0

        Args:
            chat_id (:obj:`int`): The chat id to delete. The entry will be deleted even if it is
                not empty.
        N)rc   poprd   r0  )rP   rn  s     rR   drop_chat_datazApplication.drop_chat_data  ,      	GT*3377@rS   user_idc                 r    | j                   j                  |d       | j                  j                  |       y)a  Drops the corresponding entry from the :attr:`user_data`. Will also be deleted from
        the persistence on the next run of :meth:`update_persistence`, if applicable.

        Warning:
            When using :attr:`concurrent_updates` or the :attr:`job_queue`,
            :meth:`process_update` or :meth:`telegram.ext.Job.run` may re-create this entry due to
            the asynchronous nature of these features. Please make sure that your program can
            avoid or handle such situations.

        .. versionadded:: 20.0

        Args:
            user_id (:obj:`int`): The user id to delete. The entry will be deleted even if it is
                not empty.
        N)rk   rp  rl   r0  )rP   rs  s     rR   drop_user_datazApplication.drop_user_data  rr  rS   messager;   old_chat_idnew_chat_idc                    |r|s|rt        d      t        |||f      st        d      |rl|j                  |j                  t        d      |j                  xs |j                  j
                  }|j                  xs |j                  j
                  }n+t        |t              rt        |t              st        d      | j                  |   | j                  |<   | j                  |       | j                  j                  |       y)a  Moves the contents of :attr:`chat_data` at key :paramref:`old_chat_id` to the key
        :paramref:`new_chat_id`. Also marks the entries to be updated accordingly in the next run
        of :meth:`update_persistence`.

        Warning:
            * Any data stored in :attr:`chat_data` at key :paramref:`new_chat_id` will be
              overridden
            * The key :paramref:`old_chat_id` of :attr:`chat_data` will be deleted
            * This does not update the :attr:`~telegram.ext.Job.chat_id` attribute of any scheduled
              :class:`telegram.ext.Job`.

            When using :attr:`concurrent_updates` or the :attr:`job_queue`,
            :meth:`process_update` or :meth:`telegram.ext.Job.run` may re-create the old entry due
            to the asynchronous nature of these features. Please make sure that your program can
            avoid or handle such situations.

        .. seealso:: :wiki:`Storing Bot, User and Chat Related Data            <Storing-bot%2C-user-and-chat-related-data>`

        Args:
            message (:class:`telegram.Message`, optional): A message with either
                :attr:`~telegram.Message.migrate_from_chat_id` or
                :attr:`~telegram.Message.migrate_to_chat_id`.
                Mutually exclusive with passing :paramref:`old_chat_id` and
                :paramref:`new_chat_id`.

                .. seealso::
                    :attr:`telegram.ext.filters.StatusUpdate.MIGRATE`

            old_chat_id (:obj:`int`, optional): The old chat ID.
                Mutually exclusive with passing :paramref:`message`
            new_chat_id (:obj:`int`, optional): The new chat ID.
                Mutually exclusive with passing :paramref:`message`

        Raises:
            ValueError: Raised if the input is invalid.
        z/Message and chat_id pair are mutually exclusivez&chat_id pair or message must be passedNzvInvalid message instance. The message must have either `Message.migrate_from_chat_id` or `Message.migrate_to_chat_id`.z,old_chat_id and new_chat_id must be integers)r   anymigrate_from_chat_idmigrate_to_chat_idchatr   r   r_  rc   rq  re   r0  )rP   rv  rw  rx  s       rR   migrate_chat_datazApplication.migrate_chat_data  s    V {NOOG[+67EFF++38R8R8Z V 
 "66I',,//K!44GK[#.:k33OKLL'+{'C$K(3377DrS   )r   jobr  r@   c                   t        |t              rv|j                  r/| j                  j	                  |j                  j
                         |j                  r/| j                  j	                  |j                  j
                         |rd|j                  r%| j                  j	                  |j                         |j                  r&| j                  j	                  |j                         y y y rM   )
r   r   effective_chatre   r0  r   effective_userrm   rn  rs  )rP   r   r  s      rR   rC  z(Application._mark_for_persistence_update9  s     ff%$$;;??@U@U@X@XY$$;;??@U@U@X@XY{{;;??L{{;;??L  rS   chat_idsuser_idsc                 *   |rGt        |t              r| j                  j                  |       n| j                  j	                  |       |rHt        |t              r| j
                  j                  |       y| j
                  j	                  |       yy)a  Mark entries of :attr:`chat_data` and :attr:`user_data` to be updated on the next
        run of :meth:`update_persistence`.

        Tip:
            Use this method sparingly. If you have to use this method, it likely means that you
            access and modify ``context.application.chat/user_data[some_id]`` within a callback.
            Note that for data which should be available globally in all handler callbacks
            independent of the chat/user, it is recommended to use :attr:`bot_data` instead.

        .. versionadded:: 20.3

        Args:
            chat_ids (:obj:`int` | Collection[:obj:`int`], optional): Chat IDs to mark.
            user_ids (:obj:`int` | Collection[:obj:`int`], optional): User IDs to mark.

        N)r   r_  re   r0  r   rm   )rP   r  r  s      rR    mark_data_for_update_persistencez,Application.mark_data_for_update_persistenceH  ss    & (C(;;??I;;BB8L(C(;;??I;;BB8L	 rS   c                   K   | j                   j                         s[| j                  sy 	 t        j                  | j                   j                         | j                  j                         d {    y y y 7 # t        j                  $ r Y nw xY w| j                          d {  7   | j                   j                         sRw)N)r   )	r   r#  rt   r   wait_forr   update_intervalTimeoutErrorr   r   s    rR   r   z Application._persistence_updaterf  s     1188:##&&3388: ,,<<    ; ''  ))+++% 1188:sG   (C	AA; 1A92A; 6C	9A; ;BC	BC	'B*(C	c                    K   | j                   4 d{    | j                          d{    ddd      d{    y7 -7 7 	# 1 d{  7  sw Y   yxY ww)a  Updates :attr:`user_data`, :attr:`chat_data`, :attr:`bot_data` in :attr:`persistence`
        along with :attr:`~telegram.ext.ExtBot.callback_data_cache` and the conversation states of
        any persistent :class:`~telegram.ext.ConversationHandler` registered for this application.

        For :attr:`user_data` and :attr:`chat_data`, only those entries are updated which either
        were used or have been manually marked via :meth:`mark_data_for_update_persistence` since
        the last run of this method.

        Tip:
            This method will be called in regular intervals by the application. There is usually
            no need to call it manually.

        Note:
            Any data is deep copied with :func:`copy.deepcopy` before handing it over to the
            persistence in order to avoid race conditions, so all persisted data must be copyable.

        .. seealso:: :attr:`telegram.ext.BasePersistence.update_interval`,
            :meth:`mark_data_for_update_persistence`
        N)r    _Application__update_persistencer   s    rR   r   zApplication.update_persistence|  sV     ( 11 	. 	.++---	. 	. 	.-	. 	. 	. 	.sQ   AAAAAAAAAAAAAAAc           
      v   K    j                   sy t        j                  d       t               } j                   j                  j
                  rg j                  j                  Q|j                   j                   j                  t         j                  j                  j                                      j                   j                  j                  r=|j                   j                   j                  t         j                                      j                   j                  j                  r j                  }t                _         j                   }t                _        ||z  }|D ]C  }|j                   j                   j#                  |t         j                  |                      E |D ],  }|j                   j                   j%                  |             .  j                   j                  j&                  r j(                  }t                _         j*                  }t                _        ||z  }|D ]C  }|j                   j                   j-                  |t         j&                  |                      E |D ],  }|j                   j                   j/                  |             . ddlm} t4        j6                  j9                  d  j:                  j=                         D              D ]  \  }\  }}	t?        |	|      r|	jA                         sb jB                  rt        j                  d       nt        jE                  d       |	jF                  }
 j:                  |   jI                  |       n|	jK                         }
n|	}
|
tL        jN                  u rd n|
}|j                   j                   jQ                  |||              tS        jT                  |dd	i d {   }t        j                  d
       tS        jT                   fd|D          d {    y 7 =7 w)Nz.Starting next run of updating the persistence.r   )PendingStatec              3   |   K   | ]4  \  }}t        t        j                  |      |j                                6 y wrM   )zipr   repeatpop_accessed_write_items).0r   states_dicts      rR   	<genexpr>z3Application.__update_persistence.<locals>.<genexpr>  s9      D
!k 	  &(L(L(NOD
s   :<zA ConversationHandlers state was not yet resolved. Updating the persistence with the current state. Will check again on next run of Application.update_persistence.zcA ConversationHandlers state was not yet resolved. Updating the persistence with the current state.)r   r  	new_stater   TzFinished updating persistence.c              3   d   K   | ]'  }t        |t              rj                  |d        ) y wr   )r   r   r  )r  r   rP   s     rR   r  z3Application.__update_persistence.<locals>.<genexpr>  s3      fi0 """=s   -0)+rt   r   r   r   r   r   rn   r   r0  update_callback_datar   persistence_dataro   update_bot_datarp   re   rd   update_chat_datarq  rz   rm   rl   update_user_dataru  r   r  r   r   r   rf   rb  r   r   r   warning	old_statemark_as_accessedr   r/   DELETEDupdate_conversationr   r   )rP   
coroutines
update_ids
delete_idsrn  rs  r  r   r  r  r   effective_new_stateresultss   `            rR   __update_persistencez Application.__update_persistence  s    FG%(U
 &&44HH((4NN  5544EE &&//NN4++;;HT]]<STU&&00DDJ:=%D7DDJ:=%D7 *$J% $$55gxW^H_?`a & It//>>wGHI &&00DDJ:=%D7DDJ:=%D7 *$J% $$55gxW^H_?`a & It//>>wGHI
 	L&/oo&C&C D
%)%M%M%S%S%UD
 '
 #	"D"3	 )\2 !~~'||>  B '00F<<TBSSTWX&..0F"*0L4H4H*H$fNN  4432E 5 ?#	J  
KdKK67 nn%
 	
 	
	 L	
s$   O4P97P587P9/P70P97P9callbackrY  c                 j    || j                   v rt        j                  d       y|| j                   |<   y)ak  Registers an error handler in the Application. This handler will receive every error
        which happens in your bot. See the docs of :meth:`process_error` for more details on how
        errors are handled.

        Note:
            Attempts to add the same callback multiple times will be ignored.

        Examples:
            :any:`Errorhandler Bot <examples.errorhandlerbot>`

        .. seealso:: :wiki:`Exceptions, Warnings and Logging <Exceptions%2C-Warnings-and-Logging>`

        Args:
            callback (:term:`coroutine function`): The callback function for this error handler.
                Will be called when an error is raised. Callback signature::

                    async def callback(update: Optional[object], context: CallbackContext)

                The error that happened will be present in
                :attr:`telegram.ext.CallbackContext.error`.
            block (:obj:`bool`, optional): Determines whether the return value of the callback
                should be awaited before processing the next error handler in
                :meth:`process_error`. Defaults to :obj:`True`.
        zAThe callback is already registered as an error handler. Ignoring.N)rr   r   r  )rP   r  rY  s      rR   add_error_handlerzApplication.add_error_handler   s2    : t***OO_`(-H%rS   c                 <    | j                   j                  |d       y)zRemoves an error handler.

        Args:
            callback (:term:`coroutine function`): The error handler to remove.

        N)rr   rp  )rP   r  s     rR   remove_error_handlerz Application.remove_error_handler#  s     	$/rS   r   zJob[CCT]c           	        K   | j                   r| j                   j                         D ]  \  }}	 | j                  j                  j	                  ||| ||      }|rX|t        u rt        | j                  t              rk| j                  j                  rU| j                  j                  j                  s5| j                   |||      |dd| j                  j                   d	       	  |||       d{     yt        j#                  d|       y# t
        $ r#}t        j                  d||       Y d}~ yd}~ww xY w7 N# t         $ r Y  yt
        $ r"}t        j#                  d
|       Y d}~Od}~ww xY ww)a  Processes an error by passing it to all error handlers registered with
        :meth:`add_error_handler`. If one of the error handlers raises
        :class:`telegram.ext.ApplicationHandlerStop`, the error will not be handled by other error
        handlers. Raising :class:`telegram.ext.ApplicationHandlerStop` also stops processing of
        the update when this method is called by :meth:`process_update`, i.e. no further handlers
        (even in other groups) will handle the update. All other exceptions raised by an error
        handler will just be logged.

        .. versionchanged:: 20.0

            * ``dispatch_error`` was renamed to :meth:`process_error`.
            * Exceptions raised by error handlers are now properly logged.
            * :class:`telegram.ext.ApplicationHandlerStop` is no longer reraised but converted into
              the return value.

        Args:
            update (:obj:`object` | :class:`telegram.Update`): The update that caused the error.
            error (:obj:`Exception`): The error that was raised.
            job (:class:`telegram.ext.Job`, optional): The job that caused the error.

                .. versionadded:: 20.0
            coroutine (:term:`coroutine function`, optional): The coroutine that caused the error.

        Returns:
            :obj:`bool`: :obj:`True`, if one of the error handlers raised
            :class:`telegram.ext.ApplicationHandlerStop`. :obj:`False`, otherwise.
        )r   r   applicationr  r*  ziError while building CallbackContext for exception %s. Exception will not be processed by error handlers.r   NFTr   z:process_error:non_blocking)r   r-  r   r@  z4No error handlers are registered, logging exception.)rr   rb  rq   rU  
from_errorr   r   r   r    r   rn   r+   rZ  rY  r,  r   rI   r;  )	rP   r   r   r  r*  r  rY  rU  r   s	            rR   r  zApplication.process_error,  s    D  $$**,- !"0088CC%#$("+ D G$ \)"488V4)) HH--33&& 1%)-+DHHKK=8ST	 ' 	&vw777K-\ P[`aK ! 	!$$Q !$ %  !	!2 81 $#$ ))H%( *  sw   -F *DBF *E6E7E;F 	ED=7F =EF E	E=F E=E82F 8E==F )rK   r?   )rK   r>   )rK   N)r   r<   rK   N)TrM   )NFN)NF)NNN)NN)crT   rU   rV   rW   rA  rB  rX   r1   r   r-   r4   r)   r6   r3   r0   r*   r2   r   r   r	   rO   rB   r   r   r   r   r   strr   propertyboolr   r_  r   r}   r~   staticmethodr   r   r   r   r   r   r   r   r   r   r   r   floatr&   r   r   r  r   r   r%   r   r   r  r  	_CoroTyper5   rY   r   r,  r   Taskr2  r/  rM  r   rI  rQ  rA   r,   rd  
_DEFAULT_0r   r   r!   rj  rm  rq  ru  r~  rC  r$   r  r   r   r  r    r8   r  r  r   _ErrorCoroTyper  r|   rS   rR   rC   rC      sn   st w&I#	J M RO54O5 O5 .	O5
 '"O5 O5 0O5 ob"bj9:O5 $CRO4O5 <=ycSW?XXY
O5  <=ycSW?XXY
O5  <=ycSW?XXY
!O5bx H "	4./	 -(	 '		
 
		B# 	B    
=C 
= 
= 8O4   & &    $ $)+V

%"N:3j@4D#N  #!#(4)5+7(4/3/30<L
L
 L
 	L

 uoL
  L
 "%L
 uoL
 "$s),L
 'tnL
 L
 x}-L
 
L
` )&+/*.!"%)/3/3$(!0<&*59!X
sX
 SkX
 	X

 uS$Y'(X
 eCI&'X
 X
 c]X
 "$s),X
 'tnX
 SMX
 X
 X
 x}-X
 smX
  uS$012!X
" 
#X
|  	9!$9! x}-9! 	9!
 
9!| $(&Q
 #&QR=&Q  &Q
 sm&Q 
&QV $(!&"R=   	
 sm 
<   $(!&	,=R=,=  ,= 	,=
 
,=\<,	2*V * *P=6 P=d P=d MZ ?-;sC}#= ?-c ?-^b ?-N 0:2${3S=12E+c3PSm:T4UUVeDS#s]!;<eKPSUXZ]P]D^>__``ac
2 S,s++,2 
2j AN)"3S=1):=)	) Ac Ad A&Ac Ad A* (,%)%)	@E)$@E c]@E c]	@E
 
@EH -1M!&)M7?M	M  SWM S*M=Ec#h=OM	M<,,..k
` +!.!&#t"34!. d|!. 
	!.F0_VS$=N-O 0TX 0 %)26T T T j!	T
 N2./T 
TrS   )orW   r   r7  r   r   r  r  rA  collectionsr   copyr   pathlibr   typesr   r   typingr   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   telegram._updater   telegram._utils.defaultvaluer   r   r   r    r!   telegram._utils.loggingr"   telegram._utils.reprr#   telegram._utils.typesr$   r%   r&   telegram._utils.warningsr'   telegram.errorr(   telegram.ext._basepersistencer)   telegram.ext._contexttypesr*   telegram.ext._extbotr+   "telegram.ext._handlers.basehandlerr,   telegram.ext._updaterr-   telegram.ext._utils.stackr.    telegram.ext._utils.trackingdictr/   telegram.ext._utils.typesr0   r1   r2   r3   r4   r5   r6   r7   r8   telegram.warningsr9   r:   telegramr;   r   r<   r=    telegram.ext._applicationbuilderr>   !telegram.ext._baseupdateprocessorr?   telegram.ext._jobqueuer@   rA   r_  __annotations__rB   rY   r   r  rB  r  r  rT   r   r   rI   rC   r|   rS   rR   <module>r     sM  & 2       
 #   1     . $  / ? 7 7 ) ( 9 3 ' : ) 3 9 c c c 3 :GE*s :]3x!_
 w"Ii 8$ BCYr]RSI)B-(
X
-Y ->y'"c2r2r124G4V yrS   