Python telethon.utils.get_peer_id() Examples

The following are 19 code examples of telethon.utils.get_peer_id(). 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.utils , 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: downloader.py    From telegram-export with Mozilla Public License 2.0 6 votes vote down vote up
def _dump_admin_log(self, events, target):
        """
        Helper method to iterate the events from a GetAdminLogRequest
        and dump them into the Dumper, mostly to avoid excessive nesting.

        Also enqueues any media to be downloaded later by a different coroutine.
        """
        for event in events:
            assert isinstance(event, types.ChannelAdminLogEvent)
            if isinstance(event.action,
                          types.ChannelAdminLogEventActionChangePhoto):
                media_id1 = self.dumper.dump_media(event.action.new_photo)
                media_id2 = self.dumper.dump_media(event.action.prev_photo)
                self.enqueue_photo(event.action.new_photo, media_id1, target,
                                   peer_id=event.user_id, date=event.date)
                self.enqueue_photo(event.action.prev_photo, media_id2, target,
                                   peer_id=event.user_id, date=event.date)
            else:
                media_id1 = None
                media_id2 = None
            self.dumper.dump_admin_log_event(
                event, utils.get_peer_id(target), media_id1, media_id2
            )
        return min(e.id for e in events) 
Example #3
Source File: sed.py    From X-tra-Telegram with Apache License 2.0 6 votes vote down vote up
def on_regex(event):
    if event.fwd_from:
        return
    if not event.is_private and\
            await group_has_sedbot(await event.get_input_chat()):
        # await event.edit("This group has a sed bot. Ignoring this message!")
        return

    chat_id = utils.get_peer_id(await event.get_input_chat())

    m, s = doit(chat_id, event.pattern_match, await event.get_reply_message())

    if m is not None:
        s = f"{HEADER}{s}"
        out = await bot.send_message(
            await event.get_input_chat(), s, reply_to=m.id
        )
        last_msgs[chat_id].appendleft(out)
    elif s is not None:
        await event.edit(s)

    raise events.StopPropagation 
Example #4
Source File: sed.py    From BotHub with Apache License 2.0 6 votes vote down vote up
def on_regex(event):
    if event.fwd_from:
        return
    if not event.is_private and\
            await group_has_sedbot(await event.get_input_chat()):
        # await event.edit("This group has a sed bot. Ignoring this message!")
        return

    chat_id = utils.get_peer_id(await event.get_input_chat())

    m, s = doit(chat_id, event.pattern_match, await event.get_reply_message())

    if m is not None:
        s = f"{HEADER}{s}"
        out = await borg.send_message(
            await event.get_input_chat(), s, reply_to=m.id
        )
        last_msgs[chat_id].appendleft(out)
    elif s is not None:
        await event.edit(s)

    raise events.StopPropagation 
Example #5
Source File: dumper.py    From telegram-export with Mozilla Public License 2.0 6 votes vote down vote up
def dump_supergroup(self, supergroup_full, supergroup, photo_id,
                        timestamp=None):
        """Dump a Supergroup into the Supergroup table
        Params: ChannelFull, Channel to dump, MediaID
                of the profile photo in the DB.
        Returns -"""
        # Need to get the full object too for 'about' info
        values = (get_peer_id(supergroup),
                  timestamp or round(time.time()),
                  getattr(supergroup_full, 'about', None) or '',
                  supergroup.title,
                  supergroup.username,
                  photo_id,
                  supergroup_full.pinned_msg_id)

        for callback in self._dump_callbacks['supergroup']:
            callback(values)

        return self._insert_if_valid_date('Supergroup', values, date_column=1,
                                          where=('ID', get_peer_id(supergroup))) 
Example #6
Source File: dumper.py    From telegram-export with Mozilla Public License 2.0 6 votes vote down vote up
def dump_channel(self, channel_full, channel, photo_id, timestamp=None):
        """Dump a Channel into the Channel table.
        Params: ChannelFull, Channel to dump, MediaID
                of the profile photo in the DB
        Returns -"""
        # Need to get the full object too for 'about' info
        values = (get_peer_id(channel),
                  timestamp or round(time.time()),
                  channel_full.about,
                  channel.title,
                  channel.username,
                  photo_id,
                  channel_full.pinned_msg_id)

        for callback in self._dump_callbacks['channel']:
            callback(values)

        return self._insert_if_valid_date('Channel', values, date_column=1,
                                          where=('ID', get_peer_id(channel))) 
