
    iKI                         d Z ddlZddl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 ddlmZ dd	lmZ dd
lmZ ddlmZ erddlmZ ed         Z G d de          ZdS )zHThis module contains an object that represents a Telegram MessageEntity.    N)Sequence)TYPE_CHECKINGFinal)	constants)TelegramObject)User)enum)de_json_optional)TextEncoding)JSONDict)BotMessageEntityc                       e Zd ZU dZdZ	 	 	 	 d.dddededededz  d	edz  d
edz  dedz  dedz  f fdZ	e
d/dedddd f fd            Zedededefd            Zedeez  dedefd            Ze
deeef         eeeef         z  deeef         fd            Z eej                  Zeee                  ed<   	 ej        j        Zee         ed<   	 ej        j        Zee         ed<   	 ej        j        Zee         ed<   	 ej        j        Zee         ed<   	 ej        j        Zee         ed<   	 ej        j        Zee         ed <   	 ej        j        Zee         ed!<   	 ej        j         Z ee         ed"<   	 ej        j!        Z!ee         ed#<   	 ej        j"        Z"ee         ed$<   	 ej        j#        Z#ee         ed%<   	 ej        j$        Z$ee         ed&<   	 ej        j%        Z%ee         ed'<   	 ej        j&        Z&ee         ed(<   	 ej        j'        Z'ee         ed)<   	 ej        j(        Z(ee         ed*<   	 ej        j)        Z)ee         ed+<   	 ej        j*        Z*ee         ed,<   	 ej        j+        Z+ee         ed-<    xZ,S )0r   a  
    This object represents one special entity in a text message. For example, hashtags,
    usernames, URLs, etc.

    Objects of this class are comparable in terms of equality. Two objects of this class are
    considered equal, if their :attr:`type`, :attr:`offset` and :attr:`length` are equal.

    Args:
        type (:obj:`str`): Type of the entity. Can be :attr:`MENTION` (``@username``),
            :attr:`HASHTAG` (``#hashtag`` or ``#hashtag@chatusername``), :attr:`CASHTAG` (``$USD``
            or ``USD@chatusername``), :attr:`BOT_COMMAND` (``/start@jobs_bot``), :attr:`URL`
            (``https://telegram.org``), :attr:`EMAIL` (``do-not-reply@telegram.org``),
            :attr:`PHONE_NUMBER` (``+1-212-555-0123``),
            :attr:`BOLD` (**bold text**), :attr:`ITALIC` (*italic text*), :attr:`UNDERLINE`
            (underlined text), :attr:`STRIKETHROUGH`, :attr:`SPOILER` (spoiler message),
            :attr:`BLOCKQUOTE` (block quotation), :attr:`CODE` (monowidth string), :attr:`PRE`
            (monowidth block), :attr:`TEXT_LINK` (for clickable text URLs), :attr:`TEXT_MENTION`
            (for users without usernames), :attr:`CUSTOM_EMOJI` (for inline custom emoji stickers).

            .. versionadded:: 20.0
                Added inline custom emoji

            .. versionadded:: 20.8
                Added block quotation
        offset (:obj:`int`): Offset in UTF-16 code units to the start of the entity.
        length (:obj:`int`): Length of the entity in UTF-16 code units.
        url (:obj:`str`, optional): For :attr:`TEXT_LINK` only, url that will be opened after
            user taps on the text.
        user (:class:`telegram.User`, optional): For :attr:`TEXT_MENTION` only, the mentioned
             user.
        language (:obj:`str`, optional): For :attr:`PRE` only, the programming language of
            the entity text.
        custom_emoji_id (:obj:`str`, optional): For :attr:`CUSTOM_EMOJI` only, unique identifier
            of the custom emoji. Use :meth:`telegram.Bot.get_custom_emoji_stickers` to get full
            information about the sticker.

            .. versionadded:: 20.0
    Attributes:
        type (:obj:`str`): Type of the entity.  Can be :attr:`MENTION` (``@username``),
            :attr:`HASHTAG` (``#hashtag`` or ``#hashtag@chatusername``), :attr:`CASHTAG` (``$USD``
            or ``USD@chatusername``), :attr:`BOT_COMMAND` (``/start@jobs_bot``), :attr:`URL`
            (``https://telegram.org``), :attr:`EMAIL` (``do-not-reply@telegram.org``),
            :attr:`PHONE_NUMBER` (``+1-212-555-0123``),
            :attr:`BOLD` (**bold text**), :attr:`ITALIC` (*italic text*), :attr:`UNDERLINE`
            (underlined text), :attr:`STRIKETHROUGH`, :attr:`SPOILER` (spoiler message),
            :attr:`BLOCKQUOTE` (block quotation), :attr:`CODE` (monowidth string), :attr:`PRE`
            (monowidth block), :attr:`TEXT_LINK` (for clickable text URLs), :attr:`TEXT_MENTION`
            (for users without usernames), :attr:`CUSTOM_EMOJI` (for inline custom emoji stickers).

            .. versionadded:: 20.0
                Added inline custom emoji

            .. versionadded:: 20.8
                Added block quotation
        offset (:obj:`int`): Offset in UTF-16 code units to the start of the entity.
        length (:obj:`int`): Length of the entity in UTF-16 code units.
        url (:obj:`str`): Optional. For :attr:`TEXT_LINK` only, url that will be opened after
            user taps on the text.
        user (:class:`telegram.User`): Optional. For :attr:`TEXT_MENTION` only, the mentioned
             user.
        language (:obj:`str`): Optional. For :attr:`PRE` only, the programming language of
            the entity text.
        custom_emoji_id (:obj:`str`): Optional. For :attr:`CUSTOM_EMOJI` only, unique identifier
            of the custom emoji. Use :meth:`telegram.Bot.get_custom_emoji_stickers` to get full
            information about the sticker.

            .. versionadded:: 20.0

    )custom_emoji_idlanguagelengthoffsettypeurluserN
api_kwargsr   r   r   r   r   r   r   r   c                D   t                                          |           t          j        t          j        ||          | _        || _        || _        || _	        || _
        || _        || _        | j        | j        | j        f| _        |                                  d S )Nr   )super__init__r	   
