
    ՟f_P                     N   d Z ddlZddlZddlmZ ddlmZ ddlmZm	Z	m
Z
mZmZmZmZmZmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZ ddlmZ  ddl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+ ddl,m-Z-  edd      Z. ee/d      Z0 G d ded   ejb                        Z2y)zEThis module contains an abstract class to make POST and GET requests.    N)
HTTPStatus)TracebackType)	AsyncContextManagerFinalListOptionalTupleTypeTypeVarUnionfinal)DEFAULT_NONE)DefaultValue)
get_logger)TextEncoding)JSONDictODVInput)warn)__version__)
BadRequestChatMigratedConflict	ForbiddenInvalidTokenNetworkError
RetryAfterTelegramError)RequestData)PTBDeprecationWarningRTBaseRequest)bound)
class_namec                      e Zd ZU dZdZde dZee   e	d<   	 e
Zeed      e	d<   	 ded	efd
Zdeee      dee   dee   d	dfdZed	ee   fd       Zej0                  dd       Zej0                  dd       Zedeeeefdedee   dee   dee   dee   dee   d	eee e   e!f   fd       Z"eeeeefdedee   dee   dee   dee   d	e#fd       Z$deeeefdededee   dee   dee   dee   dee   d	e#fdZ%e&de#d	efd       Z'ej0                  deeeefdededee   dee   dee   dee   dee   d	e(e)e#f   fd       Z*y) r!   a?  Abstract interface class that allows python-telegram-bot to make requests to the Bot API.
    Can be implemented via different asyncio HTTP libraries. An implementation of this class
    must implement all abstract methods and properties.

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

    .. code:: python

        async with request_object:
            # code

    is roughly equivalent to

    .. code:: python

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

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

    Tip:
        JSON encoding and decoding is done with the standard library's :mod:`json` by default.
        To use a custom library for this, you can override :meth:`parse_json_payload` and implement
        custom logic to encode the keys of :attr:`telegram.request.RequestData.parameters`.

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

    .. versionadded:: 20.0
     zpython-telegram-bot vz" (https://python-telegram-bot.org)
USER_AGENTNr   selfreturnc                    K   	 | j                          d{    | S 7 # t        $ r | j                          d{  7    w xY ww)a'  |async_context_manager| :meth:`initializes <initialize>` the Request.

        Returns:
            The initialized Request instance.

        Raises:
            :exc:`Exception`: If an exception is raised during initialization, :meth:`shutdown`
                is called in this case.
        N)