Example #7
Source File: __main__.py    From telegram-export with Mozilla Public License 2.0 5 votes vote down vote up
def find_fmt_dialog_padding(dialogs):
    """
    Find the correct amount of space padding
    to give dialogs when printing them.
    """
    no_username = NO_USERNAME[:-1]  # Account for the added '@' if username
    return (
        max(len(str(utils.get_peer_id(dialog.entity))) for dialog in dialogs),
        max(len(getattr(dialog.entity, 'username', no_username) or no_username)
            for dialog in dialogs) + 1
    ) 
Example #8
Source File: __main__.py    From telegram-export with Mozilla Public License 2.0 5 votes vote down vote up
def fmt_dialog(dialog, id_pad=0, username_pad=0):
    """
    Space-fill a row with given padding values
    to ensure alignment when printing dialogs.
    """
    username = getattr(dialog.entity, 'username', None)
    username = '@' + username if username else NO_USERNAME
    return '{:<{id_pad}} | {:<{username_pad}} | {}'.format(
        utils.get_peer_id(dialog.entity), username, dialog.name,
        id_pad=id_pad, username_pad=username_pad
    ) 
Example #9
Source File: downloader.py    From telegram-export with Mozilla Public License 2.0 5 votes vote down vote up
def _dump_messages(self, messages, target):
        """
        Helper method to iterate the messages from a GetMessageHistoryRequest
        and dump them into the Dumper, mostly to avoid excessive nesting.

        Also enqueues any media to be downloaded later by a different coroutine.
        """
        for m in messages:
            if isinstance(m, types.Message):
                media_id = self.dumper.dump_media(m.media)
                if media_id and self._check_media(m.media):
                    self.enqueue_media(
                        media_id, utils.get_peer_id(target), m.from_id, m.date
                    )

                self.dumper.dump_message(
                    message=m,
                    context_id=utils.get_peer_id(target),
                    forward_id=self.dumper.dump_forward(m.fwd_from),
                    media_id=media_id
                )
            elif isinstance(m, types.MessageService):
                if isinstance(m.action, types.MessageActionChatEditPhoto):
                    media_id = self.dumper.dump_media(m.action.photo)
                    self.enqueue_photo(m.action.photo, media_id, target,
                                       peer_id=m.from_id, date=m.date)
                else:
                    media_id = None
                self.dumper.dump_message_service(
                    message=m,
                    context_id=utils.get_peer_id(target),
                    media_id=media_id
                ) 
Example #10
Source File: tests.py    From telegram-export with Mozilla Public License 2.0 5 votes vote down vote up
def test_formatter_get_chat(self):
        """
        Ensures that the BaseFormatter is able to fetch the expected
        entities when using a date parameter.
        """
        chat = types.Chat(
            id=123,
            title='Some title',
            photo=types.ChatPhotoEmpty(),
            participants_count=7,
            date=datetime.now(),
            version=1
        )
        dumper = Dumper(self.dumper_config)

        fmt = BaseFormatter(dumper.conn)
        for month in range(1, 13):
            dumper.dump_chat(chat, None, timestamp=int(datetime(
                year=2010, month=month, day=1
            ).timestamp()))
        dumper.commit()
        cid = tl_utils.get_peer_id(chat)
        # Default should get the most recent version
        date = fmt.get_chat(cid).date_updated
        assert date == datetime(year=2010, month=12, day=1)

        # Expected behaviour is to get the previous available date
        target = datetime(year=2010, month=6, day=29)
        date = fmt.get_chat(cid, target).date_updated
        assert date == datetime(year=2010, month=6, day=1)

        # Expected behaviour is to get the next date if previous unavailable
        target = datetime(year=2009, month=12, day=1)
        date = fmt.get_chat(cid, target).date_updated
        assert date == datetime(year=2010, month=1, day=1) 
