Source code for pyrogram.methods.advanced.resolve_peer

#  Pyrogram - Telegram MTProto API Client Library for Python
#  Copyright (C) 2017-present Dan <https://github.com/delivrance>
#
#  This file is part of Pyrogram.
#
#  Pyrogram is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Lesser General Public License as published
#  by the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Pyrogram is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public License
#  along with Pyrogram.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import annotations

import logging
import re

import pyrogram
from pyrogram import raw, utils
from pyrogram.errors import BadRequest, PeerIdInvalid

log = logging.getLogger(__name__)


class ResolvePeer:
    async def resolve_peer(
        self: pyrogram.Client, peer_id: int | str
    ) -> raw.base.InputPeer | raw.base.InputUser | raw.base.InputChannel:
        """Get the InputPeer of a known peer id.
        Useful whenever an InputPeer type is required.

        .. note::

            This is a utility method intended to be used **only** when working with raw
            :obj:`functions <pyrogram.raw.functions>` (i.e: a Telegram API method you wish to use which is not
            available yet in the Client class as an easy-to-use method).

        .. include:: /_includes/usable-by/users-bots.rst

        Parameters:
            peer_id (``int`` | ``str``):
                The peer id you want to extract the InputPeer from.
                Can be a direct id (int), a username (str), a phone number (str) or a t.me link (str).

        Returns:
            ``InputPeer``: On success, the resolved peer id is returned in form of an InputPeer object.

        Raises:
            KeyError: In case the peer doesn't exist in the internal database.
        """
        if not self.is_connected:
            raise ConnectionError("Client has not been started yet")

        if isinstance(peer_id, str):
            match = self.CHANNEL_MESSAGE_LINK_RE.match(peer_id.lower())

            if match:
                peer_id = match.group(1)

                if peer_id.isdigit():
                    peer_id = utils.get_channel_id(int(peer_id))

        try:
            return await self.storage.get_peer_by_id(peer_id)
        except KeyError:
            if isinstance(peer_id, str):
                if peer_id in ("self", "me"):
                    return raw.types.InputPeerSelf()

                peer_id = re.sub(r"[@+\s]", "", peer_id.lower())

                try:
                    int(peer_id)
                except ValueError:
                    try:
                        return await self.storage.get_peer_by_username(peer_id)
                    except KeyError:
                        await self.invoke(raw.functions.contacts.ResolveUsername(username=peer_id))

                        return await self.storage.get_peer_by_username(peer_id)
                else:
                    try:
                        return await self.storage.get_peer_by_phone_number(peer_id)
                    except KeyError:
                        if not peer_id.isdigit():
                            raise PeerIdInvalid

                        try:
                            r = await self.invoke(
                                raw.functions.contacts.ResolvePhone(phone=peer_id)
                            )
                        except BadRequest as e:
                            raise PeerIdInvalid from e

                        return await self.storage.get_peer_by_id(utils.get_peer_id(r.peer))

            peer_type = utils.get_peer_type(peer_id)

            min_peer_ref = getattr(self, "_min_peer_messages", {}).get(peer_id)
            if min_peer_ref is None and peer_type == "channel":
                min_peer_ref = getattr(self, "_min_peer_messages", {}).get(
                    utils.get_channel_id(peer_id)
                )

            if min_peer_ref is not None:
                chat_id, msg_id = min_peer_ref
                try:
                    channel_peer = await self.resolve_peer(chat_id)
                except Exception:
                    pass
                else:
                    if peer_type == "user":
                        return raw.types.InputPeerUserFromMessage(
                            peer=channel_peer,
                            msg_id=msg_id,
                            user_id=peer_id,
                        )
                    elif peer_type == "channel":
                        return raw.types.InputPeerChannelFromMessage(
                            peer=channel_peer,
                            msg_id=msg_id,
                            channel_id=utils.get_channel_id(peer_id),
                        )

            if peer_type == "user":
                try:
                    await self.fetch_peers(
                        await self.invoke(
                            raw.functions.users.GetUsers(
                                id=[raw.types.InputUser(user_id=peer_id, access_hash=0)]
                            )
                        )
                    )
                except Exception:
                    pass
            elif peer_type == "chat":
                try:
                    await self.invoke(raw.functions.messages.GetChats(id=[-peer_id]))
                except Exception:
                    pass
            elif peer_type == "secret_chat":
                raise PeerIdInvalid
            else:
                try:
                    await self.invoke(
                        raw.functions.channels.GetChannels(
                            id=[
                                raw.types.InputChannel(
                                    channel_id=utils.get_channel_id(peer_id), access_hash=0
                                )
                            ]
                        )
                    )
                except Exception:
                    pass

            try:
                return await self.storage.get_peer_by_id(peer_id)
            except KeyError:
                min_peer_ref = getattr(self, "_min_peer_messages", {}).get(peer_id)
                if min_peer_ref is None and peer_type == "channel":
                    min_peer_ref = getattr(self, "_min_peer_messages", {}).get(
                        utils.get_channel_id(peer_id)
                    )

                if min_peer_ref is not None:
                    chat_id, msg_id = min_peer_ref
                    try:
                        channel_peer = await self.resolve_peer(chat_id)
                    except Exception:
                        raise PeerIdInvalid from None

                    if peer_type == "user":
                        return raw.types.InputPeerUserFromMessage(
                            peer=channel_peer,
                            msg_id=msg_id,
                            user_id=peer_id,
                        )
                    elif peer_type == "channel":
                        return raw.types.InputPeerChannelFromMessage(
                            peer=channel_peer,
                            msg_id=msg_id,
                            channel_id=utils.get_channel_id(peer_id),
                        )

                raise PeerIdInvalid