get_memberr   MessageEntityTyper   r   r   r   r   r   r   	_id_attrs_freeze)
selfr   r   r   r   r   r   r   r   	__class__s
            W/Users/shanyulin/my-agent/.venv/lib/python3.11/site-packages/telegram/_messageentity.pyr   zMessageEntity.__init__q   s     	J///)DdDQQ	!!"!%	$,+:)T[$+>    databotz
Bot | Nonereturnc                     |                      |          }t          |                    d          t          |          |d<   t	                                          ||          S )z,See :meth:`telegram.TelegramObject.de_json`.r   )r$   r%   )_parse_datar
   getr   r   de_json)clsr$   r%   r!   s      r"   r*   zMessageEntity.de_json   sQ     t$$'(8(8$DDVwwDc222r#   textentitiesc                 H   t          t          j        d |D                        }d}i }t          |          D ]Y\  }}|dk    r||dz
           nd}| ||         }|t	          |                    t          j                            dz  z  }|||<   Zg }	|D ]}
||
j                 }||
j        |
j	        z            |z
  }t          j
        |
          }|                                5  ||_        ||_	        ddd           n# 1 swxY w Y   |	                    |           |	S )u  Utility functionality for converting the offset and length of entities from
        Unicode (:obj:`str`) to UTF-16 (``utf-16-le`` encoded :obj:`bytes`).

        Tip:
            Only the offsets and lengths calulated in UTF-16 is acceptable by the Telegram Bot API.
            If they are calculated using the Unicode string (:obj:`str` object), errors may occur
            when the text contains characters that are not in the Basic Multilingual Plane (BMP).
            For more information, see `Unicode <https://en.wikipedia.org/wiki/Unicode>`_ and
            `Plane (Unicode) <https://en.wikipedia.org/wiki/Plane_(Unicode)>`_.

        .. versionadded:: 21.4

        Examples:
            Below is a snippet of code that demonstrates how to use this function to convert
            entities from Unicode to UTF-16 space. The ``unicode_entities`` are calculated in
            Unicode and the `utf_16_entities` are calculated in UTF-16.

            .. code-block:: python

                text = "𠌕 bold 𝄢 italic underlined: 𝛙𝌢𑁍"
                unicode_entities = [
                    MessageEntity(offset=2, length=4, type=MessageEntity.BOLD),
                    MessageEntity(offset=9, length=6, type=MessageEntity.ITALIC),
                    MessageEntity(offset=28, length=3, type=MessageEntity.UNDERLINE),
                ]
                utf_16_entities = MessageEntity.adjust_message_entities_to_utf_16(
                    text, unicode_entities
                )
                await bot.send_message(
                    chat_id=123,
                    text=text,
                    entities=utf_16_entities,
                )
                # utf_16_entities[0]: offset=3, length=4
                # utf_16_entities[1]: offset=11, length=6
                # utf_16_entities[2]: offset=30, length=6

        Args:
            text (:obj:`str`): The text that the entities belong to
            entities (Sequence[:class:`telegram.MessageEntity`]): Sequence of entities
                with offset and length calculated in Unicode

        Returns:
            Sequence[:class:`telegram.MessageEntity`]: Sequence of entities
            with offset and length calculated in UTF-16 encoding
        c              3   B   K   | ]}|j         |j         |j        z   fV  d S N)r   r   ).0xs     r"   	<genexpr>zBMessageEntity.adjust_message_entities_to_utf_16.<locals>.<genexpr>   s3      ,_,_QRah188K-L,_,_,_,_,_,_r#   r         N)sorted	itertoolschain	enumeratelenencoder   	UTF_16_LEr   r   copy	_unfrozenappend)r,   r-   	positionsaccumulated_lengthposition_translationipositionlast_position