Example #11
Source File: downloader.py    From telegram-export with Mozilla Public License 2.0 5 votes vote down vote up
def enqueue_entities(self, entities):
        """
        Enqueues the given iterable of entities to be dumped later by a
        different coroutine. These in turn might enqueue profile photos.
        """
        for entity in entities:
            eid = utils.get_peer_id(entity)
            self._displays[eid] = utils.get_display_name(entity)
            if isinstance(entity, types.User):
                if entity.deleted or entity.min:
                    continue  # Empty name would cause IntegrityError
            elif isinstance(entity, types.Channel):
                if entity.left:
                    continue  # Getting full info triggers ChannelPrivateError
            elif not isinstance(entity, (types.Chat,
                                         types.InputPeerUser,
                                         types.InputPeerChat,
                                         types.InputPeerChannel)):
                # Drop UserEmpty, ChatEmpty, ChatForbidden and ChannelForbidden
                continue

            if eid in self._checked_entity_ids:
                continue
            else:
                self._checked_entity_ids.add(eid)
                if isinstance(entity, (types.User, types.InputPeerUser)):
                    self._user_queue.put_nowait(entity)
                else:
                    self._chat_queue.put_nowait(entity) 
Example #12
Source File: downloader.py    From telegram-export with Mozilla Public License 2.0 5 votes vote down vote up
def enqueue_photo(self, photo, photo_id, context,
                      peer_id=None, date=None):
        if not photo_id:
            return
        if not isinstance(context, int):
            context = utils.get_peer_id(context)
        if peer_id is None:
            peer_id = context
        if date is None:
            date = getattr(photo, 'date', None) or datetime.datetime.now()
        self.enqueue_media(photo_id, context, peer_id, date) 
Example #13
Source File: downloader.py    From telegram-export with Mozilla Public License 2.0 5 votes vote down vote up
def download_past_media(self, dumper, target_id):
        """
        Downloads the past media that has already been dumped into the
        database but has not been downloaded for the given target ID yet.

        Media which formatted filename results in an already-existing file
        will be *ignored* and not re-downloaded again.
        """
        # TODO Should this respect and download only allowed media? Or all?
        target_in = await self.client.get_input_entity(target_id)
        target = await self.client.get_entity(target_in)
        target_id = utils.get_peer_id(target)
        bar = tqdm.tqdm(unit='B', desc='media', unit_divisor=1000,
                        unit_scale=True, bar_format=BAR_FORMAT, total=0,
                        postfix={'chat': utils.get_display_name(target)})

        msg_cursor = dumper.conn.cursor()
        msg_cursor.execute('SELECT ID, Date, FromID, MediaID FROM Message '
                           'WHERE ContextID = ? AND MediaID IS NOT NULL',
                           (target_id,))

        msg_row = msg_cursor.fetchone()
        while msg_row:
            await self._download_media(
                media_id=msg_row[3],
                context_id=target_id,
                sender_id=msg_row[2],
                date=datetime.datetime.utcfromtimestamp(msg_row[1]),
                bar=bar
            )
            msg_row = msg_cursor.fetchone() 
Example #14
Source File: users.py    From Telethon with MIT License 5 votes vote down vote up
def get_peer_id(
            self: 'TelegramClient',
            peer: 'hints.EntityLike',
            add_mark: bool = True) -> int:
        """
        Gets the ID for the given entity.

        This method needs to be ``async`` because `peer` supports usernames,
        invite-links, phone numbers (from people in your contact list), etc.

        If ``add_mark is False``, then a positive ID will be returned
        instead. By default, bot-API style IDs (signed) are returned.

        Example
            .. code-block:: python

                print(await client.get_peer_id('me'))
        """
        if isinstance(peer, int):
            return utils.get_peer_id(peer, add_mark=add_mark)

        try:
            if peer.SUBCLASS_OF_ID not in (0x2d45687, 0xc91c90b6):
                # 0x2d45687, 0xc91c90b6 == crc32(b'Peer') and b'InputPeer'
                peer = await self.get_input_entity(peer)
        except AttributeError:
            peer = await self.get_input_entity(peer)

        if isinstance(peer, types.InputPeerSelf):
            peer = await self.get_me(input_peer=True)

        return utils.get_peer_id(peer, add_mark=add_mark)

    # endregion

    # region Private methods 
Example #15
Source File: __init__.py    From mautrix-telegram with GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_portal_response(self, user_id: UserID, portal: Portal) -> web.Response:
        user, _ = await self.get_user(user_id, expect_logged_in=None, require_puppeting=False)
        return web.json_response({
            "mxid": portal.mxid,
            "chat_id": get_peer_id(portal.peer),
            "peer_type": portal.peer_type,
            "title": portal.title,
            "about": portal.about,
            "username": portal.username,
            "megagroup": portal.megagroup,
            "can_unbridge": (await portal.can_user_perform(user, "unbridge")) if user else False,
        }) 