initialize	Exceptionshutdownr'   s    X/var/www/cvtools/html/venv/lib/python3.12/site-packages/telegram/request/_baserequest.py
__aenter__zBaseRequest.__aenter__j   sG     	//### 	 $ 	--/!!	s.   A    A  A?AAexc_typeexc_valexc_tbc                 @   K   | j                          d{    y7 w)zB|async_context_manager| :meth:`shuts down <shutdown>` the Request.N)r,   )r'   r0   r1   r2   s       r.   	__aexit__zBaseRequest.__aexit__{   s      mmos   c                     t         )a  This property must return the default read timeout in seconds used by this class.
        More precisely, the returned value should be the one used when
        :paramref:`post.read_timeout` of :meth:post` is not passed/equal to :attr:`DEFAULT_NONE`.

        .. versionadded:: 20.7

        Warning:
            For now this property does not need to be implemented by subclasses and will raise
            :exc:`NotImplementedError` if accessed without being overridden. However, in future
            versions, this property will be abstract and must be implemented by subclasses.

        Returns:
            :obj:`float` | :obj:`None`: The read timeout in seconds.
        )NotImplementedErrorr-   s    r.   read_timeoutzBaseRequest.read_timeout   s
      "!    c                    K   yw)zKInitialize resources used by this class. Must be implemented by a subclass.Nr%   r-   s    r.   r*   zBaseRequest.initialize           c                    K   yw)zMStop & clear resources used by this class. Must be implemented by a subclass.Nr%   r-   s    r.   r,   zBaseRequest.shutdown   r:   r;   urlrequest_datar7   write_timeoutconnect_timeoutpool_timeoutc           	      z   K   | j                  |d|||||       d{   }| j                  |      }|d   S 7 w)a_  Makes a request to the Bot API handles the return code and parses the answer.

        Warning:
            This method will be called by the methods of :class:`telegram.Bot` and should *not* be
            called manually.

        Args:
            url (:obj:`str`): The URL to request.
            request_data (:class:`telegram.request.RequestData`, optional): An object containing
                information about parameters and files to upload for the request.
            read_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the maximum
                amount of time (in seconds) to wait for a response from Telegram's server instead
                of the time specified during creating of this object. Defaults to
                :attr:`DEFAULT_NONE`.
            write_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the maximum
                amount of time (in seconds) to wait for a write operation to complete (in terms of
                a network socket; i.e. POSTing a request or uploading a file) instead of the time
                specified during creating of this object. Defaults to :attr:`DEFAULT_NONE`.
            connect_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the
                maximum amount of time (in seconds) to wait for a connection attempt to a server
                to succeed instead of the time specified during creating of this object. Defaults
                to :attr:`DEFAULT_NONE`.
            pool_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the maximum
                amount of time (in seconds) to wait for a connection to become available instead
                of the time specified during creating of this object. Defaults to
                :attr:`DEFAULT_NONE`.

        Returns:
          The JSON response of the Bot API.

        POSTr=   methodr>   r7   r?   r@   rA   Nresult)_request_wrapperparse_json_payload)	r'   r=   r>   r7   r?   r@   rA   rF   	json_datas	            r.   postzBaseRequest.post   s\     R ,,%%'+% - 
 
 ++F3	 ""
s   ;9;c                 L   K   | j                  |d||||       d{   S 7 w)a  Retrieve the contents of a file by its URL.

        Warning:
            This method will be called by the methods of :class:`telegram.Bot` and should *not* be
            called manually.

        Args:
            url (:obj:`str`): The web location we want to retrieve.
            read_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the maximum
                amount of time (in seconds) to wait for a response from Telegram's server instead
                of the time specified during creating of this object. Defaults to
                :attr:`DEFAULT_NONE`.
            write_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the maximum
                amount of time (in seconds) to wait for a write operation to complete (in terms of
                a network socket; i.e. POSTing a request or uploading a file) instead of the time
                specified during creating of this object. Defaults to :attr:`DEFAULT_NONE`.
            connect_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the
                maximum amount of time (in seconds) to wait for a connection attempt to a server
                to succeed instead of the time specified during creating of this object. Defaults
                to :attr:`DEFAULT_NONE`.
            pool_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the maximum
                amount of time (in seconds) to wait for a connection to become available instead
                of the time specified during creating of this object. Defaults to
                :attr:`DEFAULT_NONE`.

        Returns:
            :obj:`bytes`: The files contents.

        GET)r=   rE   r7   r?   r@   rA   N)rG   )r'   r=   r7   r?   r@   rA   s         r.   retrievezBaseRequest.retrieve   s=     L **%'+% + 
 
 	
 
s   $"$rE   c           	        K   ddl m} |xr |j                  }	|	rMt        | |      sAt        |t              r1t        t        dd| j                  j                   d      d       d}	 | j                  |||||||	       d
{   \  }
}t        j                  |
cxk  rdk  r|S  | j                  |      }|j!                  d      }|r|nd}|j!                  d      }|rD|j!                  d      }|rt#        |      |j!                  d      }|rt%        |      |d| z  }|
t        j&                  k(  rt)        |      |
t        j*                  t        j,                  fv rt/        |      |
t        j0                  k(  rt3        |      |
t        j4                  k(  rt7        |      |
t        j8                  k(  rt        |xs d      t        | d|
 d      7 ]# t        $ r  t        $ r}t        d|      |d
}~ww xY ww)a  Wraps the real implementation request method.

        Performs the following tasks:
        * Handle the various HTTP response codes.
        * Parse the Telegram server response.

        Args:
            url (:obj:`str`): The URL to request.
            method (:obj:`str`): HTTP method (i.e. 'POST', 'GET', etc.).
            request_data (:class:`telegram.request.RequestData`, optional): An object containing
                information about parameters and files to upload for the request.
            read_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the maximum
                amount of time (in seconds) to wait for a response from Telegram's server instead
                of the time specified during creating of this object. Defaults to
                :attr:`DEFAULT_NONE`.
            write_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the maximum
                amount of time (in seconds) to wait for a write operation to complete (in terms of
                a network socket; i.e. POSTing a request or uploading a file) instead of the time
                specified during creating of this object. Defaults to :attr:`DEFAULT_NONE`.
            connect_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the
                maximum amount of time (in seconds) to wait for a connection attempt to a server
                to succeed instead of the time specified during creating of this object. Defaults
                to :attr:`DEFAULT_NONE`.
            pool_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the maximum
                amount of time (in seconds) to wait for a connection to become available instead
                of the time specified during creating of this object. Defaults to
                :attr:`DEFAULT_NONE`.

        Returns:
            bytes: The payload part of the HTTP server response.

        Raises:
            TelegramError

        r   )HTTPXRequestz20.7z(The `write_timeout` parameter passed to z.do_request will default to `BaseRequest.DEFAULT_NONE` instead of 20 in future versions for *all* methods of the `Bot` class, including methods sending media.   )
stacklevel   rD   Nz&Unknown error in HTTP implementation: i+  descriptionzUnknown HTTPError
parametersmigrate_to_chat_idretry_afterz3
The server response contained unknown parameters: zBad Gatewayz ())telegram.requestrO   multipart_data
isinstancer   r   r   	__class____name__
do_requestr   r+   r   r   OKrH   getr   r   	FORBIDDENr   	NOT_FOUNDUNAUTHORIZEDr   BAD_REQUESTr   CONFLICTr   BAD_GATEWAY)r'   r=   rE   r>   r7   r?   r@   rA   rO   	has_filescodepayloadexcresponse_datarS   messagerT   rU   rV   s                      r.   rG   zBaseRequest._request_wrapper  s6    \ 	2 !@\%@%@	t\2=,7%>t~~?V?V>W X] ]  M	Z"&//))+ /) #2 # MD' ==D'C'N ( //8#''6!,+2E #&&|4
!+0D!E!"#566$..7K --Mj\ZZG:'''G$$J((**A*ABB w'':)))W%%:&&&7##:))){;m<<gYba011m  	 	Z!GwOPVYY	Zs=   A&H)G$ G!G$ EH!G$ $H
6HH

Hrh   c                     | j                  t        j                  d      }	 t        j                  |      S # t
        $ r'}t        j                  d|       t        d      |d}~ww xY w)a  Parse the JSON returned from Telegram.

        Tip:
            By default, this method uses the standard library's :func:`json.loads` and
            ``errors="replace"`` in :meth:`bytes.decode`.
            You can override it to customize either of these behaviors.

        Args:
            payload (:obj:`bytes`): The UTF-8 encoded JSON payload as returned by Telegram.

        Returns:
            dict: A JSON parsed as Python dict with results.

        Raises:
            TelegramError: If loading the JSON data failed
        replacez$Can not load invalid JSON data: "%s"zInvalid server responseN)	decoder   UTF_8jsonloads
ValueError_LOGGER	exceptionr   )rh   	decoded_sri   s      r.   rH   zBaseRequest.parse_json_payload  s`    $ NN<#5#5yA		D::i(( 	DDiP 9:C	Ds   7 	A' "A""A'c                    K   yw)a  Makes a request to the Bot API. Must be implemented by a subclass.

        Warning:
            This method will be called by :meth:`post` and :meth:`retrieve`. It should *not* be
            called manually.

        Args:
            url (:obj:`str`): The URL to request.
            method (:obj:`str`): HTTP method (i.e. ``'POST'``, ``'GET'``, etc.).
            request_data (:class:`telegram.request.RequestData`, optional): An object containing
                information about parameters and files to upload for the request.
            read_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the maximum
                amount of time (in seconds) to wait for a response from Telegram's server instead
                of the time specified during creating of this object. Defaults to
                :attr:`DEFAULT_NONE`.
            write_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the maximum
                amount of time (in seconds) to wait for a write operation to complete (in terms of
                a network socket; i.e. POSTing a request or uploading a file) instead of the time
                specified during creating of this object. Defaults to :attr:`DEFAULT_NONE`.
            connect_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the
                maximum amount of time (in seconds) to wait for a connection attempt to a server
                to succeed instead of the time specified during creating of this object. Defaults
                to :attr:`DEFAULT_NONE`.
            pool_timeout (:obj:`float` | :obj:`None`, optional): If passed, specifies the maximum
                amount of time (in seconds) to wait for a connection to become available instead
                of the time specified during creating of this object. Defaults to
                :attr:`DEFAULT_NONE`.

        Returns:
            Tuple[:obj:`int`, :obj:`bytes`]: The HTTP return code & the payload part of the server
            response.
        Nr%   )r'   r=   rE   r>   r7   r?   r@   rA   s           r.   r]   zBaseRequest.do_request  r:   r;   )r(   N)+r\   
