
    YiH                       % S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKJ	r	  SSK
JrJrJrJrJr  SSKJr  SSKJr  SSKJrJr  SSKJrJrJrJrJrJrJrJr  SS	K J!r!  SS
K"J#r#J$r$J%r%J&r&J'r'  SSK(J)r)  SSK*J+r+  SSK,J-r-J.r.J/r/  SSK0J1r1  SSK2J3r3  SSK4J5r5  SSK6J7r7  SSK8J9r9  SSK:J;r;  SSK<J=r=  SSK>J?r?  SSK@JArA  SSKBJCrCJDrDJErEJFrFJGrGJHrHJIrIJJrJJKrK  SSKLJMrM  \(       a&  SSKNJNrN  SSKOJPrP  SSKQJRrRJSrS  SSKTJUrU  SSKVJWrW  SSKXJYrY  SrZ\[\\S'   \" S S!S"9r]\^" 5       r_\'" S5      r`\R                  S#:  a  \\H   rbO\\S$S\H4   \\H   4   rb\\b\H      rc\)" \d5      re " S% S&\f5      rg " S' S!\\D\E\I\F\C\G4   \R                  S!   5      rig)(z+This module contains the Application class.    N)defaultdict)	Awaitable	Coroutine	GeneratorMappingSequence)deepcopy)Path)MappingProxyTypeTracebackType)TYPE_CHECKINGAnyCallableGenericNoReturnOptional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                   F   ^  \ rS rSrSrSrSS\\   SS4U 4S jjjrSr	U =r
$ )	ApplicationHandlerStopU   a  
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.
)stateNrD   returnc                 .   > [         TU ]  5         Xl        g N)super__init__rD   )selfrD   	__class__s     D/app/.venv/lib/python3.13/site-packages/telegram/ext/_application.pyrI   ApplicationHandlerStop.__init__o   s    ',
    rG   )__name__
__module____qualname____firstlineno____doc__	__slots__r   objectrI   __static_attributes____classcell__)rK   s   @rL   rB   rB   U   s,    . I-hv. -$ - -rN   rB   c            #          \ rS rSrSr\R                  S:  a  SOSrSSS\S	S
S\	\
   S\SSS\	\\\\4      S\\\\\4   S\	\S/\\\S4   4      S\	\S/\\\S4   4      S\	\S/\\\S4   4      4S jrS\S\4S jrS\	\\      S\	\   S\	\   SS4S jrS\4S jr\S\4S j5       r \S\!4S j5       r"\S\	S   4S  j5       r#\S}S! j5       r$\%S\&4S" j5       r'\%S~S# j5       r(SS$ jr)SS% jr*SS' jr+SS( jr,SS) jr-SS* jr.SS+ jr/SS, jr0S-S.S/\1\1\1\1SSS0\14S1\2S2\!S3\!S4\3\2   S5\3\2   S6\3\2   S7\3\2   S8\	\4\      S9\	\   S:\S;\3\4\!      SS4S< jjr5\6\7S=SSS>SSSSS?S0\1SS4S@\8\   SA\8\!   SB\SC\	\9\\:4      SD\	\9\\:4      S3\!SE\	\   S8\	\4\      S9\	\   SF\	\   SG\!S:\S;\3\4\!      SH\	\   SI\	\9\\:SJ4      SS4 SK jjr; SSL\S;\3\4\!      S:\SS4SM jjr< SSSN.SO\=\>   SP\	\?   SQ\	\   SSR4SS jjjr@   SSO\=\>   SP\	\?   ST\SQ\	\   SSR4
SU jjrASV\BR                  SS4SW jrD  SSO\=\>   SP\	\?   ST\S\>4SX jjrESSY jrFSSZ jrGSP\?SS4S[ jrHSP\?SS4S\ jrI\J4S&\K\\\4   S]\!SS4S^ jjrL\M4S_\9\4\K\\\4      \N\!\4\K\\\4      4   4   S]\9\!\O\!   4   SS4S` jjrP\J4S&\K\\\4   S]\!SS4Sa jjrQSb\!SS4Sc jrRSd\!SS4Se jrS   SSf\	Sg   Sh\	\!   Si\	\!   SS4Sj jjrTSSSk.SP\	\?   Sl\	Sm   SS4Sn jjrU SSo\	\V\!      Sp\	\V\!      SS4Sq jjrWSSr jrXSSs jrYSSt jrZ\[4Su\\\?\S4   Sv\8\   SS4Sw jjr]Su\\\?\S4   SS4Sx jr^  SSP\	\?   Sy\_Sl\	Sz   SO\	\`\>      S\4
S{ jjraS|rbg)r<   t   a1  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

)r?      )__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__ rJ   z$Application[BT, CCT, UD, CD, BD, JQ]rl   rv   zasyncio.Queue[object]rw   	job_queueupdate_processorr8   rr   ro   rs   Nrt   ru   c       
         T   [        [        R                  " 5       [        [        5      R
                  R                  5       S-  5      (       d
  [        SSS9  Xl        X l	        Xpl
        X0l        0 U l        0 U l        UU l        U	U l        U
U l        XPl        U R                  R%                  5       U l        ['        U R                  R(                  5      U l        ['        U R                  R,                  5      U l        [1        U R*                  5      U l        [1        U R.                  5      U l        S U l        U(       a   [5        U[6        5      (       d  [9        S5      eX`l        [;        5       U l        [;        5       U l        [;        5       U l         [;        5       U l!        0 U l"        SU l#        SU l$        X@l%        S U l&        S U l'        [P        RR                  " 5       U l*        [P        RV                  " 5       U l,        [;        5       U l-        [P        RR                  " 5       U l.        g )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    rl   rv   ro   rw   rq   rp   rs   rt   ru   rh   rm   r   rx   ri   rn   ra   r   rr   
isinstancer"   	TypeErrorsetrc   rk   rb   rj   rd   re   rg   rf   !_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)rJ   rl   rv   rw   r{   r|   rr   ro   rs   rt   ru   s              rL   rI   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GWXX& AD3@C3@C3@C3  	0
 "'=A"AE&*1--/')0&69e %,]]_"rN   rE   c                    #     U R                  5       I Sh  vN   U $  N! [         a    U R                  5       I Sh  vN    e f = f7f)z|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rJ   s    rL   
__aenter__Application.__aenter__g  sF     	//### 	 $ 	--/!!	s/   A    A  AA AAexc_typeexc_valexc_tbc                 @   #    U R                  5       I Sh  vN   g N7f)z>|async_context_manager| :meth:`shuts down <shutdown>` the App.N)r   )rJ   r   r   r   s       rL   	__aexit__Application.__aexit__x  s      mmos   c                 (    [        X R                  S9$ )zGive 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`
)rl   )r   rl   r   s    rL   __repr__Application.__repr__  s     .dAArN   c                     U R                   $ )ze:obj:`bool`: Indicates if this application is running.

.. seealso::
    :meth:`start`, :meth:`stop`
)rg   r   s    rL   runningApplication.running  s     }}rN   c                 .    U R                   R                  $ )aj  :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`
)rh   max_concurrent_updatesr   s    rL   concurrent_updatesApplication.concurrent_updates  s     %%<<<rN   zJobQueue[CCT]c                 H    U R                   c
  [        SSS9  U R                   $ )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   )rf   r    r   s    rL   r{   Application.job_queue  s+     ??"B
 rN   c                     U R                   $ )z:class:`telegram.ext.BaseUpdateProcessor`: The update processor used by this
application.

.. seealso:: :wiki:`Concurrency`

.. versionadded:: 20.4
)rh   r   s    rL   r|   Application.update_processor  s     %%%rN   c                      [         erG   )
SystemExitrz   rN   rL   _raise_system_exitApplication._raise_system_exit  s    rN   c                      SSK Jn   U " 5       $ )zdConvenience method. Returns a new :class:`telegram.ext.ApplicationBuilder`.

.. versionadded:: 20.0
r   ApplicationBuilder)telegram.extr   r   s    rL   builderApplication.builder  s     	4!##rN   c                 <    U R                   (       d  [        S5      eg )NzBThis Application was not initialized via `Application.initialize`!)re   RuntimeErrorr   s    rL   _check_initializedApplication._check_initialized  s       T  !rN   c                 .  #    U R                   (       a  [        R                  S5        gU R                  R	                  5       I Sh  vN   U R
                  R	                  5       I Sh  vN   U R                  (       a"  U R                  R	                  5       I Sh  vN   U R                  (       d  SU l         gU R                  5       I Sh  vN   SSK	J
n  [        R                  R                  U R                  R                  5       5       HT  n[!        X!5      (       d  M  UR"                  (       d  M(  UR$                  (       d  M;  U R'                  U5      I Sh  vN   MV     SU l         U R(                  R+                  5         g GNB GN# N N N47f)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   r5   )re   _LOGGERdebugrl   r   rh   rw   rr   _initialize_persistence*telegram.ext._handlers.conversationhandlerr5   	itertoolschainfrom_iterablerq   valuesr   
persistentname_add_ch_to_persistencer   clear)rJ   r5   handlers      rL   r   Application.initialize  s)     MMDEhh!!###$$//111<<,,))+++ $D**,,, 	S !44T]]5I5I5KLG'77G<N<N<NSZS_S_S_11'::: M !""((*- 	$1 , 	- ;sm   AFF	!F)F*2FF0FFAF$F7F
FF+FFFFFr   c                 t   #    U R                   R                  UR                  U 5      I S h  vN 5        g  N	7frG   )rd   updater   )rJ   r   s     rL   r   "Application._add_ch_to_persistence  s-     007711$77	
7s   *86
8c                   #    U R                   (       a  [        S5      eU R                  (       d  [        R	                  S5        gU R
                  R                  5       I Sh  vN   U R                  R                  5       I Sh  vN   U R                  (       a"  U R                  R                  5       I Sh  vN   U R                  (       ad  [        R	                  S5        U R                  5       I Sh  vN   U R                  R                  5       I Sh  vN   [        R	                  S5        SU l        g N N N NI N)7f)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   re   r   r   rl   r   rh   rw   rr   update_persistenceflushr   s    rL   r   Application.shutdown  s     $ <<CDD  MMMNhh!!!$$--///<<,,'')))MMKL))+++""((***MM;<! 	"/ * ,*sZ   A!E#D:$!ED<2E8D>9=E6E 7!EE"E<E>E EEc                   #    U R                   (       d  gU R                   R                  R                  (       a;  U R                  R	                  U R                   R                  5       I Sh  vN 5        U R                   R                  R                  (       a;  U R                  R	                  U R                   R                  5       I Sh  vN 5        U R                   R                  R                  (       a  U R                   R                  5       I Sh  vN U l	        [        U R                  U R                  R                  5      (       d,  [        SU R                  R                  R                   35      eU R                   R                  R                  (       a  U R                   R"                  b{  U R                   R%                  5       I Sh  vN nUbU  [        U[&        5      (       a  [)        U5      S:w  a  [        S5      eU R                   R"                  R+                  U5        gggg GN GNl GN$ Nh7f)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)rr   
store_datarx   ri   r   get_user_datarn   ra   get_chat_datarm   get_bot_datar   ro   
ValueErrorrO   callback_datarl   callback_data_cacheget_callback_datatuplelenload_persistence_data)rJ   persistent_datas     rL   r   #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I /0B0B0K0K0T0T/UV  &&44HH((4$($4$4$F$F$HHO*!/599S=QUV=V$%PQQ,,BB# + 5 5 $J#IA IsL   A*I ,H5-AI H8A
I H;B=I H>A I 8I ;I >I c                   #    U R                   (       a  [        S5      eU R                  5         SU l        U R                  R                  5          U R                  (       aU  [        R                  " U R                  5       SU R                  R                   S3S9U l        [        R                  S5        U R                  (       a7  U R                  R!                  5       I Sh  vN   [        R                  S5        [        R                  " U R#                  5       SU R                  R                   S	3S9U l        [        R'                  S
5        g No! [(         a	    SU l        e f = f7f)aY  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   rg   r   r   rr   r   create_task_persistence_updaterrl   idr   r   r   rf   start_update_fetcherr   infor   r   s    rL   r   Application.startH  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&A.E E-E E**E-c                 *  #    U R                   (       d  [        S5      eSU l        U R                  R	                  5         [
        R                  S5        U R                  (       a  U R                  R                  5       (       a   U R                  R                  5         OrU R                  R                  [        5      I Sh  vN   [
        R                  S5        U R                  R!                  5       I Sh  vN   U R                  I Sh  vN   [
        R                  S	5        U R"                  (       aK  [
        R                  S
5        U R"                  R%                  SS9I Sh  vN   [
        R                  S5        [
        R                  S5        [&        R(                  " U R*                  SS06I Sh  vN   U R,                  (       an  U R.                  (       a]  [
        R                  S5        U R0                  R3                  5         U R.                  I Sh  vN   U R0                  R	                  5         [
        R                  S5        g! [         a   n[
        R                  SUSS9   SnAGNhSnAff = f GN GN GN{ GN" N No7f)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   rg   r   r   r   r   r   doneresultBaseExceptioncriticalrv   put_STOP_SIGNALr   joinrf   stopr   gatherr   rr   r   r   r   )rJ   excs     rL   r   Application.stop}  s    . ||ABB""((*IJ %%))..0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   BJI  #JJ6J:J;JJ	AJ*J+AJ<J=A$J!J"4J
J  I;5J;J  JJ	JJJJc                     U R                   (       a$  [        R                  " 5       R                  5         gU R                  R                  5         U R                  (       d  [        R                  S5        gg)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   re   r   r   r   s    rL   stop_runningApplication.stop_running  sS    2 << $$&++-&&**,$$! %rN   g        
   Tpoll_intervaltimeoutbootstrap_retriesread_timeoutwrite_timeoutconnect_timeoutpool_timeoutallowed_updatesdrop_pending_updates
close_loopstop_signalsc                   ^  T R                   (       d  [        S5      eXEXg4[        4S-  :w  a  [        [	        SS5      SS9  S[
        SS	4U 4S
 jjnT R                  T R                   R                  UUUUUUUUU	US9
U
US9$ )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 (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
    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   rE   Nc                 D   > TR                  TR                  U S S95        g N)errorr   )r   process_error)r   rJ   s    rL   error_callback/Application.run_polling.<locals>.error_callbacka  s!    T//c$/GHrN   )
r  r  r  r  r  r  r  r  r	  r  updater_coroutiner
  r  )rw   r   r   r    r2   r!   _Application__runstart_polling)rJ   r  r  r  r  r  r  r  r  r	  r
  r  r  s   `            rL   run_pollingApplication.run_polling  s    \ ||^  G\O^_L_`%U
 	I 	I$ 	I zz"ll88+"3)+ /) /%9- 9  "%  
 	
rN    r   (   listenporturl_pathcertkeywebhook_url
ip_addressmax_connectionssecret_tokenunixr3   c                     U R                   (       d  [        S5      eU R                  U R                   R                  UUUUUUU	UUU
UUUS9UUS9$ )a
  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 (Sequence[:obj:`str`], optional): Passed to
        :meth:`telegram.Bot.set_webhook`.

        .. 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`.
    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  )rw   r   r  start_webhook)rJ   r  r  r  r  r   r  r!  r  r	  r"  r#  r
  r  r$  r%  s                   rL   run_webhookApplication.run_webhooku  sz    H ||^  zz"ll88!"3%9' /% /) 9  "%#  
 	
