Python telethon.tl.types.PeerUser() Examples

The following are 11 code examples of telethon.tl.types.PeerUser(). 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: core.py    From telethon-session-sqlalchemy with MIT License 7 votes vote down vote up
def get_entity_rows_by_id(self, key: int, exact: bool = True) -> Optional[Tuple[int, int]]:
        t = self.Entity.__table__
        if exact:
            rows = self.engine.execute(select([t.c.id, t.c.hash]).where(
                and_(t.c.session_id == self.session_id, t.c.id == key)))
        else:
            ids = (
                utils.get_peer_id(PeerUser(key)),
                utils.get_peer_id(PeerChat(key)),
                utils.get_peer_id(PeerChannel(key))
            )
            rows = self.engine.execute(select([t.c.id, t.c.hash])
                .where(
                and_(t.c.session_id == self.session_id, t.c.id.in_(ids))))

        try:
            return next(rows)
        except StopIteration:
            return None 
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_user(message):
    """Get user who sent message, searching if not found easily"""
    try:
        return await message.client.get_entity(message.from_id)
    except ValueError:  # Not in database. Lets go looking for them.
        logging.debug("user not in session cache. searching...")
    if isinstance(message.to_id, PeerUser):
        await message.client.get_dialogs()
        return await message.client.get_entity(message.from_id)
    if isinstance(message.to_id, (PeerChannel, PeerChat)):
        async for user in message.client.iter_participants(message.to_id, aggressive=True):
            if user.id == message.from_id:
                return user
        logging.error("WTF! user isn't in the group where they sent the message")
        return None
    logging.error("WTF! to_id is not a user, chat or channel")
    return None 
Example #3
Source File: baseformatter.py    From telegram-export with Mozilla Public License 2.0 6 votes vote down vote up
def ensure_id_marked(eid, etype):
        """
        Given an entity ID and type (PeerUser, PeerChat, PeerChannel), return
        the marked ID regardless of whether the ID is already marked.
        """
        if etype == types.PeerUser:
            return eid
        if etype == types.PeerChat:
            if eid < 0:
                return eid
            return -eid
        if etype == types.PeerChannel:
            if str(eid).startswith('-100'):
                return eid
            # Append -100 at start. See telethon/utils.py get_peer_id.
            return -(eid + pow(10, math.floor(math.log10(eid) + 3))) 
Example #4
Source File: baseformatter.py    From telegram-export with Mozilla Public License 2.0 6 votes vote down vote up
def get_entity(self, context_id, at_date=None):
        """
        Return the entity (user, chat or channel) corresponding to this context
        ID, at the given date (like all the specific methods). Context ID must
        be marked in the Bot API style, as with get_messages_from_context.
        """
        peer_type = utils.resolve_id(context_id)[1]
        if peer_type == types.PeerUser:
            return self.get_user(context_id, at_date=at_date)
        elif peer_type == types.PeerChat:
            return self.get_chat(context_id, at_date=at_date)
        elif peer_type == types.PeerChannel:
            supergroup = self.get_supergroup(context_id, at_date=at_date)
            if not supergroup:
                return self.get_channel(context_id, at_date=at_date)
            return supergroup
        else:
            raise ValueError('Invalid ID {} given'.format(context_id)) 
Example #5
Source File: baseformatter.py    From telegram-export with Mozilla Public License 2.0 6 votes vote down vote up
def get_user(self, uid, at_date=None):
        """
        Return the user with given ID or return None. If at_date is set, get
        the user as they were at the given date (to the best of our knowledge).
        If it is not set, get the user as we last saw them. at_date should be a UTC
        timestamp or datetime object.
        """
        at_date = self.get_timestamp(at_date)
        uid = self.ensure_id_marked(uid, types.PeerUser)
        cur = self.dbconn.cursor()
        query = (
            "SELECT ID, DateUpdated, FirstName, LastName, Username, "
            "Phone, Bio, Bot, CommonChatsCount, PictureID FROM User"
        )
        row = self._fetch_at_date(cur, query, uid, at_date)
        if not row:
            return None
        user = User(*row)
        return user._replace(date_updated=datetime.datetime.fromtimestamp(user.date_updated)) 