__module____qualname____doc__	__slots__ptb_verr&   r   str__annotations___DEFAULT_NONEr   r   r    r/   r   r
   BaseExceptionr   r4   propertyfloatr7   abcabstractmethodr*   r,   r   r   r   r   r   r   boolrJ   bytesrM   rG   staticmethodrH   r	   intr]   r%   r8   r.   r!   r!   3   s*    D I4WI=_`Jc
`.;L%T*+;	r b "	4./	 -(	 '		
 
	 "huo " "" 	Z Z 	\ \  /3(4)5+7(44#4# {+4# uo	4#
  4# "%4# uo4# 
xh-	.4# 4#l  )5)5+7(4,
,
 uo,
  	,

 "%,
 uo,
 
,
 ,
d /3(4)5+7(4}2}2 }2 {+	}2
 uo}2  }2 "%}2 uo}2 
}2~ DE Dh D D0 	
 /3(4)5+7(4)) ) {+	)
 uo)  ) "%) uo) 
sEz	) )r8   )3ry   r   rp   httpr   typesr   typingr   r   r   r   r	   r
   r   r   r   telegram._utils.defaultvaluer   r~   r   telegram._utils.loggingr   telegram._utils.stringsr   telegram._utils.typesr   r   telegram._utils.warningsr   telegram._versionr   r{   telegram.errorr   r   r   r   r   r   r   r   telegram.request._requestdatar   telegram.warningsr   r    r\   rs   ABCr!   r%   r8   r.   <module>r      s   & L 
    a a a F 5 . 0 4 ) 4	 	 	 6 3T'
X-
8U&GGUr8   