text_sliceoutentitytranslated_positionstranslated_length
new_entitys                 r"   !adjust_message_entities_to_utf_16z/MessageEntity.adjust_message_entities_to_utf_16   s   b 9?,_,_V^,_,_,_`aa	 02$Y// 	@ 	@KAx01AIa!e,,1MmH45J#j&7&78N&O&O"P"PTU"UU-? ** 		# 		#F#7#F $V]V]%BCFZZ  6**J%%'' 6 6$8
!$5
!6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 JJz""""
s   &DD	D	byc                 V   t          | t                    r| n$t          |                     d                    dz  }g }|D ]g}t	          j        |          }|                                5  |xj        |z  c_        ddd           n# 1 swxY w Y   |                    |           h|S )u  Utility functionality for shifting the offset of entities by a given amount.

        Examples:
            Shifting by an integer amount:

            .. code-block:: python

                text = "Hello, world!"
                entities = [
                    MessageEntity(offset=0, length=5, type=MessageEntity.BOLD),
                    MessageEntity(offset=7, length=5, type=MessageEntity.ITALIC),
                ]
                shifted_entities = MessageEntity.shift_entities(1, entities)
                await bot.send_message(
                    chat_id=123,
                    text="!" + text,
                    entities=shifted_entities,
                )

            Shifting using a string:

            .. code-block:: python

                text = "Hello, world!"
                prefix = "𝄢"
                entities = [
                    MessageEntity(offset=0, length=5, type=MessageEntity.BOLD),
                    MessageEntity(offset=7, length=5, type=MessageEntity.ITALIC),
                ]
                shifted_entities = MessageEntity.shift_entities(prefix, entities)
                await bot.send_message(
                    chat_id=123,
                    text=prefix + text,
                    entities=shifted_entities,
                )

        Tip:
            The :paramref:`entities` are *not* modified in place. The function returns a sequence
            of new objects.

        .. versionadded:: 21.5

        Args:
            by (:obj:`str` | :obj:`int`): Either the amount to shift the offset by or
                a string whose length will be used as the amount to shift the offset by. In this
                case, UTF-16 encoding will be used to calculate the length.
            entities (Sequence[:class:`telegram.MessageEntity`]): Sequence of entities

        Returns:
            Sequence[:class:`telegram.MessageEntity`]: Sequence of entities with the offset shifted
        z	utf-16-ler5   N)
isinstanceintr:   r;   r=   r>   r   r?   )rM   r-   effective_shiftrG   rH   rK   s         r"   shift_entitieszMessageEntity.shift_entities   s    j !+2s 3 3Y""RYY{=S=S9T9TXY9Y 	# 	#F6**J%%'' 5 5!!_4!!5 5 5 5 5 5 5 5 5 5 5 5 5 5 5JJz""""
s   +BB	B	argsc                     d}g }|D ]s}|d         |d         }}t          |          dk    r |d         du r|                     ||          }|                    |                     ||                     ||z  }t||fS )u
  Utility functionality for concatenating two text along with their formatting entities.

        Tip:
            This function is useful for prefixing an already formatted text with a new text and its
            formatting entities. In particular, it automatically correctly handles UTF-16 encoding.

        Examples:
            This example shows a callback function that can be used to add a prefix and suffix to
            the message in a :class:`~telegram.ext.CallbackQueryHandler`:

            .. code-block:: python

                async def prefix_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
                    prefix = "𠌕 bold 𝄢 italic underlined: 𝛙𝌢𑁍 | "
                    prefix_entities = [
                        MessageEntity(offset=2, length=4, type=MessageEntity.BOLD),
                        MessageEntity(offset=9, length=6, type=MessageEntity.ITALIC),
                        MessageEntity(offset=28, length=3, type=MessageEntity.UNDERLINE),
                    ]
                    suffix = " | 𠌕 bold 𝄢 italic underlined: 𝛙𝌢𑁍"
                    suffix_entities = [
                        MessageEntity(offset=5, length=4, type=MessageEntity.BOLD),
                        MessageEntity(offset=12, length=6, type=MessageEntity.ITALIC),
                        MessageEntity(offset=31, length=3, type=MessageEntity.UNDERLINE),
                    ]

                    message = update.effective_message
                    first = (prefix, prefix_entities, True)
                    second = (message.text, message.entities)
                    third = (suffix, suffix_entities, True)

                    new_text, new_entities = MessageEntity.concatenate(first, second, third)
                    await update.callback_query.edit_message_text(
                        text=new_text,
                        entities=new_entities,
                    )

        Hint:
            The entities are *not* modified in place. The function returns a
            new sequence of objects.

        .. versionadded:: 21.5

        Args:
            *args (tuple[:obj:`str`, Sequence[:class:`telegram.MessageEntity`]] |                 tuple[:obj:`str`, Sequence[:class:`telegram.MessageEntity`], :obj:`bool`]):
                Arbitrary number of tuples containing the text and its entities to concatenate.
                If the last element of the tuple is a :obj:`bool`, it is used to determine whether
                to adjust the entities to UTF-16 via
                :meth:`adjust_message_entities_to_utf_16`. UTF-16 adjustment is disabled by
                default.

        Returns:
            tuple[:obj:`str`, Sequence[:class:`telegram.MessageEntity`]]: The concatenated text
            and its entities
         r   r4   r5   T)r:   rL   extendrR   )r+   rS   output_textoutput_entitiesargr,   r-   s          r"   concatenatezMessageEntity.concatenate  s    z /1 	  	 C VSV(D3xx!||A$@@xPP""3#5#5k8#L#LMMM4KKO++r#   	ALL_TYPES
