
    iY                        d 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mZ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 dd
lmZ ddlmZm Z m!Z!m"Z"m#Z#m$Z$ dZ%dZ& ede          Z'dee'         deee'                  fdZ(dee'         de)de'fdZ*de'deeeee'         e)f         f         fdZ+ G d dej,                  Z- G d dej.                  Z/ G d dee!e ef                   Z0dS )z1This module contains the PicklePersistence class.    N)deepcopy)Path)AnyCallableDictOptionalSetTupleTypeTypeVarUnioncastoverload)BotTelegramObject)FilePathInput)warn)BasePersistencePersistenceInput)ContextTypes)BDCDUDCDCDataConversationDictConversationKeyz/a known bot replaced by PTB's PicklePersistencez2an unknown bot replaced by PTB's PicklePersistenceTelegramObj)boundclsreturnc                     |                                  }t          |                              d |D                       S )zsGets all subclasses of the specified object, recursively. from
    https://stackoverflow.com/a/3862957/9706202
    c                 6    g | ]}t          |          D ]}|S  )_all_subclasses).0css      e/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/telegram/ext/_picklepersistence.py
<listcomp>z#_all_subclasses.<locals>.<listcomp>+   s.    !T!T!TQRASAS!T!TA!!T!T!T!T    )__subclasses__setunion)r   
subclassess     r(   r$   r$   &   s>     ##%%Jz??  !T!TZ!T!T!TUUUr*   kwargsc                 Z    |                      |           }|                    |           |S )a  
    This method is used for unpickling. The data, which is in the form a dictionary, is
    converted back into a class. Works mostly the same as :meth:`TelegramObject.__setstate__`.
    This function should be kept in place for backwards compatibility even if the pickling logic
    is changed, since `_custom_reduction` places references to this function into the pickled data.
    )__new____setstate__)r   r/   objs      r(   _reconstruct_tor4   .   s.     ++c

CVJr*   c                 ~    |                      d          }t          |d                   |d<   t          | j        |ffS )z
    This method is used for pickling. The bot attribute is preserved so _BotPickler().persistent_id
    works as intended.
    T)include_private
api_kwargs)
_get_attrsdictr4   	__class__)r   datas     r(   _custom_reductionr<   :   sB    
 >>$>//D d<011DS]D111r*   c                        e Zd ZdZdededef fdZdedee	ee
e         ef         f         fdZdedee         fd	Z xZS )
_BotPickler_botbotargsr/   c                 H    || _          t                      j        |i | d S Nr@   super__init__selfrA   rB   r/   r:   s       r(   rG   z_BotPickler.__init__I   ,    	$)&)))))r*   r3   r    c                 X    t          |t                    st          S t          |          S )z
        This method is used for pickling. The bot attribute is preserved so
        _BotPickler().persistent_id works as intended.
        )
isinstancer   NotImplementedr<   rI   r3   s     r(   reducer_overridez_BotPickler.reducer_overrideM   s*     #~.. 	"!! %%%r*   c                     || j         u rt          S t          |t                    rt	          dd           t
          S dS )zUsed to 'mark' the Bot, so it can be replaced later. See
        https://docs.python.org/3/library/pickle.html#pickle.Pickler.persistent_id for more info
        zHUnknown bot instance found. Will be replaced by `None` during unpickling   )