Example #16
Source File: __init__.py    From mautrix-telegram with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_chats(self, request: web.Request) -> web.Response:
        data, user, err = await self.get_user_request_info(request, expect_logged_in=True)
        if err is not None:
            return err

        if not user.is_bot:
            return web.json_response([{
                "id": chat.id,
                "title": chat.title,
            } async for chat in user.client.iter_dialogs(ignore_migrated=True, archived=False)])
        else:
            return web.json_response([{
                "id": get_peer_id(chat.peer),
                "title": chat.title,
            } for chat in user.portals.values() if chat.tgid]) 
Example #17
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 #18
Source File: userdata.py    From TG-UserBot with GNU General Public License v3.0 4 votes vote down vote up
def whichid(event: NewMessage.Event) -> None:
    """
    Get the ID of a chat/channel or user.


    `{prefix}id` or **{prefix}id user1 user2**
    """
    match = event.matches[0].group(1)
    text = ""
    if not match and not event.reply_to_msg_id:
        attr = "first_name" if event.is_private else "title"
        text = f"{getattr(event.chat, attr)}: "
        text += f"`{get_peer_id(event.chat_id)}`"
    elif event.reply_to_msg_id:
        reply = await event.get_reply_message()
        user = reply.sender_id
        if reply.fwd_from:
            if reply.fwd_from.from_id:
                user = reply.fwd_from.from_id
        peer = get_peer_id(user)
        text = f"[{peer}](tg://user?id={peer}): `{peer}`"
    else:
        failed = []
        strings = []
        users, _ = await client.parse_arguments(match)
        for user in users:
            try:
                entity = await client.get_input_entity(user)
                peer = get_peer_id(entity)
                strings.append(
                    f"[{user}](tg://user?id={peer}): `{peer}`"
                )
            except Exception as e:
                failed.append(user)
                LOGGER.debug(e)
        if strings:
            text = ",\n".join(strings)
        if failed:
            ftext = "**Users which weren't resolved:**\n"
            ftext += ", ".join(f'`{f}`' for f in failed)
            await event.answer(ftext, reply=True)
    if text:
        await event.answer(text) 
Example #19
Source File: parser.py    From BotHub with Apache License 2.0 4 votes vote down vote up
def parse_full_user(usr_obj: types.UserFull,
                              event: NewMessage.Event) -> str:
        """Human-friendly string of an User obj's attributes"""
        user = usr_obj.user

        user_id = get_peer_id(user.id)
        is_self = user.is_self
        contact = user.contact
        mutual_contact = user.mutual_contact
        deleted = user.deleted
        is_bot = user.bot
        verified = user.verified
        restricted = user.restricted
        support = user.support
        scam = user.scam
        first_name = user.first_name
        last_name = user.last_name
        username = user.username
        dc_id = user.photo.dc_id if user.photo else None
        common_chats_count = usr_obj.common_chats_count
        blocked = usr_obj.blocked
        about = usr_obj.about
        total_pics = (await event.client.get_profile_photos(user_id)).total

        text = ""  # "**USER**\n"
        text += f"  **ID:** [{user_id}](tg://user?id={user_id})"
        if first_name:
            text += f"\n  **First name:** `{first_name}`"
        if last_name:
            text += f"\n  **Last name:** `{last_name}`"
        if about:
            text += f"\n  **Bio:** `{about}`"
        if username:
            text += f"\n  **Username:** @{username}"
        if common_chats_count:
            text += f"\n  **Groups in common:** `{common_chats_count}`"
        if dc_id:
            text += f"\n  **DC ID:** `{dc_id}`"
        if is_self:
            text += f"\n  **Self:** `{is_self}`"
        if contact:
            text += f"\n  **Contact:** `{contact}`"
        if mutual_contact:
            text += f"\n  **Mutual contact:** `{mutual_contact}`"
        if deleted:
            text += f"\n  **Deleted:** `{deleted}`"
        if is_bot:
            text += f"\n  **Bot:** `{is_bot}`"
        if verified:
            text += f"\n  **Verified:** `{verified}`"
        if support:
            text += f"\n  **TG support team:** `{support}`"
        if restricted:
            text += f"\n  **Restricted for:** `{user.restriction_reason}`"
        if blocked:
            text += f"\n  **Blocked:** `{blocked}`"
        if scam:
            text += f"\n  **Scam:** `{scam}`"
        if total_pics:
            text += f"\n  **Total profile pictures:** `{total_pics}`"
        return text