def query_inline(
        self,
        bot: Union[int, str],
        query: str = "",
        offset: str = "",
        latitude: float = None,
        longitude: float = None,
    ) -> InlineResultContainer:
        geo_point = None
        if latitude and longitude:
            geo_point = InputGeoPoint(lat=latitude, long=longitude)

        request = self.send(
            GetInlineBotResults(
                bot=self.resolve_peer(bot),
                peer=types.InputPeerSelf(),
                query=query,
                offset=offset,
                geo_point=geo_point,
            ))
        return InlineResultContainer(self,
                                     bot,
                                     query,
                                     request,
                                     offset,
                                     geo_point=geo_point)
Esempio n. 2
0
    def get_inline_bot_results(
            self,
            bot,
            query,
            offset='',
            latitude=None,
            longitude=None
    ):
        geo_point = None
        if latitude and longitude:
            geo_point = InputGeoPoint(
                lat=latitude,
                long=longitude
            )

        request = self.send(
            GetInlineBotResults(
                bot=self.resolve_peer(bot),
                peer=types.InputPeerSelf(),
                query=query,
                offset=offset,
                geo_point=geo_point
            )
        )
        return InlineResultContainer(self, bot, query, request, offset, geo_point=geo_point)
    def get_inline_bot_results(self,
                               bot: Union[int, str],
                               query: str = "",
                               offset: str = "",
                               latitude: float = None,
                               longitude: float = None):
        """Get bot results via inline queries.
        You can then send a result using :obj:`send_inline_bot_result <pyrogram.Client.send_inline_bot_result>`

        Parameters:
            bot (``int`` | ``str``):
                Unique identifier of the inline bot you want to get results from. You can specify
                a @username (str) or a bot ID (int).

            query (``str``, *optional*):
                Text of the query (up to 512 characters).
                Defaults to "" (empty string).

            offset (``str``, *optional*):
                Offset of the results to be returned.

            latitude (``float``, *optional*):
                Latitude of the location.
                Useful for location-based results only.

            longitude (``float``, *optional*):
                Longitude of the location.
                Useful for location-based results only.

        Returns:
            :obj:`BotResults <pyrogram.api.types.messages.BotResults>`: On Success.

        Raises:
            TimeoutError: In case the bot fails to answer within 10 seconds.

        Example:
            .. code-block:: python

                results = app.get_inline_bot_results("pyrogrambot")
                print(results)
        """
        # TODO: Don't return the raw type

        try:
            return self.send(
                functions.messages.GetInlineBotResults(
                    bot=self.resolve_peer(bot),
                    peer=types.InputPeerSelf(),
                    query=query,
                    offset=offset,
                    geo_point=types.InputGeoPoint(lat=latitude, long=longitude)
                    if (latitude is not None
                        and longitude is not None) else None))
        except UnknownError as e:
            # TODO: Add this -503 Timeout error into the Error DB
            if e.x.error_code == -503 and e.x.error_message == "Timeout":
                raise TimeoutError(
                    "The inline bot didn't answer in time") from None
            else:
                raise e
Esempio n. 4
0
    async def leave_chat(self, chat_id: Union[int, str], delete: bool = False):
        """Leave a group chat or channel.

        Parameters:
            chat_id (``int`` | ``str``):
                Unique identifier for the target chat or username of the target channel/supergroup
                (in the format @username).

            delete (``bool``, *optional*):
                Deletes the group chat dialog after leaving (for simple group chats, not supergroups).

        Raises:
            RPCError: In case of a Telegram RPC error.
        """
        peer = await self.resolve_peer(chat_id)

        if isinstance(peer, types.InputPeerChannel):
            return await self.send(
                functions.channels.LeaveChannel(
                    channel=await self.resolve_peer(chat_id)))
        elif isinstance(peer, types.InputPeerChat):
            r = await self.send(
                functions.messages.DeleteChatUser(
                    chat_id=peer.chat_id, user_id=types.InputPeerSelf()))

            if delete:
                await self.send(
                    functions.messages.DeleteHistory(peer=peer, max_id=0))

            return r
Esempio n. 5
0
    def leave_chat(self, chat_id: int or str, delete: bool = False):
        """Use this method to leave a group chat or channel.

        Args:
            chat_id (``int`` | ``str``):
                Unique identifier for the target chat or username of the target channel/supergroup
                (in the format @username).

            delete (``bool``, *optional*):
                Deletes the group chat dialog after leaving (for simple group chats, not supergroups).

        Raises:
            :class:`Error <pyrogram.Error>` in case of a Telegram RPC error.
        """
        peer = self.resolve_peer(chat_id)

        if isinstance(peer, types.InputPeerChannel):
            return self.send(
                functions.channels.LeaveChannel(
                    channel=self.resolve_peer(chat_id)))
        elif isinstance(peer, types.InputPeerChat):
            r = self.send(
                functions.messages.DeleteChatUser(
                    chat_id=peer.chat_id, user_id=types.InputPeerSelf()))

            if delete:
                self.send(functions.messages.DeleteHistory(peer=peer,
                                                           max_id=0))

            return r
Esempio n. 6
0
    def get_me(self):
        """A simple method for testing your authorization. Requires no parameters.

        Returns:
            Basic information about the user or bot in form of a :obj:`User` object

        Raises:
            :class:`Error <pyrogram.Error>` in case of a Telegram RPC error.
        """
        return utils.parse_user(
            self.send(functions.users.GetFullUser(types.InputPeerSelf())).user)
Esempio n. 7
0
    async def get_me(self) -> "pyrogram.User":
        """Get your own user identity.

        Returns:
            :obj:`User`: Basic information about the user or bot.

        Raises:
            RPCError: In case of a Telegram RPC error.
        """
        return pyrogram.User._parse(self, (await self.send(
            functions.users.GetFullUser(id=types.InputPeerSelf()))).user)
