How to use the telethon.utils function in Telethon

To help you get started, we’ve selected a few Telethon examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github LonamiWebs / Telethon / telethon / client / downloads.py View on Github external
#
                # telethon.sync must be imported for this to work,
                # and you must not be inside an "async def".
                stream = client.iter_download(media, request_size=32)
                header = next(stream)
                stream.close()
                assert len(header) == 32

                # Fetching only the header, inside of an ``async def``
                async def main():
                    stream = client.iter_download(media, request_size=32)
                    header = await stream.__anext__()
                    await stream.close()
                    assert len(header) == 32
        """
        info = utils._get_file_info(file)
        if info.dc_id is not None:
            dc_id = info.dc_id

        if file_size is None:
            file_size = info.size

        file = info.location

        if chunk_size is None:
            chunk_size = request_size

        if limit is None and file_size is not None:
            limit = (file_size + chunk_size - 1) // chunk_size

        if stride is None:
            stride = chunk_size
github LonamiWebs / Telethon / telethon / events / messageread.py View on Github external
def __contains__(self, message):
            """`True` if the message(s) are read message."""
            if utils.is_list_like(message):
                return all(self.is_read(message))
            else:
                return self.is_read(message)
github uwinx / pomegranate / garnet / events / raw.py View on Github external
def __init__(self, types=None, *, func=None):
        super().__init__(func=func)
        if not types:
            self.types = None
        elif not utils.is_list_like(types):
            if not isinstance(types, type):
                raise TypeError('Invalid input type given %s', types)

            self.types = types
        else:
            if not all(isinstance(x, type) for x in types):
                raise TypeError('Invalid input types given %s', types)

            self.types = tuple(types)
github LonamiWebs / Telethon / telethon / tl / entity_database.py View on Github external
def expand(self, entities):
        """Adds new input entities to the local database unconditionally.
           Unknown types will be ignored.
        """
        if not entities or not self.enabled:
            return False

        new = []  # Array of entities (User, Chat, or Channel)
        new_input = {}  # Dictionary of {entity_marked_id: access_hash}
        for e in entities:
            if not isinstance(e, TLObject):
                continue

            try:
                p = utils.get_input_peer(e, allow_self=False)
                marked_id = utils.get_peer_id(p, add_mark=True)

                has_hash = False
                if isinstance(p, InputPeerChat):
                    # Chats don't have a hash
                    new_input[marked_id] = 0
                    has_hash = True
                elif p.access_hash:
                    # Some users and channels seem to be returned without
                    # an 'access_hash', meaning Telegram doesn't want you
                    # to access them. This is the reason behind ensuring
                    # that the 'access_hash' is non-zero. See issue #354.
                    new_input[marked_id] = p.access_hash
                    has_hash = True

                if self.enabled_full and has_hash:
github LonamiWebs / Telethon / telethon / sessions / memory.py View on Github external
# hex(crc32(b'InputPeer', b'InputUser' and b'InputChannel'))
                # We already have an Input version, so nothing else required
                return key
            # Try to early return if this key can be casted as input peer
            return utils.get_input_peer(key)
        except (AttributeError, TypeError):
            # Not a TLObject or can't be cast into InputPeer
            if isinstance(key, TLObject):
                key = utils.get_peer_id(key)
                exact = True
            else:
                exact = not isinstance(key, int) or key < 0

        result = None
        if isinstance(key, str):
            phone = utils.parse_phone(key)
            if phone:
                result = self.get_entity_rows_by_phone(phone)
            else:
                username, invite = utils.parse_username(key)
                if username and not invite:
                    result = self.get_entity_rows_by_username(username)
                else:
                    tup = utils.resolve_invite_link(key)[1]
                    if tup:
                        result = self.get_entity_rows_by_id(tup, exact=False)

        elif isinstance(key, int):
            result = self.get_entity_rows_by_id(key, exact)

        if not result and isinstance(key, str):
            result = self.get_entity_rows_by_name(key)
github LonamiWebs / Telethon / telethon / client / uploads.py View on Github external
notify them. Set it to ``True`` to alter this behaviour.

        Notes:
            If the ``hachoir3`` package (``hachoir`` module) is installed,
            it will be used to determine metadata from audio and video files.

        Returns:
            The `telethon.tl.custom.message.Message` (or messages) containing
            the sent file, or messages if a list of them was passed.
        """
        if not caption:
            caption = ''

        # First check if the user passed an iterable, in which case
        # we may want to send as an album if all are photo files.
        if utils.is_list_like(file):
            # TODO Fix progress_callback
            images = []
            if force_document:
                documents = file
            else:
                documents = []
                for x in file:
                    if utils.is_image(x):
                        images.append(x)
                    else:
                        documents.append(x)

            result = []
            while images:
                result += await self._send_album(
                    entity, images[:10], caption=caption,
github LonamiWebs / Telethon / telethon / tl / entity_database.py View on Github external
def get_input_entity(self, peer):
        try:
            i = utils.get_peer_id(peer, add_mark=True)
            h = self._input_entities[i]  # we store the IDs marked
            i, k = utils.resolve_id(i)  # removes the mark and returns kind

            if k == PeerUser:
                return InputPeerUser(i, h)
            elif k == PeerChat:
                return InputPeerChat(i)
            elif k == PeerChannel:
                return InputPeerChannel(i, h)

        except ValueError as e:
            raise KeyError(peer) from e
        raise KeyError(peer)
github LonamiWebs / Telethon / telethon / sessions / sqlalchemy.py View on Github external
def get_entity_rows_by_id(self, key, exact=True):
        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
github LonamiWebs / Telethon / telethon / tl / custom / dialog.py View on Github external
def __init__(self, client, dialog, entities, message):
        # Both entities and messages being dicts {ID: item}
        self._client = client
        self.dialog = dialog
        self.pinned = bool(dialog.pinned)
        self.folder_id = dialog.folder_id
        self.archived = dialog.folder_id is not None
        self.message = message
        self.date = getattr(self.message, 'date', None)

        self.entity = entities[utils.get_peer_id(dialog.peer)]
        self.input_entity = utils.get_input_peer(self.entity)
        self.id = utils.get_peer_id(self.entity)  # ^ May be InputPeerSelf()
        self.name = self.title = utils.get_display_name(self.entity)

        self.unread_count = dialog.unread_count
        self.unread_mentions_count = dialog.unread_mentions_count

        self.draft = Draft(client, self.entity, self.dialog.draft)

        self.is_user = isinstance(self.entity, types.User)
        self.is_group = (
            isinstance(self.entity, (types.Chat, types.ChatForbidden)) or
            (isinstance(self.entity, types.Channel) and self.entity.megagroup)
        )
        self.is_channel = isinstance(self.entity, types.Channel)
github LonamiWebs / Telethon / telethon / events / common.py View on Github external
def _set_client(self, client):
        """
        Setter so subclasses can act accordingly when the client is set.
        """
        self._client = client
        if self._chat_peer:
            self._chat, self._input_chat = utils._get_entity_pair(
                self.chat_id, self._entities, client._entity_cache)
        else:
            self._chat = self._input_chat = None