L i|ddZddlZddlZddlZddlZddlmZmZddl m Z ddl m Z ddl mZmZmZmZmZmZddlmZmZmZddlmZdd lmZdd lmZmZdd lm Z dd l!m"Z" dd l#m$Z$m%Z%dZ&er ddl(m(Z(ddl)m*Z*eddZ+ee,Z-Gddej\dZ/y#e'$rdZ&YBwxYw)z]This module contains the class Updater, which tries to make creating Telegram bots intuitive.N) CoroutineSequence)Path) TracebackType) TYPE_CHECKINGAnyCallableOptionalTypeVarUnion) DEFAULT_80 DEFAULT_IP DefaultValue) get_logger)build_repr_with_selected_attrs)DVType TimePeriod) TelegramErrornetwork_retry_loop)WebhookAppClass WebhookServerTF)socket)Bot _UpdaterTypeUpdater)boundc!eZdZdZdZ d5dZdedefdZdee e d ee d ee dd fd Z de fd ZedefdZd6dZd6dZdej*ddd d d fdedededeee deedeeegd fddfdZdedededeedeee dej<deeegd fdd fdZe e!dd d dd d d d dd d f d e"e d!e"ed"e d#ee#e e$fd$ee#e e$fded%ee deee deed&ee d'ed(ee d)ee#e e$d*fddfd+Z% d7d e d!ed"e dedeee d#ee#e e$fd$ee#e e$fdeed%ee deej<d&ee d'ed(ee d)ee#e e$d*fdd fd,Z&e'd-e d e d!ed"e de f d.Z( d8d/ed%ee deee deed#ee)d0ed&ee d'ed(ee dd fd1Z*d6d2Z+d6d3Z,d6d4Z-y )9ra]This class fetches updates for the bot either via long polling or by starting a webhook server. Received updates are enqueued into the :attr:`update_queue` and may be fetched from there to handle them appropriately. Instances of this class can be used as asyncio context managers, where .. code:: python async with updater: # code is roughly equivalent to .. code:: python try: await updater.initialize() # code finally: await updater.shutdown() .. seealso:: :meth:`__aenter__` and :meth:`__aexit__`. .. seealso:: :wiki:`Architecture Overview `, :wiki:`Builder Pattern ` .. versionchanged:: 20.0 * Removed argument and attribute ``user_sig_handler`` * The only arguments and attributes are now :attr:`bot` and :attr:`update_queue` as now the sole purpose of this class is to fetch updates. The entry point to a PTB application is now :class:`telegram.ext.Application`. Args: bot (:class:`telegram.Bot`): The bot used with this Updater. update_queue (:class:`asyncio.Queue`): Queue for the updates. Attributes: bot (:class:`telegram.Bot`): The bot used with this Updater. update_queue (:class:`asyncio.Queue`): Queue for the updates. ) __lock__polling_cleanup_cb__polling_task__polling_task_stop_event_httpd _initialized_last_update_id_runningbot update_queueasyncio.Queue[object]c||_||_d|_d|_d|_d|_t j|_d|_ t j|_ d|_ y)NrF) r'r(r%r&r$r#asyncioLock_Updater__lock_Updater__polling_taskEvent!_Updater__polling_task_stop_event_Updater__polling_cleanup_cb)selfr'r(s [/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/telegram/ext/_updater.py__init__zUpdater.__init__os\ 3?  !/3 lln 6:8? &W[!r2returncK |jd{|S7#t$r|jd{7wxYww)a0 |async_context_manager| :meth:`initializes ` the Updater. Returns: The initialized Updater instance. Raises: :exc:`Exception`: If an exception is raised during initialization, :meth:`shutdown` is called in this case. N) initialize Exceptionshutdownr2s r3 __aenter__zUpdater.__aenter__sG //# # # $ --/ ! !  s.A  A A?AAexc_typeexc_valexc_tbNc@K|jd{y7w)zB|async_context_manager| :meth:`shuts down ` the Updater.N)r:)r2r=r>r?s r3 __aexit__zUpdater.__aexit__smmos c0t||jS)aGive a string representation of the updater in the form ``Updater[bot=...]``. As this class doesn't implement :meth:`object.__str__`, the default implementation will be used, which is equivalent to :meth:`__repr__`. Returns: :obj:`str` )r')rr'r;s r3__repr__zUpdater.__repr__s.dAAr5c|jSN)r&r;s r3runningzUpdater.runnings }}r5cK|jrtjdy|jj d{d|_y7 w)zInitializes the Updater & the associated :attr:`bot` by calling :meth:`telegram.Bot.initialize`. .. seealso:: :meth:`shutdown` z$This Updater is already initialized.NT)r$_LOGGERdebugr'r8r;s r3r8zUpdater.initializesD    MM@ A hh!!###  $sAAA AcK|jr td|jstj dy|j j d{d|_tj dy7!w)z Shutdown the Updater & the associated :attr:`bot` by calling :meth:`telegram.Bot.shutdown`. .. seealso:: :meth:`initialize` Raises: :exc:`RuntimeError`: If the updater is still running. zThis Updater is still running!z-This Updater is already shut down. Returning.NFzShut down of Updater complete)rF RuntimeErrorr$rHrIr'r:r;s r3r:zUpdater.shutdownsd <<?@ @  MMI J hh!!!! 56 "sAA=A;"A=g secondsr poll_intervaltimeoutbootstrap_retriesallowed_updatesdrop_pending_updateserror_callbackc nK|r tj|r td|j4d{|jr t d|j s t dd|_ tj}|j|||||||d{tjd|jd{tjd|jcdddd{S77e7:#t$r d |_wxYw7 #1d{7swYyxYww) aO Starts polling updates from Telegram. .. versionchanged:: 20.0 Removed the ``clean`` argument in favor of :paramref:`drop_pending_updates`. .. versionchanged:: 22.0 Removed the deprecated arguments ``read_timeout``, ``write_timeout``, ``connect_timeout``, and ``pool_timeout`` in favor of setting the timeouts via the corresponding methods of :class:`telegram.ext.ApplicationBuilder`. or by specifying the timeout via :paramref:`telegram.Bot.get_updates_request`. Args: poll_interval (:obj:`float`, optional): Time to wait between polling updates from Telegram in seconds. Default is ``0.0``. timeout (:obj:`int` | :class:`datetime.timedelta`, optional): Passed to :paramref:`telegram.Bot.get_updates.timeout`. Defaults to ``timedelta(seconds=10)``. .. versionchanged:: v22.2 |time-period-input| bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of will retry on failures on the Telegram server. * < 0 - retry indefinitely * 0 - no retries (default) * > 0 - retry up to X times .. versionchanged:: 21.11 The default value will be changed to from ``-1`` to ``0``. Indefinite retries during bootstrapping are not recommended. allowed_updates (Sequence[:obj:`str`], optional): Passed to :meth:`telegram.Bot.get_updates`. .. versionchanged:: 21.9 Accepts any :class:`collections.abc.Sequence` as input instead of just a list drop_pending_updates (:obj:`bool`, optional): Whether to clean any pending updates on Telegram servers before actually starting to poll. Default is :obj:`False`. .. versionadded :: 13.4 error_callback (Callable[[:exc:`telegram.error.TelegramError`], :obj:`None`], optional): Callback to handle :exc:`telegram.error.TelegramError` s that occur while calling :meth:`telegram.Bot.get_updates` during polling. Defaults to :obj:`None`, in which case errors will be logged. Callback signature:: def callback(error: telegram.error.TelegramError) Note: The :paramref:`error_callback` must *not* be a :term:`coroutine function`! If asynchronous behavior of the callback is wanted, please schedule a task from within the callback. Returns: :class:`asyncio.Queue`: The update queue that can be filled from the main thread. Raises: :exc:`RuntimeError`: If the updater is already running or was not initialized. zYThe `error_callback` must not be a coroutine function! Use an ordinary function instead. N This Updater is already running!:This Updater was not initialized via `Updater.initialize`!T)rOrPrQrSrRreadyrTzWaiting for polling to startz%Polling updates from Telegram startedF)r+iscoroutinefunction TypeErrorr-rFrKr$r&r/_start_pollingrHrIwaitr9r()r2rOrPrQrRrSrT polling_readys r3 start_pollingzUpdater.start_pollings1N g99.I  ;; % %||"#EFF$$"#_`` DM  '  ))"/#&7)=$3'#1* <=#((*** EF$$9 % % %+  %  3 % % % %s3D5DD56D 0/D D ,D  D D & D 1 D5=D>D5D D  DD D5 D2&D) 'D2.D5rXc Ktjdj||ddd{tjddfd }dtddfd} t j t fd ||xs| d |jd d d_dfd } | _ ||jyy7w)NzUpdater started (polling))rS webhook_urlrRzBootstrap doner6cK jjjd{}|rcjst j dy|D]%}jj|d{'|djdz_y7j#t$rt$r!}t j d|Yd}~yd}~wwxYw7Vw)NoffsetrPrRzcSomething went wrong processing the data received from Telegram. Received data was *not* processed!exc_infozYUpdater stopped unexpectedly. Pulled updates will be ignored and pulled again on restart.) r' get_updatesr%rr9rHcriticalrFr(put update_id)updatesexcupdaterRr2rPs r3polling_action_cbz1Updater._start_polling..polling_action_cbRs  $ 4 4//#$3!5!"||$$,  #*<"//33F;;;<+22;+@+@1+DD( 9 !    9 !  ".default_error_callbackrs   MX[  \r5cjSrE)rFr;sr3z(Updater._start_polling..zs 4<<r5zPolling UpdatesrgT) is_running action_cb on_err_cb descriptioninterval stop_event max_retriesrepeat_on_successz"Updater:start_polling:polling_task)namecKtjd jjjt j dd{y7#t$rtjdYywxYww)NzHCalling `get_updates` one more time to mark all fetched updates as read.rrMrca-Error while calling `get_updates` one more time to mark all fetched updates as read: %s. Suppressing error to ensure graceful shutdown. When polling for updates is restarted, updates may be fetched again. Please adjust timeouts via `ApplicationBuilder` or the parameter `get_updates_request` of `Bot`.) rHrIr'rir%dtm timedeltarrr)rRr2sr3_get_updates_cleanupz4Updater._start_polling.._get_updates_cleanupsx MMZ  hh**//MM!4$3 + ! !!` s:B?A!AA!BA!!B?BBBr6N) rHrI _bootstraprr+ create_taskrr0r.r1set) r2rOrPrQrSrRrXrTrprsrs ` ` ` r3r[zUpdater._start_polling:s  12 oo !5      &' @ ]  ]$ ] &11 /+(B,B-&99"& 6  & &%9!   IIK o s.CCBCr`(listenporturl_pathcertkeyra ip_addressmax_connections secret_tokenunixrcpKts td| rcd}t|tst|j dt|tst|j d|s td|j 4d{|j r td|js tdd |_ tj}|jtj|tj|||||| |||| | | | d{tjd |jd{tjd |j"cdddd{S77e7:#t $r d |_wxYw7 #1d{7swYyxYww)a Starts a small http server to listen for updates via webhook. If :paramref:`cert` and :paramref:`key` are not provided, the webhook will be started directly on ``http://listen:port/url_path``, so SSL can be handled by another application. Else, the webhook will be started on ``https://listen:port/url_path``. Also calls :meth:`telegram.Bot.set_webhook` as required. Important: If you want to use this method, you must install PTB with the optional requirement ``webhooks``, i.e. .. code-block:: bash pip install "python-telegram-bot[webhooks]" .. seealso:: :wiki:`Webhooks` .. versionchanged:: 13.4 :meth:`start_webhook` now *always* calls :meth:`telegram.Bot.set_webhook`, so pass ``webhook_url`` instead of calling ``updater.bot.set_webhook(webhook_url)`` manually. .. versionchanged:: 20.0 * Removed the ``clean`` argument in favor of :paramref:`drop_pending_updates` and removed the deprecated argument ``force_event_loop``. Args: listen (:obj:`str`, optional): IP-Address to listen on. Defaults to `127.0.0.1 `_. port (:obj:`int`, optional): Port the bot should be listening on. Must be one of :attr:`telegram.constants.SUPPORTED_WEBHOOK_PORTS` unless the bot is running behind a proxy. Defaults to ``80``. url_path (:obj:`str`, optional): Path inside url (http(s)://listen:port/). Defaults to ``''``. cert (:class:`pathlib.Path` | :obj:`str`, optional): Path to the SSL certificate file. key (:class:`pathlib.Path` | :obj:`str`, optional): Path to the SSL key file. drop_pending_updates (:obj:`bool`, optional): Whether to clean any pending updates on Telegram servers before actually starting to poll. Default is :obj:`False`. .. versionadded :: 13.4 bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of will retry on failures on the Telegram server. * < 0 - retry indefinitely * 0 - no retries (default) * > 0 - retry up to X times webhook_url (:obj:`str`, optional): Explicitly specify the webhook url. Useful behind NAT, reverse proxy, etc. Default is derived from :paramref:`listen`, :paramref:`port`, :paramref:`url_path`, :paramref:`cert`, and :paramref:`key`. ip_address (:obj:`str`, optional): Passed to :meth:`telegram.Bot.set_webhook`. Defaults to :obj:`None`. .. versionadded :: 13.4 allowed_updates (Sequence[:obj:`str`], optional): Passed to :meth:`telegram.Bot.set_webhook`. Defaults to :obj:`None`. .. versionchanged:: 21.9 Accepts any :class:`collections.abc.Sequence` as input instead of just a list max_connections (:obj:`int`, optional): Passed to :meth:`telegram.Bot.set_webhook`. Defaults to ``40``. .. versionadded:: 13.6 secret_token (:obj:`str`, optional): Passed to :meth:`telegram.Bot.set_webhook`. Defaults to :obj:`None`. When added, the web server started by this call will expect the token to be set in the ``X-Telegram-Bot-Api-Secret-Token`` header of an incoming request and will raise a :class:`http.HTTPStatus.FORBIDDEN ` 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 `_ to create the socket. If the Path does not exist, the file will be created. * or the socket itself. This option allows you to e.g. restrict the permissions of the socket for improved security. Note that you need to pass the correct family, type and socket options yourself. Caution: This parameter is a replacement for the default TCP bind. Therefore, it is mutually exclusive with :paramref:`listen` and :paramref:`port`. When using this param, you must also run a reverse proxy to the unix socket and set the appropriate :paramref:`webhook_url`. .. versionadded:: 20.8 .. versionchanged:: 21.1 Added support to pass a socket instance itself. Returns: :class:`queue.Queue`: The update queue that can be filled from the main thread. Raises: :exc:`RuntimeError`: If the updater is already running or was not initialized. z`To use `start_webhook`, PTB must be installed via `pip install "python-telegram-bot[webhooks]"`.z|You can not pass unix and {0}, only use one. Unix if you want to initialize a unix socket, or {0} for a standard TCP server.rrzqSince you set unix, you also need to set the URL to the webhook of the proxy you run in front of the unix socket.NrVrWT)rrrrrrQrSrarRrXrrrrz#Waiting for webhook server to startzWebhook server startedF)WEBHOOKS_AVAILABLErK isinstancerformatr-rFr$r&r+r/_start_webhook get_valuerHrIr\r9r()r2rrrrrrQrarRrSrrrr error_msg webhook_readys r3 start_webhookzUpdater.start_webhooksb"4  N fl3"9#3#3H#=>>dL1"9#3#3F#;<<"H ;;% %% %||"#EFF$$"#_`` DM  '  ))'11&9%//5%&7)= +$3')$3!-*" CD#((*** 67 $$K% %% %% %$+  %  A% %% %% %% %sBF6 F F6 6F!AF  F!,F  FF ' F!2 F6>F?F6F F  FF!F6!F3'F* (F3/F6c Ktjd|jdsd|}t||j|j | }|C|A t jt jj}|j||nd}t||||||_| s,|j|rdndt!j"|||} |j%|rt'|j)nd||| || | | d{|jj+| d{y#t j$r}td|d}~wwxYw7P7.w) Nz Updater thread started (webhook)/zInvalid SSL Certificatehttpshttpprotocolrrr)rr|rSrarRrrr)rX)rHrI startswithrr'r(sslcreate_default_contextPurpose CLIENT_AUTHload_cert_chainSSLErrorrrr#_gen_webhook_urlrrrr read_bytes serve_forever)r2rrrrQrRrrrSrarXrrrrappssl_ctxrns r3rzUpdater._start_webhookPso"  89""3'8*~Hh$2C2C\R   H474N4NKK++5''c2G#FD#wE //$+#--f5! 0Koo-1d&&(d)!5#+!+%  kk''e'444;<< H#$=>CG H  5sIAE%?D:A.bootstrap_del_webhooks@ MM, -# MN(())?S)T T TsA AAAc Ktjdrtjdjjd{y7w)NzSetting webhookr)url certificaterRrrSrr)rHrIr' set_webhook)rRrrSrrrr2rasr3bootstrap_set_webhookz1Updater._bootstrap..bootstrap_set_webhooksZ MM+ ,# MN((&& /%%9 /)'  sAAAAzBootstrap delete Webhook)rwryrzr{r|zBootstrap Set Webhookrr) r2r|rarRrSrrrrrrrs ` ```` ``` r3rzUpdater._bootstrapsu" U  $ {$/6+'    $/3+'      s!,AAAAAAcK|j4d{|js tdtj dd|_|j d{|jd{tj ddddd{y77D7.7 #1d{7swYyxYww)zStops the polling/webhook. .. seealso:: :meth:`start_polling`, :meth:`start_webhook` Raises: :exc:`RuntimeError`: If the updater is not running. NzThis Updater is not running!zStopping UpdaterFzUpdater.stop() is complete)r-rFrKrHrIr& _stop_httpd _stop_pollingr;s r3stopz Updater.stops;; 8 8<<"#ABB MM, -!DM""$ $ $$$& & & MM6 7 8 8 8 % & 8 8 8 8siB>B!B>AB)B#B)6B%7B) B>B'B>#B)%B)'B>)B;/B2 0B;7B>cK|jr?tjd|jjd{d|_yy7 w)z@Stops the Webhook server by calling ``WebhookServer.shutdown()``z4Waiting for current webhook connection to be closed.N)r#rHrIr:r;s r3rzUpdater._stop_httpds? ;; MMP Q++&&( ( (DK  (s?AAAcK|jrtjd|jj t j tj5|jd{dddd|_|jj|jr |jd{d|_ ytjdyy7p#1swYoxYw71w)z&Stops the polling task by awaiting it.z-Waiting background polling task to finish up.NzmNo polling cleanup callback defined. The last fetched updates may be fetched again on the next polling start.) r.rHrIr0r contextlibsuppressr+CancelledErrorclearr1warningr;s r3rzUpdater._stop_pollings    MMI J  * * . . 0$$W%;%;< *)))) * #'D   * * 0 0 2((//111,0)?!  * * *2s=AC2!C$1C"2C$6AC2>C0?#C2"C$$C-)C2)r'rr(r)r) NNNNNNrNN)NNrhNrN).__name__ __module__ __qualname____doc__ __slots__r4rr<r type BaseExceptionrrAstrrCpropertyboolrFr8r:rrfloatrintrr rr^r+r/r[rr rr rrr staticmethodrbytesrrrrrr5r3rr6s)V I\ \.\"| $ 4 ./ -( '    B# B !7. #+cmmB7!"37/3DHi%i%i% i% "(3-0 i% 'tn i%!=/4*?!@Ai% !i%Vggg g 'tn g "(3-0 g}}g!=/4*?!@Ag gV)&+/*.!"%)37/3$(!&*59k%s k%Skk% k% uS$Y'( k% eCI& ' k%k%c]k%"(3-0k%'tnk%SMk%k%smk%uS$012k% !k%h,0*./3%))-$(!&*59A5A5A5 A5  A5 "(3-0 A5uS$Y'(A5eCI& 'A5'tnA5c]A5 &A5SMA5A5smA5uS$012A5 !A5F939939#9RU9904 $$%$(!&*;;c];"(3-0 ; 'tn ; uo ;";SM;;sm; ;z8,r5)0rr+rdatetimerrcollections.abcrrpathlibrtypesrtypingrrr r r r telegram._utils.defaultvaluer rrtelegram._utils.loggingrtelegram._utils.reprrtelegram._utils.typesrrtelegram.errorrtelegram.ext._utils.networkloopr"telegram.ext._utils.webhookhandlerrrr ImportErrorrtelegramrrrrHAbstractAsyncContextManagerrrr5r3rs&d /IIMM.?4(>Q~Y7 X R j44Y?R s" B%%B/.B/