Python telethon.tl.types.MessageEntityMentionName() Examples

The following are 12 code examples of telethon.tl.types.MessageEntityMentionName(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module telethon.tl.types , or try the search function .
Example #1
Source File: log_group.py    From friendly-telegram with GNU Affero General Public License v3.0 6 votes vote down vote up
def append_entity(self, id, entities, message):
        fail = True
        try:
            entity = await self._client.get_input_entity(id)
        except ValueError:
            pass
        else:
            if isinstance(entity, InputPeerSelf):
                entity = await self._client.get_me(True)
            if isinstance(entity, InputPeerUser):
                fail = False
                entities.append(MessageEntityMentionName(len(message),
                                len(str(entity.user_id)), entity.user_id))
                message += str(entity.user_id)
        if fail:
            if not isinstance(id, int):
                id = utils.get_entity_id(id)
            entities.append(MessageEntityCode(len(message), len(str(id))))
            message += str(id)
        return message 
Example #2
Source File: utils.py    From friendly-telegram with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_target(message, arg_no=0):
    if any(isinstance(ent, MessageEntityMentionName) for ent in (message.entities or [])):
        e = sorted(filter(lambda x: isinstance(x, MessageEntityMentionName),
                          message.entities), key=lambda x: x.offset)[0]
        return e.user_id
    elif len(get_args(message)) > arg_no:
        user = get_args(message)[arg_no]
    elif message.is_reply:
        return (await message.get_reply_message()).from_id
    elif hasattr(message.to_id, "user_id"):
        user = message.to_id.user_id
    else:
        return None
    try:
        ent = await message.client.get_entity(user)
    except ValueError:
        return None
    else:
        if isinstance(ent, User):
            return ent.id 
Example #3
Source File: utils.py    From telegram-export with Mozilla Public License 2.0 6 votes vote down vote up
def encode_msg_entities(entities):
    """
    Encodes a list of MessageEntity into a string so it
    can easily be dumped into e.g. Dumper's database.
    """
    if not entities:
        return None
    parsed = []
    for entity in entities:
        if entity.__class__ in ENTITY_TO_TEXT:
            if isinstance(entity, types.MessageEntityTextUrl):
                extra = ',{}'.format(
                    entity.url.replace(',', '%2c').replace(';', '%3b')
                )
            elif isinstance(entity, types.MessageEntityMentionName):
                extra = ',{}'.format(entity.user_id)
            else:
                extra = ''
            parsed.append('{},{},{}{}'.format(
                ENTITY_TO_TEXT[type(entity)],
                entity.offset, entity.length, extra
            ))
    return ';'.join(parsed) 
Example #4
Source File: utils.py    From telegram-export with Mozilla Public License 2.0 6 votes vote down vote up
def decode_msg_entities(string):
    """
    Reverses the transformation made by ``utils.encode_msg_entities``.
    """
    if not string:
        return None
    parsed = []
    for part in string.split(';'):
        split = part.split(',')
        kind, offset, length = split[0], int(split[1]), int(split[2])
        if kind in TEXT_TO_ENTITY:
            if kind == 'texturl':
                parsed.append(types.MessageEntityTextUrl(
                    offset, length, split[-1]
                ))
            elif kind == 'mentionname':
                parsed.append(types.MessageEntityMentionName(
                    offset, length, int(split[-1])
                ))
            else:
                parsed.append(TEXT_TO_ENTITY[kind](offset, length))
    return parsed 
Example #5
Source File: ids.py    From TG-UserBot with GNU General Public License v3.0 6 votes vote down vote up
def get_user_from_msg(event: NewMessage.Event) -> Union[int, str, None]:
    """Get a user's ID or username from the event's regex pattern match"""
    user = None
    match = event.matches[0].group(1)

    if match == "this":
        match = str(event.chat.id)

    if event.entities:
        for entity in event.entities:
            if isinstance(entity, types.MessageEntityMentionName):
                return entity.user_id
            elif isinstance(entity, types.MessageEntityMention):
                offset = entity.offset
                length = entity.length
                maxlen = offset + length
                return event.text[offset:maxlen]

    if match:
        if isinstance(match, str) and match.isdigit():
            user = int(match.strip())
        else:
            user = match.strip()

    return user 
Example #6
Source File: ids.py    From BotHub with Apache License 2.0 6 votes vote down vote up
def get_user_from_msg(event: NewMessage.Event) -> Union[int, str, None]:
    """Get a user's ID or username from the event's regex pattern match"""
    user = None
    match = event.matches[0].group(1)

    if match == "this":
        match = str(event.chat.id)

    if event.entities:
        for entity in event.entities:
            if isinstance(entity, types.MessageEntityMentionName):
                return entity.user_id
            elif isinstance(entity, types.MessageEntityMention):
                offset = entity.offset
                length = entity.length
                maxlen = offset + length
                return event.text[offset:maxlen]

    if match:
        if isinstance(match, str) and match.isdigit():
            user = int(match.strip())
        else:
            user = match.strip()

    return user 
Example #7
Source File: tests.py    From telegram-export with Mozilla Public License 2.0 5 votes vote down vote up
def test_dump_msg_entities(self):
        """Show that entities are correctly parsed and stored"""
        message = types.Message(
            id=1,
            to_id=types.PeerUser(321),
            date=datetime.now(),
            message='No entities'
        )
        dumper = Dumper(self.dumper_config)
        fmt = BaseFormatter(dumper.conn)

        # Test with no entities
        dumper.dump_message(message, 123, None, None)
        dumper.commit()
        assert not next(fmt.get_messages_from_context(123, order='DESC')).formatting

        # Test with many entities
        text, entities = markdown.parse(
            'Testing message with __italic__, **bold**, inline '
            '[links](https://example.com) and [mentions](@hi), '
            'as well as `code` and ``pre`` blocks.'
        )
        entities[3] = types.MessageEntityMentionName(
            entities[3].offset, entities[3].length, 123
        )
        message.id = 2
        message.date -= timedelta(days=1)
        message.message = text
        message.entities = entities
        dumper.dump_message(message, 123, None, None)
        dumper.commit()
        msg = next(fmt.get_messages_from_context(123, order='ASC'))
        assert utils.decode_msg_entities(msg.formatting) == message.entities 
Example #8
Source File: slap.py    From BotHub with Apache License 2.0 5 votes vote down vote up
def get_user(event):
    if event.reply_to_msg_id:
        previous_message = await event.get_reply_message()
        replied_user = await event.client(GetFullUserRequest(previous_message.from_id))
    else:
        user = event.pattern_match.group(1)

        if user.isnumeric():
            user = int(user)

        if not user:
            self_user = await event.client.get_me()
            user = self_user.id

        if event.message.entities is not None:
            probable_user_mention_entity = event.message.entities[0]

            if isinstance(probable_user_mention_entity, MessageEntityMentionName):
                user_id = probable_user_mention_entity.user_id
                replied_user = await event.client(GetFullUserRequest(user_id))
                return replied_user
        try:
            user_object = await event.client.get_entity(user)
            replied_user = await event.client(GetFullUserRequest(user_object.id))

        except (TypeError, ValueError):
            await event.edit("`I don't slap strangers !!`")
            return None

    return replied_user 
Example #9
Source File: memes.py    From X-tra-Telegram with Apache License 2.0 5 votes vote down vote up
def get_user(event):
    """ Get the user from argument or replied message. """
    if event.reply_to_msg_id:
        previous_message = await event.get_reply_message()
        replied_user = await event.client(GetFullUserRequest(previous_message.from_id))
    else:
        user = event.pattern_match.group(1)

        if user.isnumeric():
            user = int(user)

        if not user:
            self_user = await event.client.get_me()
            user = self_user.id

        if event.message.entities is not None:
            probable_user_mention_entity = event.message.entities[0]

            if isinstance(probable_user_mention_entity, MessageEntityMentionName):
                user_id = probable_user_mention_entity.user_id
                replied_user = await event.client(GetFullUserRequest(user_id))
                return replied_user
        try:
            user_object = await event.client.get_entity(user)
            replied_user = await event.client(GetFullUserRequest(user_object.id))

        except (TypeError, ValueError):
            await event.edit("`I don't slap aliens, they ugly AF !!`")
            return None

    return replied_user 
Example #10
Source File: whois.py    From BotHub with Apache License 2.0 4 votes vote down vote up
def get_full_user(event):
    if event.reply_to_msg_id:
        previous_message = await event.get_reply_message()
        if previous_message.forward:
            replied_user = await event.client(
                GetFullUserRequest(
                    previous_message.forward.from_id or previous_message.forward.channel_id
                )
            )
            return replied_user, None
        else:
            replied_user = await event.client(
                GetFullUserRequest(
                    previous_message.from_id
                )
            )
            return replied_user, None
    else:
        input_str = None
        try:
            input_str = event.pattern_match.group(1)
        except IndexError as e:
            return None, e
        if event.message.entities is not None:
            mention_entity = event.message.entities
            probable_user_mention_entity = mention_entity[0]
            if isinstance(probable_user_mention_entity, MessageEntityMentionName):
                user_id = probable_user_mention_entity.user_id
                replied_user = await event.client(GetFullUserRequest(user_id))
                return replied_user, None
            else:
                try:
                    user_object = await event.client.get_entity(input_str)
                    user_id = user_object.id
                    replied_user = await event.client(GetFullUserRequest(user_id))
                    return replied_user, None
                except Exception as e:
                    return None, e
        elif event.is_private:
            try:
                user_id = event.chat_id
                replied_user = await event.client(GetFullUserRequest(user_id))
                return replied_user, None
            except Exception as e:
                return None, e
        else:
            try:
                user_object = await event.client.get_entity(int(input_str))
                user_id = user_object.id
                replied_user = await event.client(GetFullUserRequest(user_id))
                return replied_user, None
            except Exception as e:
                return None, e 
Example #11
Source File: profilepicgrab.py    From BotHub with Apache License 2.0 4 votes vote down vote up
def get_full_user(event):
    if event.reply_to_msg_id:
        previous_message = await event.get_reply_message()
        if previous_message.forward:
            replied_user = await event.client(
                GetFullUserRequest(
                    previous_message.forward.from_id or previous_message.forward.channel_id
                )
            )
            return replied_user, None
        else:
            replied_user = await event.client(
                GetFullUserRequest(
                    previous_message.from_id
                )
            )
            return replied_user, None
    else:
        input_str = None
        try:
            input_str = event.pattern_match.group(1)
        except IndexError as e:
            return None, e
        if event.message.entities is not None:
            mention_entity = event.message.entities
            probable_user_mention_entity = mention_entity[0]
            if isinstance(probable_user_mention_entity, MessageEntityMentionName):
                user_id = probable_user_mention_entity.user_id
                replied_user = await event.client(GetFullUserRequest(user_id))
                return replied_user, None
            else:
                try:
                    user_object = await event.client.get_entity(input_str)
                    user_id = user_object.id
                    replied_user = await event.client(GetFullUserRequest(user_id))
                    return replied_user, None
                except Exception as e:
                    return None, e
        elif event.is_private:
            try:
                user_id = event.chat_id
                replied_user = await event.client(GetFullUserRequest(user_id))
                return replied_user, None
            except Exception as e:
                return None, e
        else:
            try:
                user_object = await event.client.get_entity(int(input_str))
                user_id = user_object.id
                replied_user = await event.client(GetFullUserRequest(user_id))
                return replied_user, None
            except Exception as e:
                return None, e 
Example #12
Source File: whois.py    From X-tra-Telegram with Apache License 2.0 4 votes vote down vote up
def get_full_user(event):
    if event.reply_to_msg_id:
        previous_message = await event.get_reply_message()
        if previous_message.forward:
            replied_user = await event.client(
                GetFullUserRequest(
                    previous_message.forward.from_id or previous_message.forward.channel_id
                )
            )
            return replied_user, None
        else:
            replied_user = await event.client(
                GetFullUserRequest(
                    previous_message.from_id
                )
            )
            return replied_user, None
    else:
        input_str = None
        try:
            input_str = event.pattern_match.group(1)
        except IndexError as e:
            return None, e
        if event.message.entities is not None:
            mention_entity = event.message.entities
            probable_user_mention_entity = mention_entity[0]
            if isinstance(probable_user_mention_entity, MessageEntityMentionName):
                user_id = probable_user_mention_entity.user_id
                replied_user = await event.client(GetFullUserRequest(user_id))
                return replied_user, None
            else:
                try:
                    user_object = await event.client.get_entity(input_str)
                    user_id = user_object.id
                    replied_user = await event.client(GetFullUserRequest(user_id))
                    return replied_user, None
                except Exception as e:
                    return None, e
        elif event.is_private:
            try:
                user_id = event.chat_id
                replied_user = await event.client(GetFullUserRequest(user_id))
                return replied_user, None
            except Exception as e:
                return None, e
        else:
            try:
                user_object = await event.client.get_entity(int(input_str))
                user_id = user_object.id
                replied_user = await event.client(GetFullUserRequest(user_id))
                return replied_user, None
            except Exception as e:
                return None, e