BLOCKQUOTEBOLDBOT_COMMANDCASHTAGCODECUSTOM_EMOJIEMAILEXPANDABLE_BLOCKQUOTEHASHTAGITALICMENTIONPHONE_NUMBERPRESPOILERSTRIKETHROUGH	TEXT_LINKTEXT_MENTION	UNDERLINEURL)NNNNr0   )-__name__
__module____qualname____doc__	__slots__strrP   r   r   r   classmethodr*   staticmethod_SEMrL   rR   tupleboolrZ   listr   r   r[   r   __annotations__r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   __classcell__)r!   s   @r"   r   r   (   sF        D DL [I  #&* '+    	
 4Z Tk * t tO     6 3 38 3, 3/ 3 3 3 3 3 [3 F Ft F F F F \FP <39 < < < < < \<| G,S$Y%T4"88G, 
sDy	G, G, G, [G,R #'$y'B"C"CIuT#YCCCI&8CJc
CCC !27D%*777<'9EKsEEEC#5=GU3Z===? 27D%*777<(:GL%*GGG "39E5:999=(1(C(Y5:YYY $5=GU3Z===?"4;FE#J;;;>#5=GU3Z===?(:GL%*GGGD15Cs555;#5=GU3Z=== !* ; IM5:IIIE%7AIuSzAAAA(:GL%*GGGD%7AIuSzAAAA15Cs555;;;;r#   )rr   r=   r7   collections.abcr   typingr   r   telegramr   telegram._telegramobjectr   telegram._userr   telegram._utilsr	   telegram._utils.argumentparsingr
   telegram._utils.stringsr   telegram._utils.typesr   r   rw   r    r#   r"   <module>r      s-  & O N      $ $ $ $ $ $ ' ' ' ' ' ' ' '       3 3 3 3 3 3                   < < < < < < 0 0 0 0 0 0 * * * * * *  r< r< r< r< r<N r< r< r< r< r<r#   