stacklevelN)r@   _REPLACED_KNOWN_BOTrL   r   r   _REPLACED_UNKNOWN_BOTrN   s     r(   persistent_idz_BotPickler.persistent_idY   sS     $)&&c3 	)Z    )(tr*   )__name__
__module____qualname__	__slots__r   r   rG   r   r
   r   r   r9   rO   objectr   strrU   __classcell__r:   s   @r(   r>   r>   F   s        I*C * *s * * * * * *
&
&	xtK0$677	8
& 
& 
& 
& HSM        r*   r>   c                   L     e Zd ZdZdededef fdZdedee         fdZ	 xZ
S )	_BotUnpicklerr?   rA   rB   r/   c                 H    || _          t                      j        |i | d S rD   rE   rH   s       r(   rG   z_BotUnpickler.__init__k   rJ   r*   pidr    c                 h    |t           k    r| j        S |t          k    rdS t          j        d          )zSReplaces the bot with the current bot if known, else it is replaced by :obj:`None`.Nz,Found unknown persistent id when unpickling!)rS   r@   rT   pickleUnpicklingError)rI   ra   s     r(   persistent_loadz_BotUnpickler.persistent_loado   s9    %%%9'''4$%STTTr*   )rV   rW   rX   rY   r   r   rG   r[   r   re   r\   r]   s   @r(   r_   r_   h   s        I*C * *s * * * * * *U3 U8C= U U U U U U U Ur*   r_   c                       e Zd ZdZdZe	 	 	 	 d1ddd	ed
ee         de	de	de
fd            Ze	 	 	 	 	 d2ddd	ed
ee         de	de	de
deeeeeef                  fd            Z	 	 	 	 	 d2d	ed
ee         de	de	de
deeeeeef                  f fdZd3dZd	edefdZd3dZd	ededdfdZdeeef         fdZdeeef         fdZdefdZdee         fdZdedefdZ dede!d ee         ddfd!Z"d"ededdfd#Z#d$ededdfd%Z$deddfd&Z%deddfd'Z&d$eddfd(Z'd"eddfd)Z(d"ed*eddfd+Z)d$ed,eddfd-Z*d.eddfd/Z+d3d0Z, xZ-S )4PicklePersistenceaq  Using python's builtin :mod:`pickle` for making your bot persistent.

    Attention:
        The interface provided by this class is intended to be accessed exclusively by
        :class:`~telegram.ext.Application`. Calling any of the methods below manually might
        interfere with the integration of persistence into :class:`~telegram.ext.Application`.

    Note:
        This implementation of :class:`BasePersistence` uses the functionality of the pickle module
        to support serialization of bot instances. Specifically any reference to
        :attr:`~BasePersistence.bot` will be replaced by a placeholder before pickling and
        :attr:`~BasePersistence.bot` will be inserted back when loading the data.

    Examples:
        :any:`Persistent Conversation Bot <examples.persistentconversationbot>`

    .. seealso:: :wiki:`Making Your Bot Persistent <Making-your-bot-persistent>`

    .. versionchanged:: 20.0

        * The parameters and attributes ``store_*_data`` were replaced by :attr:`store_data`.
        * The parameter and attribute ``filename`` were replaced by :attr:`filepath`.
        * :attr:`filepath` now also accepts :obj:`pathlib.Path` as argument.

    Args:
        filepath (:obj:`str` | :obj:`pathlib.Path`): The filepath for storing the pickle files.
            When :attr:`single_file` is :obj:`False` this will be used as a prefix.
        store_data (:class:`~telegram.ext.PersistenceInput`, optional): Specifies which kinds of
            data will be saved by this persistence instance. By default, all available kinds of
            data will be saved.
        single_file (:obj:`bool`, optional): When :obj:`False` will store 5 separate files of
            `filename_user_data`, `filename_bot_data`, `filename_chat_data`,
            `filename_callback_data` and `filename_conversations`. Default is :obj:`True`.
        on_flush (:obj:`bool`, optional): When :obj:`True` will only save to file when
            :meth:`flush` is called and keep data in memory until that happens. When
            :obj:`False` will store data on any transaction *and* on call to :meth:`flush`.
            Default is :obj:`False`.
        context_types (:class:`telegram.ext.ContextTypes`, optional): Pass an instance
            of :class:`telegram.ext.ContextTypes` to customize the types used in the
            ``context`` interface. If not passed, the defaults documented in
            :class:`telegram.ext.ContextTypes` will be used.

            .. versionadded:: 13.6
        update_interval (:obj:`int` | :obj:`float`, optional): The
            :class:`~telegram.ext.Application` will update
            the persistence in regular intervals. This parameter specifies the time (in seconds) to
            wait between two consecutive runs of updating the persistence. Defaults to 60 seconds.

            .. versionadded:: 20.0
    Attributes:
        filepath (:obj:`str` | :obj:`pathlib.Path`): The filepath for storing the pickle files.
            When :attr:`single_file` is :obj:`False` this will be used as a prefix.
        store_data (:class:`~telegram.ext.PersistenceInput`): Specifies which kinds of data will
            be saved by this persistence instance.
        single_file (:obj:`bool`): Optional. When :obj:`False` will store 5 separate files of
            `filename_user_data`, `filename_bot_data`, `filename_chat_data`,
            `filename_callback_data` and `filename_conversations`. Default is :obj:`True`.
        on_flush (:obj:`bool`): Optional. When :obj:`True` will only save to file when
            :meth:`flush` is called and keep data in memory until that happens. When
            :obj:`False` will store data on any transaction *and* on call to :meth:`flush`.
            Default is :obj:`False`.
        context_types (:class:`telegram.ext.ContextTypes`): Container for the types used
            in the ``context`` interface.

            .. versionadded:: 13.6
    )	bot_datacallback_data	chat_datacontext_typesconversationsfilepathon_flushsingle_file	user_dataNTF<   rI   zAPicklePersistence[Dict[Any, Any], Dict[Any, Any], Dict[Any, Any]]rm   
store_dataro   rn   update_intervalc                     d S rD   r#   )rI   rm   rr   ro   rn   rs   s         r(   rG   zPicklePersistence.__init__   s	     sr*   zPicklePersistence[UD, CD, BD]rk   c                     d S rD   r#   )rI   rm   rr   ro   rn   rs   rk   s          r(   rG   zPicklePersistence.__init__   s	     sr*   c                 d   t                                          ||           t          |          | _        || _        || _        d | _        d | _        d | _        d | _	        d | _
        t          t          t          t          t          t           f         |pt                                | _        d S )N)rr   rs   )rF   rG   r   rm   ro   rn   rp   rj   rh   ri   rl   r   r   r   r   r   r   rk   )rI   rm   rr   ro   rn   rs   rk   r:   s          r(   rG   zPicklePersistence.__init__   s     	JPPP"8nn+6(02626&*04]a<@b"b)=+JLNN=
 =
r*   r    c                    	 | j                             d          5 }t          | j        |                                          }d d d            n# 1 swxY w Y   |d         | _        |d         | _        |                    d| j        	                                          | _	        |                    di           | _
        |d         | _        d S # t          $ r> i | _        i | _        i | _        | j        	                                | _	        d | _
        Y d S t          j        $ r%}| j         j        }t!          d| d          |d }~wt"          $ r"}t!          d	| j         j                   |d }~ww xY w)
Nrbrp   rj   rh   ri   rl   File # does not contain valid pickle data Something went wrong unpickling )rm   openr_   rA   loadrp   rj   getrk   rh   ri   rl   OSErrorrc   rd   name	TypeError	Exception)rI   filer;   excfilenames        r(   _load_singlefilez"PicklePersistence._load_singlefile   s   	^##D)) <T$TXt4499;;< < < < < < < < < < < < < < < "+.DN!+.DN HHZ1C1L1L1N1NOODM!%/2!>!>D!%o!6D 	& 	& 	&!#DDNDN .7799DM!%D% 	\ 	\ 	\})HQHQQQRRX[[ 	^ 	^ 	^St}?QSSTTZ]]	^sN   C (AC AC AA7C AE5E5& EE5E00E5c                 r   	 |                     d          5 }t          | j        |                                          cd d d            S # 1 swxY w Y   d S # t          $ r Y d S t
          j        $ r}t          d|j         d          |d }~wt          $ r}t          d|j                   |d }~ww xY w)Nrx   ry   rz   r{   )
r|   r_   rA   r}   r   rc   rd   r   r   r   )rI   rm   r   r   s       r(   
_load_filezPicklePersistence._load_file
  s+   		Yt$$ <$TXt4499;;< < < < < < < < < < < < < < < < < <  	 	 	44% 	a 	a 	aVHMVVVWW]`` 	Y 	Y 	YNx}NNOOUXX	YsK   A 'AA AA AA 
B6%B63BB6B11B6c                    | j         | j        | j        | j        | j        d}| j                            d          5 }t          | j        |t          j
                                      |           d d d            d S # 1 swxY w Y   d S )N)rl   rp   rj   rh   ri   wbprotocol)rl   rp   rj   rh   ri   rm   r|   r>   rA   rc   HIGHEST_PROTOCOLdump)rI   r;   r   s      r(   _dump_singlefilez"PicklePersistence._dump_singlefile  s    !/!/
 
 ]%% 	U$1HIIINNtTTT	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	Us   5A>>BBr;   c                     |                     d          5 }t          | j        |t          j                                      |           d d d            d S # 1 swxY w Y   d S )Nr   r   )r|   r>   rA   rc   r   r   )rI   rm   r;   r   s       r(   
_dump_filezPicklePersistence._dump_file!  s    ]]4   	UD$1HIIINNtTTT	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	U 	Us   5AAAc                    K   | j         rnQ| j        s6|                     t          | j         d                    }|si }|| _         n|                                  t          | j                   S )zReturns the user_data from the pickle file if it exists or an empty :obj:`dict`.

        Returns:
            Dict[:obj:`int`, :obj:`dict`]: The restored user data.
        
_user_data)rp   ro   r   r   rm   r   r   rI   r;   s     r(   get_user_datazPicklePersistence.get_user_data%  |       > 	$! 	$??44=(D(D(D#E#EFFD !DNN!!###'''r*   c                    K   | j         rnQ| j        s6|                     t          | j         d                    }|si }|| _         n|                                  t          | j                   S )zReturns the chat_data from the pickle file if it exists or an empty :obj:`dict`.

        Returns:
            Dict[:obj:`int`, :obj:`dict`]: The restored chat data.
        