Example #6
Source File: dumper.py    From telegram-export with Mozilla Public License 2.0 6 votes vote down vote up
def iter_resume_entities(self, context_id):
        """
        Returns an iterator over the entities that need resuming for the
        given context_id. Note that the entities are *removed* once the
        iterator is consumed completely.
        """
        c = self.conn.execute("SELECT ID, AccessHash FROM ResumeEntity "
                              "WHERE ContextID = ?", (context_id,))
        row = c.fetchone()
        while row:
            kind = resolve_id(row[0])[1]
            if kind == types.PeerUser:
                yield types.InputPeerUser(row[0], row[1])
            elif kind == types.PeerChat:
                yield types.InputPeerChat(row[0])
            elif kind == types.PeerChannel:
                yield types.InputPeerChannel(row[0], row[1])
            row = c.fetchone()

        c.execute("DELETE FROM ResumeEntity WHERE ContextID = ?",
                  (context_id,)) 
Example #7
Source File: informer.py    From informer with MIT License 6 votes vote down vote up
def get_user_by_id(self, user_id=None):
        u = await self.client.get_input_entity(PeerUser(user_id=user_id))
        user = await self.client(GetFullUserRequest(u))

        logging.info('{}: User ID {} has data:\n {}\n\n'.format(sys._getframe().f_code.co_name, user_id, user))

        return {
            'username': user.user.username,
            'first_name': user.user.first_name,
            'last_name': user.user.last_name,
            'is_verified': user.user.verified,
            'is_bot': user.user.bot,
            'is_restricted': user.user.restricted,
            'phone': user.user.phone,
        }

    # ==============================
    # Initialize keywords to monitor
    # ============================== 
Example #8
Source File: admin_tools.py    From modules-repo with GNU Affero General Public License v3.0 6 votes vote down vote up
def kickcmd(self, message):
        """Kick the user out of the group"""
        if isinstance(message.to_id, PeerUser):
            return await utils.answer(message, self.strings["kick_not_group"])
        if message.is_reply:
            user = await utils.get_user(await message.get_reply_message())
        else:
            args = utils.get_args(message)
            if len(args) == 0:
                return await utils.answer(message, self.strings["kick_none"])
            user = await self.client.get_entity(args[0])
        if not user:
            return await utils.answer(message, self.strings["who"])
        logger.debug(user)
        try:
            await self.client.kick_participant(message.chat_id, user.id)
        except BadRequestError:
            await utils.answer(message, self.strings["not_admin"])
        else:
            await self.allmodules.log("kick", group=message.chat_id, affected_uids=[user.id])
            await utils.answer(message, self.strings["kicked"].format(utils.escape_html(ascii(user.first_name)))) 
Example #9
Source File: utils.py    From friendly-telegram with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_chat_id(message):
    """Get the chat ID, but without -100 if its a channel"""
    chat = message.to_id
    if isinstance(chat, PeerUser):
        return message.chat_id
    return get_entity_id(chat) 
Example #10
Source File: orm.py    From telethon-session-sqlalchemy with MIT License 5 votes vote down vote up
def get_entity_rows_by_id(self, key: int, exact: bool = True) -> Optional[Tuple[int, int]]:
        if exact:
            query = self._db_query(self.Entity, self.Entity.id == key)
        else:
            ids = (
                utils.get_peer_id(PeerUser(key)),
                utils.get_peer_id(PeerChat(key)),
                utils.get_peer_id(PeerChannel(key))
            )
            query = self._db_query(self.Entity, self.Entity.id.in_(ids))

        row = query.one_or_none()
        return (row.id, row.hash) if row else None 
Example #11
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