o
    ZzjHR  ã                   @   sÈ   d Z ddl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mZ ddlmZ ddlmZ erVddl
mZ ed ZG d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)Úextract_tzinfo_from_defaultsÚfrom_timestamp)ÚTextEncoding)ÚJSONDict)ÚBotÚMessageEntityc                       sà  e Zd ZU dZdZ						d6ddœdededededB d	edB d
edB dedB dedB dej	dB de
dB f‡ fdd„Zed7de
dddd f‡ fdd„ƒZedededefdd„ƒZedeeB dedefdd„ƒZedeeef eeeef B deeef fd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d0< 	 ejj*Z*ee ed1< 	 ejj+Z+ee ed2< 	 ejj,Z,ee ed3< 	 ejj-Z-ee ed4< 	 ejj.Z.ee ed5< ‡  Z/S )8r   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)
            or :attr:`DATE_TIME` (for formatted date and time).

            .. versionadded:: 20.0
                Added inline custom emoji

            .. versionadded:: 20.8
                Added block quotation

            .. versionadded:: 22.7
                Added date_time
        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
        date_time_format (:obj:`str`, optional): For :attr:`DATE_TIME` only, the string that
            defines the formatting of the date and time. See `date-time entity formatting
            <https://core.telegram.org/bots/api#date-time-entity-formatting>`_ for more details and
            :class:`telegram.constants.MessageEntityDateTimeFormats` for all possible formats.

            .. versionadded:: 22.7
        unix_time (:class:`datetime.datetime`, optional): For :attr:`DATE_TIME` only, the time
            associated with the entity.
            |datetime_localization|

            .. versionadded:: 22.7
    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)
            or :attr:`DATE_TIME` (for formatted date and time).

            .. versionadded:: 20.0
                Added inline custom emoji

            .. versionadded:: 20.8
                Added block quotation

            .. versionadded:: 22.7
                Added date_time
        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
        date_time_format (:obj:`str`): Optional. For :attr:`DATE_TIME` only, the string that
            defines the formatting of the date and time. See `date-time entity formatting
            <https://core.telegram.org/bots/api#date-time-entity-formatting>`_ for more details and
            :class:`telegram.constants.MessageEntityDateTimeFormats` for all possible formats.

            .. versionadded:: 22.7
        unix_time (:class:`datetime.datetime`): Optional. For :attr:`DATE_TIME` only, the time
            associated with the entity.
            |datetime_localization|

            .. versionadded:: 22.7

    )	Úcustom_emoji_idÚdate_time_formatÚlanguageÚlengthÚoffsetÚtypeÚ	unix_timeÚurlÚuserN©Ú
api_kwargsr   r   r   r   r   r   r   r   r   r   c
                   sn   t ƒ j|
d� t tj||¡| _|| _|| _|| _	|| _
|| _|| _|| _|	| _| j| j| jf| _|  ¡  d S )Nr   )ÚsuperÚ__init__r   Ú
get_memberr   ÚMessageEntityTyper   r   r   r   r   r   r   r   r   Ú	_id_attrsÚ_freeze)Úselfr   r   r   r   r   r   r   r   r   r   ©Ú	__class__© úR/var/www/kodo/tsheker/venv/lib/python3.10/site-packages/telegram/_messageentity.pyr   ›   s   zMessageEntity.__init__ÚdataÚbotz
Bot | NoneÚreturnc                    sN   |   |¡}t| d¡t|ƒ|d< t|ƒ}t| d¡|d�|d< tƒ j||d�S )z,See :meth:`telegram.TelegramObject.de_json`.r   r   )Útzinfo)r&   r'   )Ú_parse_datar	   Úgetr   r
   r   r   Úde_json)Úclsr&   r'   Ú
loc_tzinfor"   r$   r%   r,   º   s
   
zMessageEntity.de_jsonÚtextÚentitiesc              	   C   sî   t tjdd„ |D ƒŽ ƒ}d}i }t|ƒD ]&\}}|dkr"||d  nd}| ||… }|t| tj¡ƒd 7 }|||< qg }	|D ]5}
||
j }||
j|
j	  | }t
 
|
¡}| ¡ � ||_||_	W d  ƒ n1 sjw   Y  |	 |¡ q?|	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                 s   s"   � | ]}|j |j |j fV  qd S ©N)r   r   )Ú.0Úxr$   r$   r%   Ú	<genexpr>ø   s   €  zBMessageEntity.adjust_message_entities_to_utf_16.<locals>.<genexpr>r   é   é   N)ÚsortedÚ	itertoolsÚchainÚ	enumerateÚlenÚencoder   Ú	UTF_16_LEr   r   ÚcopyÚ	_unfrozenÚappend)r/   r0   Ú	positionsÚaccumulated_lengthÚposition_translationÚiÚpositionÚlast_positionÚ
text_sliceÚoutÚentityÚtranslated_positionsÚtranslated_lengthÚ
new_entityr$   r$   r%   Ú!adjust_message_entities_to_utf_16Ç   s(   1

ÿ

þz/MessageEntity.adjust_message_entities_to_utf_16Úbyc              	   C   s|   t | tƒr| nt|  d¡ƒd }g }|D ]'}t |¡}| ¡ � | j|7  _W d  ƒ n1 s1w   Y  | |¡ q|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-ler6   N)Ú
isinstanceÚintr;   r<   r>   r?   r   r@   )rN   r0   Úeffective_shiftrH   rI   rL   r$   r$   r%   Úshift_entities  s    5

ÿzMessageEntity.shift_entitiesÚargsc                 G   sj   d}g }|D ]*}|d |d }}t |ƒdkr#|d du r#|  ||¡}| |  ||¡¡ ||7 }q||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   r5   r6   T)r;   rM   ÚextendrR   )r-   rS   Úoutput_textÚoutput_entitiesÚargr/   r0   r$   r$   r%   ÚconcatenateO  s   =
zMessageEntity.concatenateÚ	ALL_TYPESÚ
BLOCKQUOTEÚBOLDÚBOT_COMMANDÚCASHTAGÚCODEÚCUSTOM_EMOJIÚ	DATE_TIMEÚEMAILÚEXPANDABLE_BLOCKQUOTEÚHASHTAGÚITALICÚMENTIONÚPHONE_NUMBERÚPREÚSPOILERÚSTRIKETHROUGHÚ	TEXT_LINKÚTEXT_MENTIONÚ	UNDERLINEÚURL)NNNNNNr1   )0Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú	__slots__ÚstrrP   r   ÚdtmÚdatetimer   r   Úclassmethodr,   ÚstaticmethodÚ_SEMrM   rR   ÚtupleÚboolrY   Úlistr   r   rZ   r   Ú__annotations__r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   Ú__classcell__r$   r$   r"   r%   r   *   s¬   
 döôþýüûúùø	÷
öôH>þ
ýI)rr   r>   rv   ru   r8   Úcollections.abcr   Útypingr   r   Útelegramr   Útelegram._telegramobjectr   Útelegram._userr   Útelegram._utilsr   Útelegram._utils.argumentparsingr	   Útelegram._utils.datetimer
   r   Útelegram._utils.stringsr   Útelegram._utils.typesr   r   ry   r   r$   r$   r$   r%   Ú<module>   s$   