rN   r  c                 
   [         R                  " 5       nU[        L aH  [        R                  " 5       S:w  a/  [
        R                  [
        R                  [
        R                  4n [        U[        5      (       d-  U=(       d    /  H  nUR                  XPR                  5        M       UR                  U R!                  5       5        U R"                  (       a   UR                  U R#                  U 5      5        U R$                  R'                  5       (       Ga5  [(        R+                  S5         UR-                  5          U R.                  R0                  (       a)  UR                  U R.                  R3                  5       5        U R0                  (       aP  UR                  U R3                  5       5        U R4                  (       a   UR                  U R5                  U 5      5        UR                  U R7                  5       5        U R8                  (       a   UR                  U R9                  U 5      5        U(       a  UR-                  5         g g UR                  U5        UR                  U R;                  5       5        UR=                  5         UR-                  5          U R.                  R0                  (       a)  UR                  U R.                  R3                  5       5        U R0                  (       aP  UR                  U R3                  5       5        U R4                  (       a   UR                  U R5                  U 5      5        UR                  U R7                  5       5        U R8                  (       a   UR                  U R9                  U 5      5        U(       a  UR-                  5         g g ! [         a  n[        SU SU< S3SS9   S nAGN'S nAff = f! U(       a  UR-                  5         f f = f! [>        [@        4 a    [(        RC                  S5         GNf = f! U(       a  UR-                  5         f f = f! UR-                  5          U R.                  R0                  (       a)  UR                  U R.                  R3                  5       5        U R0                  (       aP  UR                  U R3                  5       5        U R4                  (       a   UR                  U R5                  U 5      5        UR                  U R7                  5       5        U R8                  (       a   UR                  U R9                  U 5      5        U(       a  UR-                  5         f f ! U(       a  UR-                  5         f f = f= f)	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`.r?   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   rs   r   is_setr   r   closerw   r   r   ru   r   rt   r   run_foreverKeyboardInterruptr   r   )rJ   r  r  r
  loopsigr   s          rL   __runApplication.__run  s    %%'<'HOO,=,J"MM6>>6>>JL
	lL99'-2-C++C1H1HI .	!##DOO$56~~''t(<=))002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 sx   (AN/ +BO6 C5O A O6 !C5P" /
O9OOO36%PP? PP? "P<?U<C5UU<U99U<r   	coroutiner   r   zasyncio.Task[RT]c                "    U R                  XUS9$ )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)rJ   r>  r   r   s       rL   r   Application.create_taskM  s    L !!I4!PPrN   is_error_handlerc                     [         R                  " U R                  XUS9US9nU R                  (       a8  U R                  R                  U5        UR                  U R                  5        U$ [        SSS9  U$ )N)r>  r   rB  r   zpTasks created via `Application.create_task` while the application is not running won't be automatically awaited!r?   r   )	r   r   "_Application__create_task_callbackr   r   addadd_done_callback'_Application__create_task_done_callbackr    )rJ   r>  r   rB  r   tasks         rL   __create_taskApplication.__create_tasku  s     ")!4!4''#EU (  	"
 <<$$((.""4#C#CD  : rN   rH  c                     U R                   R                  U5        [        R                  " [        R
                  [        R                  5         UR                  5         S S S 5        g ! , (       d  f       g = frG   )r   discard
contextlibsuppressr   CancelledErrorInvalidStateError	exception)rJ   rH  s     rL   __create_task_done_callback'Application.__create_task_done_callback  sK      ((.   !7!79R9RSNN TSSs   A))
A7c                   #     [         R                  S:  aW  [        U[        5      (       aB  [	        [        SS5      5        [        R                  " U5      I S h  vN U R                  US9  $ UI S h  vN U R                  US9  $  N, N! [         a[  n[        U[        5      (       a  [	        SSS9  e U(       a  [        R                  SUS	9  e U R                  X$US
9I S h  vN    e S nAff = f! U R                  US9  f = f7f)Nr>   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    r2   r   r   _mark_for_persistence_updater   rB   r   rQ  r  )rJ   r>  r   rB  rQ  s        rL   __create_task_callback"Application.__create_task_callback  s    &	=')jI.N.N)0 %00;;8 --V-<3 #?2 --V-<9 < # 	)%;<<a (  "!!@& "   ((S\(]]] -	0 --V-<sr   DAB BB D/B 4B
5B 8DB 
B 
C1AC,%C(&C,,C11C4 4DDc                   #     U R                   R                  5       I S h  vN nU[        L a  U R                   R                  5         g [        R                  SU5        U R                  R                  S:  a9  U R                  U R                  U5      USU R                  R                   S3S9  OU R                  U5      I S h  vN   M   N N7f)NzProcessing update %srV  r   z:process_concurrent_updater   r   )rv   getr   	task_doner   r   rh   r   r   $_Application__process_update_wrapperrl   r   rJ   r   s     rL   __update_fetcher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                 B  #     U R                  5       I S h  vN   U R                  R                  5       (       d  [        R	                  SU R                  R                  5       5        [        R                  " [        5         U R                  R                  5         S S S 5        U R                  R                  5       (       d  M  g g  N! , (       d  f       N3= f! U R                  R                  5       (       d  [        R	                  SU R                  R                  5       5        [        R                  " [        5         U R                  R                  5         S S S 5        O! , (       d  f       O= fU R                  R                  5       (       d  M  f f = f7f)NzDropping pending update: %s)
_Application__update_fetcherrv   emptyr   r   
get_nowaitrM  rN  r   r`  r   s    rL   r   Application._update_fetcher  s    	2'')))''--//;T=N=N=Y=Y=[\((4 %%//1 5 ''--// * 54 ''--//;T=N=N=Y=Y=[\((4 %%//1 544 ''--//si   FC C	C A'FC'FF	C 
CFA(FE(	F(
E62&FFFc                    #     U R                   R                  XR                  U5      5      I S h  vN   U R                  R                  5         g  N! U R                  R                  5         f = f7frG   )rh   process_updaterv   r`  rb  s     rL   __process_update_wrapper$Application.__process_update_wrapper  s[     	*((77@S@STZ@[\\\'') ]'')s+   A2-A AA A2A A//A2c           
      j  #    U R                  5         SnSnU R                  R                  5        GH>  n U GH2  nUR                  U5      nUb  USL a  M  U(       d>   U R                  R
                  R                  X5      nUR                  5       I Sh  vN   UR                  XXb5      nUR                  (       ar  UR                  [        L a  [        U R                  [         5      (       al  U R                  R"                  (       aQ  U R                  R"                  R                  (       d,  U R%                  UUSU R                  R&                   SU 3S9  OSnUI Sh  vN     GM<     GMA     U(       a  U R/                  US9  gg! [         a!  n[        R                  SUUS9   SnA    gSnAff = f GN# NX! [(         a    [        R+                  S	5           Mn  [         aE  nU R-                  XS
9I Sh  vN  (       a  [        R+                  S5         SnA  M   SnAGM  SnAff = f7f)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:r^  Tz7Stopping further handlers due to ApplicationHandlerStop)r   r  z'Error handler stopped further handlers.rU  )r   rq   r   check_updatero   contextfrom_updater   r   r   refresh_datahandle_updateblockr   r   rl   r$   defaultsr   r   rB   r   r  rZ  )	rJ   r   rp  any_blockingrq   r   checkr   r>  s	            rL   rk  Application.process_update  s    $ 	!,,.H2'G#008E} "#&*&8&8&@&@&L&LV&ZG &22444+2+@+@u+^I"==5&txx88 HH-- $ 1 1 7 7((%#)".txx{{m <$$+9!.	 )  (,'M  ( /j  --V-<	 W  ) 	##,,%D !'), -  #	# 5& ( * WX  ++6+EEEMM"KL Fs   3H3(F?%FF?F:CF?$F=%F?*H3-F?/H3
F7F2+F?0H32F77F?=F??H0H3"	H0+H+=H >H+H3+H00H3groupc                    SSK Jn  [        U[        5      (       d  [	        S[        R
                   35      e[        U[        5      (       d  [	        S5      e[        X5      (       a  UR                  (       a  UR                  (       a|  U R                  (       d  [        SUR                   S35      eU R                  (       aA  U R                  U R                  U5      SU R                  R                   S3S	9  [!        S
SS9  X R"                  ;  a@  / U R"                  U'   [%        ['        U R"                  R)                  5       5      5      U l        U R"                  U   R+                  U5        g)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   r5   r   r%   r   rO   intr   r   rr   r   re   r   r   rl   r   r    rq   dictsorteditemsappend)rJ   r   ry  r5   s       rL   add_handlerApplication.add_handlerA  s4   F 	S';//<[=Q=Q<RSTT%%%.//g338J8Jw||## *7<<. 9N N      //8'}4`a !  M  !	 %#%DMM%  (;(;(=!>?DMe##G,rN   rq   c                    [        U[        5      (       a   [        U[        5      (       d  [        S5      e[        U[        5      (       aX  UR	                  5        HC  u  p4[        U[
        5      (       d  [        SU S35      eU H  nU R                  XS5        M     ME     g[        U[
        5      (       a0  U H)  nU R                  U[        R                  " U5      5        M+     g[        S5      e)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 (Sequence[:class:`telegram.ext.BaseHandler`] |                 dict[int, Sequence[:class:`telegram.ext.BaseHandler`]]):
        Specify a sequence of handlers *or* a dictionary where the keys are groups and
        values are handlers.

        .. versionchanged:: 21.7
            Accepts any :class:`collections.abc.Sequence` as input instead of just a list
            or tuple.

    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 sequence of handlers.zThe `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   r~  r   r  	get_value)rJ   rq   ry  handler_groupgrp_handlersr   s         rL   add_handlersApplication.add_handlers  s    H h%%j.M.M`aah%%/7~~/?+!,99#-m_<\]   ,G$$W<  , 0@ (++#  ,*@*@*GH $ ] rN   c                     XR                   U   ;   aA  U R                   U   R                  U5        U R                   U   (       d  U R                   U	 ggg)zRemove 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)rq   remove)rJ   r   ry  s      rL   remove_handlerApplication.remove_handler  sL     mmE**MM% ''0=='MM%( ( +rN   chat_idc                 r    U R                   R                  US5        U R                  R                  U5        g)aQ  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)ra   poprb   rE  )rJ   r  s     rL   drop_chat_dataApplication.drop_chat_data  ,      	GT*3377@rN   user_idc                 r    U R                   R                  US5        U R                  R                  U5        g)aQ  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)ri   r  rj   rE  )rJ   r  s     rL   drop_user_dataApplication.drop_user_data  r  rN   messager4   old_chat_idnew_chat_idc                 v   U(       a  U(       d  U(       a  [        S5      e[        XU45      (       d  [        S5      eU(       ax  UR                  c  UR                  c  [        S5      eUR                  =(       d    UR                  R
                  nUR                  =(       d    UR                  R
                  nO5[        U[        5      (       a  [        U[        5      (       d  [        S5      eU R                  U   U R                  U'   U R                  U5        U R                  R                  U5        g)a0  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{  ra   r  rc   rE  )rJ   r  r  r  s       rL   migrate_chat_dataApplication.migrate_chat_data  s    V {NOOG+677EFF++38R8R8Z V 
 "66I',,//K!44GK[#..:k33O3OKLL'+{'C$K(3377DrN   )r   jobr  r9   c                   [        U[        5      (       a  UR                  (       a/  U R                  R	                  UR                  R
                  5        UR                  (       a/  U R                  R	                  UR                  R
                  5        U(       an  UR                  (       a%  U R                  R	                  UR                  5        UR                  (       a&  U R                  R	                  UR                  5        g g g rG   )
r   r   effective_chatrc   rE  r   effective_userrk   r  r  )rJ   r   r  s      rL   rZ  (Application._mark_for_persistence_update6  s     ff%%$$;;??@U@U@X@XY$$;;??@U@U@X@XY{{;;??L{{;;??L  rN   chat_idsuser_idsc                 R   U(       aL  [        U[        5      (       a  U R                  R                  U5        OU R                  R	                  U5        U(       aM  [        U[        5      (       a  U R
                  R                  U5        gU R
                  R	                  U5        gg)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{  rc   rE  r   rk   )rJ   r  r  s      rL    mark_data_for_update_persistence,Application.mark_data_for_update_persistenceE  sy    & (C((;;??I;;BB8L(C((;;??I;;BB8L	 rN   c                   #    U R                   R                  5       (       d]  U R                  (       d  g  [        R                  " U R                   R                  5       U R                  R                  S9I S h  vN   g g  N! [        R                   a     Of = fU R                  5       I S h  vN    U R                   R                  5       (       d  M  g 7f)N)r  )	r   r6  rr   r   wait_forr   update_intervalTimeoutErrorr   r   s    rL   r    Application._persistence_updaterc  s     1188::##&&3388: ,,<<    ; ''  ))+++% 1188::sM   2CAB 9B :B >C B BCBC/B20$CCc                    #    U R                    ISh  vN   U R                  5       I Sh  vN   SSS5      ISh  vN   g N- N N	! , ISh  vN  (       d  f       g= f7f)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    rL   r   Application.update_persistencey  sA     ( 111++--- 211- 2111sQ   A!AA!AAAA!AA!AA!AAAA!c           
        ^ #    T R                   (       d  g [        R                  S5        [        5       nT R                   R                  R
                  (       ah  T R                  R                  bQ  UR                  T R                   R                  [        T R                  R                  R                  5      5      5        T R                   R                  R                  (       a=  UR                  T R                   R                  [        T R                  5      5      5        T R                   R                  R                  (       a  T R                  n[        5       T l        T R                   n[        5       T l        X#-  nU HD  nUR                  T R                   R#                  U[        T R                  U   5      5      5        MF     U H-  nUR                  T R                   R%                  U5      5        M/     T R                   R                  R&                  (       a  T R(                  n[        5       T l        T R*                  n[        5       T l        X#-  nU HD  nUR                  T R                   R-                  U[        T R&                  U   5      5      5        MF     U H-  nUR                  T R                   R/                  U5      5        M/     SSKJn  [4        R6                  R9                  S T R:                  R=                  5        5       5       H  u  nu  p[?        X5      (       a  U	RA                  5       (       dg  T RB                  (       a  [        R                  S5        O[        RE                  S5        U	RF                  n
T R:                  U   RI                  U5        OU	RK                  5       n
OU	n
U
[L        RN                  L a  S OU
nUR                  T R                   RQ                  XxUS95        M     [R        RT                  " USS	06I S h  vN n[        R                  S
5        [R        RT                  " U 4S jU 5       6 I S h  vN   g  N? N7f)Nz.Starting next run of updating the persistence.r   )PendingStatec              3      #    U  H5  u  p[        [        R                  " U5      UR                  5       5      v   M7     g 7frG   )zipr   repeatpop_accessed_write_items).0r   states_dicts      rL   	<genexpr>3Application.__update_persistence.<locals>.<genexpr>  s9      D
%U! 	  &(L(L(NOO%Us   =?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   r   >#    U  H,  n[        U[        5      (       d  M  TR                  US S9v   M.     g 7fr  )r   r   r  )r  r   rJ   s     rL   r  r    s4      %Ffi0 >"""=%s   77)+rr   r   r   r   r   r   rl   r   rE  update_callback_datar	   persistence_datarm   update_bot_datarn   rc   rb   update_chat_datar  rx   rk   rj   update_user_datar  r   r  r   r   r   rd   r~  r   r   r   warning	old_statemark_as_accessedr   r(   DELETEDupdate_conversationr   r   )rJ   
coroutines
update_ids
delete_idsr  r  r  r   r   r  r   effective_new_stateresultss   `            rL   __update_persistence 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 & &t//>>wGH & &&00DDJ:=%D7DDJ:=%D7 $J%$$55gxW^H_?`a & &t//>>wGH &
 	L&/oo&C&C D
%)%M%M%S%S%UD
 '
"D"3 )22 !~~''||>  B '00F<<TBSSTWX&..0F"*0L4H4H*H$fNN  442E 5 ?'
J  
KdKK67 nn%
 	
 	
	 L	
s$   P!Q($Q$%9Q(Q&Q(&Q(callbackrt  c                 j    XR                   ;   a  [        R                  S5        gX R                   U'   g)a  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)rp   r   r  )rJ   r  rt  s      rL   add_error_handlerApplication.add_error_handler  s.    : ***OO_`(-H%rN   c                 <    U R                   R                  US5        g)zjRemoves an error handler.

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

N)rp   r  )rJ   r  s     rL   remove_error_handler Application.remove_error_handler   s     	$/rN   r  zJob[CCT]c           	      $  #    U R                   (       a  U R                   R                  5        H  u  nn U R                  R                  R	                  UUU UUS9nU(       ah  U[        L a  [        U R                  [        5      (       ar  U R                  R                  (       aW  U R                  R                  R                  (       d2  U R                  U" X5      USSU R                  R                   S3S	9  M   U" X5      I Sh  vN   M     g[        R#                  SUS9  g! [
         a   n[        R                  SUUS9   SnA  gSnAff = f NK! [          a       g[
         a   n[        R#                  S
US9   SnAGMZ  SnAff = f7f)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   rB  r   rW  z4No error handlers are registered, logging exception.)rp   r~  ro   rp  
from_errorr   r   r   r   r   rl   r$   ru  rt  r@  r   rB   rQ  )	rJ   r   r  r  r>  r  rt  rp  r   s	            rL   r  Application.process_error)  s    D  $$**,!"0088CC%#$("+ D G$ \)"488V44)) HH--33&& 1%)-+DHHKK=8ST	 ' 	&v777E -V P[`aK ! 	!$$Q !$ %  !	!2 81 $#$ ))H%( *  sw   2F'D(B!F>E	E
EF(
E2EFEFE
F!F$	F-FFFF)r[   r`   r\   r]   r^   r_   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   )rE   r8   )rE   r7   )rE   N)r   r5   rE   N)TrG   )NFN)NF)NNN)NN)crO   rP   rQ   rR   rS   rX  rY  rT   r*   r   r&   r-   r"   r/   r,   r)   r#   r+   r   r   r   rI   r;   r   typer   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  	_CoroTyper.   rU   r   r@  r   TaskrG  rD  rf  r   ra  rk  r:   r%   r  
_DEFAULT_0r|  r   r  r  r  r  r  rZ  r   r  r   r   r  r   r1   r  r  r   _ErrorCoroTyper  rV   rz   rN   rL   r<   r<   t   s:   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(437/30<O
O
 O
 	O

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

 uS$Y'([
 eCI&'[
 [
 c][
 "(3-0[
 'tn[
 SM[
 [
 [
 x}-[
 sm[
  uS$012![
" 
#[
B  	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:9[c3/0h{3S=9::;=
9 S,s++,9 
9x 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 TrN   )jrS   r   rM  r   r   r-  r/  rX  collectionsr   collections.abcr   r   r   r   r   copyr	   pathlibr
   typesr   r   typingr   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.typesr)   r*   r+   r,   r-   r.   r/   r0   r1   telegram.warningsr2   r3   telegramr4   r   r5   r6    telegram.ext._applicationbuilderr7   !telegram.ext._baseupdateprocessorr8   telegram.ext._jobqueuer9   r:   r{  __annotations__r;   rU   r   r  rY  r  r  rO   r   r   rB   AbstractAsyncContextManagerr<   rz   rN   rL   <module>r      sC  & 2       
 # N N   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 ->IBRR#$**=9IrN   