_chat_data)rj   ro   r   r   rm   r   r   r   s     r(   get_chat_datazPicklePersistence.get_chat_data6  r   r*   c                   K   | j         rnh| j        sM|                     t          | j         d                    }|s| j                                         }|| _         n|                                  t          | j                   S )a  Returns the bot_data from the pickle file if it exists or an empty object of type
        :obj:`dict` | :attr:`telegram.ext.ContextTypes.bot_data`.

        Returns:
            :obj:`dict` | :attr:`telegram.ext.ContextTypes.bot_data`: The restored bot data.
        	_bot_data)rh   ro   r   r   rm   rk   r   r   r   s     r(   get_bot_datazPicklePersistence.get_bot_dataG  s       = 	$! 	$??44=(C(C(C#D#DEED 5)2244 DMM!!###&&&r*   c                    K   | j         rnQ| j        s6|                     t          | j         d                    }|sd}|| _         n|                                  | j         dS t          | j                   S )ad  Returns the callback data from the pickle file if it exists or :obj:`None`.

        .. versionadded:: 13.6

        Returns:
            Tuple[List[Tuple[:obj:`str`, :obj:`float`, Dict[:obj:`str`, :class:`object`]]],
            Dict[:obj:`str`, :obj:`str`]] | :obj:`None`: The restored metadata or :obj:`None`,
            if no data was stored.
        _callback_dataN)ri   ro   r   r   rm   r   r   r   s     r(   get_callback_dataz#PicklePersistence.get_callback_dataY  s        	$! 	$??44=(H(H(H#I#IJJD !%D!!###%4*+++r*   r   c                   K   | j         rnS| j        s8|                     t          | j         d                    }|s|i i}|| _         n|                                  | j                             |i                                           S )zReturns the conversations from the pickle file if it exists or an empty dict.

        Args:
            name (:obj:`str`): The handlers name.

        Returns:
            :obj:`dict`: The restored conversations for the handler.
        _conversations)rl   ro   r   r   rm   r   r~   copy)rI   r   r;   s      r(   get_conversationsz#PicklePersistence.get_conversationsp  s        	$! 	$??44=(H(H(H#I#IJJD "bz!%D!!###!%%dB//44666r*   key	new_statec                 Z  K   | j         si | _         | j                             |i                               |          |k    rdS || j         |         |<   | j        sO| j        s2|                     t          | j         d          | j                    dS |                                  dS dS )aJ  Will update the conversations for the given handler and depending on :attr:`on_flush`
        save the pickle file.

        Args:
            name (:obj:`str`): The handler's name.
            key (:obj:`tuple`): The key the state is changed for.
            new_state (:class:`object`): The new state for the given key.
        Nr   )	rl   
setdefaultr~   rn   ro   r   r   rm   r   )rI   r   r   r   s       r(   update_conversationz%PicklePersistence.update_conversation  s       ! 	$!#D((r2266s;;yHHF(14 %} 	(# (%E%E%E F FHZ[[[[[%%'''''		( 	(r*   user_idc                 &  K   | j         i | _         | j                             |          |k    rdS || j         |<   | j        sO| j        s2|                     t          | j         d          | j                    dS |                                  dS dS )a  Will update the user_data and depending on :attr:`on_flush` save the pickle file.

        Args:
            user_id (:obj:`int`): The user the data might have been changed for.
            data (:obj:`dict`): The :attr:`telegram.ext.Application.user_data` ``[user_id]``.
        Nr   )rp   r~   rn   ro   r   r   rm   r   )rI   r   r;   s      r(   update_user_dataz"PicklePersistence.update_user_data         >!DN>g&&$..F"&w} 	(# (%A%A%A B BDNSSSSS%%'''''		( 	(r*   chat_idc                 &  K   | j         i | _         | j                             |          |k    rdS || j         |<   | j        sO| j        s2|                     t          | j         d          | j                    dS |                                  dS dS )a  Will update the chat_data and depending on :attr:`on_flush` save the pickle file.

        Args:
            chat_id (:obj:`int`): The chat the data might have been changed for.
            data (:obj:`dict`): The :attr:`telegram.ext.Application.chat_data` ``[chat_id]``.
        Nr   )rj   r~   rn   ro   r   r   rm   r   )rI   r   r;   s      r(   update_chat_dataz"PicklePersistence.update_chat_data  r   r*   c                    K   | j         |k    rdS || _         | j        sO| j        s2|                     t	          | j         d          | j                    dS |                                  dS dS )zWill update the bot_data and depending on :attr:`on_flush` save the pickle file.

        Args:
            data (:obj:`dict` | :attr:`telegram.ext.ContextTypes.bot_data`): The
                :attr:`telegram.ext.Application.bot_data`.
        Nr   )rh   rn   ro   r   r   rm   r   r   s     r(   update_bot_dataz!PicklePersistence.update_bot_data  s       =D  F} 	(# (%@%@%@ A A4=QQQQQ%%'''''		( 	(r*   c                    K   | j         |k    rdS || _         | j        sO| j        s2|                     t	          | j         d          | j                    dS |                                  dS dS )a  Will update the callback_data (if changed) and depending on :attr:`on_flush` save the
        pickle file.

        .. versionadded:: 13.6

        Args:
            data (Tuple[List[Tuple[:obj:`str`, :obj:`float`,                 Dict[:obj:`str`, :class:`object`]]], Dict[:obj:`str`, :obj:`str`]]):
                The relevant data to restore :class:`telegram.ext.CallbackDataCache`.
        Nr   )ri   rn   ro   r   r   rm   r   r   s     r(   update_callback_dataz&PicklePersistence.update_callback_data  s       %%F!} 	(# (%E%E%E F FHZ[[[[[%%'''''		( 	(r*   c                    K   | j         dS | j                             |d           | j        sO| j        s2|                     t          | j         d          | j                    dS |                                  dS dS )zWill delete the specified key from the ``chat_data`` and depending on
        :attr:`on_flush` save the pickle file.

        .. versionadded:: 20.0

        Args:
            chat_id (:obj:`int`): The chat id to delete from the persistence.
        Nr   )rj   poprn   ro   r   r   rm   r   )rI   r   s     r(   drop_chat_dataz PicklePersistence.drop_chat_data         >!F7D)))} 	(# (%A%A%A B BDNSSSSS%%'''''		( 	(r*   c                    K   | j         dS | j                             |d           | j        sO| j        s2|                     t          | j         d          | j                    dS |                                  dS dS )zWill delete the specified key from the ``user_data`` and depending on
        :attr:`on_flush` save the pickle file.

        .. versionadded:: 20.0

        Args:
            user_id (:obj:`int`): The user id to delete from the persistence.
        Nr   )rp   r   rn   ro   r   r   rm   r   )rI   r   s     r(   drop_user_dataz PicklePersistence.drop_user_data  r   r*   rp   c                 
   K   dS )zDoes nothing.

        .. versionadded:: 13.6
        .. seealso:: :meth:`telegram.ext.BasePersistence.refresh_user_data`
        Nr#   )rI   r   rp   s      r(   refresh_user_dataz#PicklePersistence.refresh_user_data  
        r*   rj   c                 
   K   dS )zDoes nothing.

        .. versionadded:: 13.6
        .. seealso:: :meth:`telegram.ext.BasePersistence.refresh_chat_data`
        Nr#   )rI   r   rj   s      r(   refresh_chat_dataz#PicklePersistence.refresh_chat_data  r   r*   rh   c                 
   K   dS )zDoes nothing.

        .. versionadded:: 13.6
        .. seealso:: :meth:`telegram.ext.BasePersistence.refresh_bot_data`
        Nr#   )rI   rh   s     r(   refresh_bot_dataz"PicklePersistence.refresh_bot_data  r   r*   c                   K   | j         r;| j        s| j        s| j        s| j        s| j        r|                                  dS dS | j        r0|                     t          | j	         d          | j                   | j        r0|                     t          | j	         d          | j                   | j        r0|                     t          | j	         d          | j                   | j        r0|                     t          | j	         d          | j                   | j        r2|                     t          | j	         d          | j                   dS dS )z/Will save all data in memory to pickle file(s).r   r   r   r   r   N)