Esempio n. 8
0
    async def get_me(self) -> "pyrogram.User":
        """Get your own user identity.

        Returns:
            :obj:`User`: Information about the own logged in user/bot.

        Example:
            .. code-block:: python

                me = app.get_me()
                print(me)
        """
        return pyrogram.User._parse(self, (await self.send(
            functions.users.GetFullUser(id=types.InputPeerSelf()))).user)
Esempio n. 9
0
    async def leave_chat(
        self,
        chat_id: Union[int, str],
        delete: bool = False
    ):
        """Leave a group chat or channel.

        Parameters:
            chat_id (``int`` | ``str``):
                Unique identifier for the target chat or username of the target channel/supergroup
                (in the format @username).

            delete (``bool``, *optional*):
                Deletes the group chat dialog after leaving (for simple group chats, not supergroups).
                Defaults to False.

        Example:
            .. code-block:: python

                # Leave chat or channel
                app.leave_chat(chat_id)

                # Leave basic chat and also delete the dialog
                app.leave_chat(chat_id, delete=True)
        """
        peer = await self.resolve_peer(chat_id)

        if isinstance(peer, types.InputPeerChannel):
            return await self.send(
                functions.channels.LeaveChannel(
                    channel=await self.resolve_peer(chat_id)
                )
            )
        elif isinstance(peer, types.InputPeerChat):
            r = await self.send(
                functions.messages.DeleteChatUser(
                    chat_id=peer.chat_id,
                    user_id=types.InputPeerSelf()
                )
            )

            if delete:
                await self.send(
                    functions.messages.DeleteHistory(
                        peer=peer,
                        max_id=0
                    )
                )

            return r
Esempio n. 10
0
    def resolve_peer(self, peer_id: int or str):
        """Use this method to get the InputPeer of a known peer_id.

        This is a utility method intended to be used only when working with 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), whenever an InputPeer
        type is required.

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

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

        Raises:
            :class:`Error <pyrogram.Error>`
        """
        if type(peer_id) is str:
            if peer_id in ("self", "me"):
                return types.InputPeerSelf()

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

            try:
                int(peer_id)
            except ValueError:
                if peer_id not in self.peers_by_username:
                    self.send(functions.contacts.ResolveUsername(peer_id))

                return self.peers_by_username[peer_id]
            else:
                try:
                    return self.peers_by_phone[peer_id]
                except KeyError:
                    raise PeerIdInvalid

        try:  # User
            return self.peers_by_id[peer_id]
        except KeyError:
            try:  # Chat
                return self.peers_by_id[-peer_id]
            except KeyError:
                try:  # Channel
                    return self.peers_by_id[int("-100" + str(peer_id))]
                except (KeyError, ValueError):
                    raise PeerIdInvalid
Esempio n. 11
0
    async def get_me(self) -> "pyrogram.User":
        """A simple method for testing your authorization. Requires no parameters.

        Returns:
            Basic information about the user or bot in form of a :obj:`User` object

        Raises:
            :class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error.
        """
        return pyrogram.User._parse(
            self,
            (await self.send(
                functions.users.GetFullUser(
                    id=types.InputPeerSelf()
                )
            )).user
        )
Esempio n. 12
0
    def resolve_peer(self, peer_id: int or str):
        """Use this method to get the *InputPeer* of a known *peer_id*.

        It is intended to be used when working with 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).

        Args:
            peer_id (``int`` | ``str`` | ``Peer``):
                The Peer ID you want to extract the InputPeer from. Can be one of these types: ``int`` (direct ID),
                ``str`` (@username), :obj:`PeerUser <pyrogram.api.types.PeerUser>`,
                :obj:`PeerChat <pyrogram.api.types.PeerChat>`, :obj:`PeerChannel <pyrogram.api.types.PeerChannel>`

        Returns:
            :obj:`InputPeerUser <pyrogram.api.types.InputPeerUser>` or
            :obj:`InputPeerChat <pyrogram.api.types.InputPeerChat>` or
            :obj:`InputPeerChannel <pyrogram.api.types.InputPeerChannel>` depending on the *peer_id*.

        Raises:
            :class:`Error <pyrogram.Error>`
        """
        if type(peer_id) is str:
            if peer_id in ("self", "me"):
                return types.InputPeerSelf()

            match = self.INVITE_LINK_RE.match(peer_id)

            try:
                decoded = base64.b64decode(
                    match.group(1) + "=" * (-len(match.group(1)) % 4), "-_")
                return self.resolve_peer(struct.unpack(">2iq", decoded)[1])
            except (AttributeError, binascii.Error, struct.error):
                pass

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

            try:
                int(peer_id)
            except ValueError:
                try:
                    return self.peers_by_username[peer_id]
                except KeyError:
                    self.send(functions.contacts.ResolveUsername(peer_id))
                    return self.peers_by_username[peer_id]
            else:
                try:
                    return self.peers_by_phone[peer_id]
                except KeyError:
                    raise PeerIdInvalid

        if type(peer_id) is not int:
            if isinstance(peer_id, types.PeerUser):
                peer_id = peer_id.user_id
            elif isinstance(peer_id, types.PeerChat):
                peer_id = -peer_id.chat_id
            elif isinstance(peer_id, types.PeerChannel):
                peer_id = int("-100" + str(peer_id.channel_id))

        try:  # User
            return self.peers_by_id[peer_id]
        except KeyError:
            try:  # Chat
                return self.peers_by_id[-peer_id]
            except KeyError:
                try:  # Channel
                    return self.peers_by_id[int("-100" + str(peer_id))]
                except (KeyError, ValueError):
                    raise PeerIdInvalid