ro   rp   rj   rh   ri   rl   r   r   r   rm   )rI   s    r(   flushzPicklePersistence.flush  s      	\(>( =( %	(
 %( %%'''''( ( ~ T%A%A%A B BDNSSS~ T%A%A%A B BDNSSS} R%@%@%@ A A4=QQQ! \%E%E%E F FHZ[[[! \%E%E%E F FHZ[[[[[\ \r*   )NTFrq   )NTFrq   N)r    N).rV   rW   rX   __doc__rY   r   r   r   r   boolfloatrG   r   r   r   r   r   r   r   r   r   rZ   r   r   intr   r   r   r   r   r[   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r\   r]   s   @r(   rg   rg   x   s       A AF
I  26 !# Q -. 	
     X  26 !#AE - -. 	
    S"b"_ =>   X 26 !#AE
 

 -.
 	

 
 
  S"b"_ =>
 
 
 
 
 
,^ ^ ^ ^.
Y4 
YC 
Y 
Y 
Y 
Y	U 	U 	U 	UU4 Uv U$ U U U U(T#r'] ( ( ( ("(T#r'] ( ( ( ("'B ' ' ' '$,'): , , , ,.7C 74D 7 7 7 7(((-(:B6:J(	( ( ( (,(c ( ( ( ( ( ($(c ( ( ( ( ( ($(" ( ( ( ( ( (w (4 ( ( ( (((C (D ( ( ( (&(C (D ( ( ( (&s r d    s r d    r d    \ \ \ \ \ \ \ \r*   rg   )1r   rc   r   r   pathlibr   typingr   r   r   r   r	   r
   r   r   r   r   r   telegramr   r   telegram._utils.typesr   telegram._utils.warningsr   telegram.extr   r   telegram.ext._contexttypesr   telegram.ext._utils.typesr   r   r   r   r   r   rS   rT   r   r$   r9   r4   r<   Picklerr>   	Unpicklerr_   rg   r#   r*   r(   <module>r      s  & 8 7              b b b b b b b b b b b b b b b b b b b b b b b b b b ( ( ( ( ( ( ( ( / / / / / / ) ) ) ) ) ) : : : : : : : : 3 3 3 3 3 3 \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \G L gm>:::Vk* Vs43D/E V V V V	k* 	D 	[ 	 	 	 		2; 	255kARTXAX;Y1Y+Z 	2 	2 	2 	2    &.   DU U U U UF$ U U U z\ z\ z\ z\ z\B
3 z\ z\ z\ z\ z\r*   