How to use the telethon.helpers 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 / network / mtproto_sender.py View on Github external
def _decode_msg(self, body):
        """
        Decodes the body of the payload received from the network.

        :param body: the body to be decoded.
        :return: a tuple of (decoded message, remote message id, remote seq).
        """
        if len(body) < 8:
            if body == b'l\xfe\xff\xff':
                raise BrokenAuthKeyError()
            else:
                raise BufferError("Can't decode packet ({})".format(body))

        with BinaryReader(body) as reader:
            return helpers.unpack_message(self.session, reader)
github kandnub / TG-UserBot / userbot / utils / FastTelethon.py View on Github external
async def _internal_transfer_to_telegram(
    client: TelegramClient, response: BinaryIO, progress_callback: callable
) -> Tuple[TypeInputFile, int]:
    file_id = helpers.generate_random_long()
    file_size = os.path.getsize(response.name)

    hash_md5 = hashlib.md5()
    uploader = ParallelTransferrer(client)
    part_size, part_count, is_large = await uploader.init_upload(
        file_id, file_size
    )
    buffer = bytearray()
    for data in stream_file(response):
        if progress_callback:
            r = progress_callback(response.tell(), file_size)
            if inspect.isawaitable(r):
                await r
        if not is_large:
            hash_md5.update(data)
        if len(buffer) == 0 and len(data) == part_size:
github LonamiWebs / Telethon / telethon / hints.py View on Github external
types.TypePeer,
    types.TypeInputPeer,
    Entity,
    FullEntity
]
EntitiesLike = typing.Union[EntityLike, typing.Sequence[EntityLike]]

ButtonLike = typing.Union[types.TypeKeyboardButton, custom.Button]
MarkupLike = typing.Union[
    types.TypeReplyMarkup,
    ButtonLike,
    typing.Sequence[ButtonLike],
    typing.Sequence[typing.Sequence[ButtonLike]]
]

TotalList = helpers.TotalList

DateLike = typing.Optional[typing.Union[float, datetime.datetime, datetime.date, datetime.timedelta]]

LocalPath = str
ExternalUrl = str
BotFileID = str
FileLike = typing.Union[
    LocalPath,
    ExternalUrl,
    BotFileID,
    bytes,
    typing.BinaryIO,
    types.TypeMessageMedia,
    types.TypeInputFile,
    types.TypeInputFileLocation
]
github LonamiWebs / Telethon / telethon / client / downloads.py View on Github external
# media which should be done with `download_media` instead.
            return None

        file = self._get_proper_filename(
            file, 'profile_photo', '.jpg',
            possible_names=possible_names
        )

        try:
            result = await self.download_file(loc, file, dc_id=dc_id)
            return result if file is bytes else file
        except errors.LocationInvalidError:
            # See issue #500, Android app fails as of v4.6.0 (1155).
            # The fix seems to be using the full channel chat photo.
            ie = await self.get_input_entity(entity)
            ty = helpers._entity_type(ie)
            if ty == helpers._EntityType.CHANNEL:
                full = await self(functions.channels.GetFullChannelRequest(ie))
                return await self._download_photo(
                    full.full_chat.chat_photo, file,
                    date=None, progress_callback=None,
                    thumb=thumb
                )
            else:
                # Until there's a report for chats, no need to.
                return None
github LonamiWebs / Telethon / telethon / network / mtproto_sender.py View on Github external
"""Sends the given packet bytes with the additional
           information of the original request. This does NOT lock the threads!"""
        request.msg_id = self.session.get_new_msg_id()

        # First calculate plain_text to encrypt it
        with BinaryWriter() as plain_writer:
            plain_writer.write_long(self.session.salt, signed=False)
            plain_writer.write_long(self.session.id, signed=False)
            plain_writer.write_long(request.msg_id)
            plain_writer.write_int(self.generate_sequence(request.confirmed))
            plain_writer.write_int(len(packet))
            plain_writer.write(packet)

            msg_key = utils.calc_msg_key(plain_writer.get_bytes())

            key, iv = utils.calc_key(self.session.auth_key.key, msg_key, True)
            cipher_text = AES.encrypt_ige(plain_writer.get_bytes(), key, iv)

        # And then finally send the encrypted packet
        with BinaryWriter() as cipher_writer:
            cipher_writer.write_long(self.session.auth_key.key_id, signed=False)
            cipher_writer.write(msg_key)
            cipher_writer.write(cipher_text)
            self.transport.send(cipher_writer.get_bytes())
github LonamiWebs / Telethon / telethon / tl / custom / conversation.py View on Github external
used outside of a context manager, and it needs to resolve the chat.
        """
        chat_id = await self._client.get_peer_id(self._input_chat)
        for conv in self._client._conversations[chat_id]:
            conv.cancel()

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        chat_id = utils.get_peer_id(self._chat_peer)
        conv_set = self._client._conversations[chat_id]
        conv_set.discard(self)
        if not conv_set:
            del self._client._conversations[chat_id]

        self._cancel_all()

    __enter__ = helpers._sync_enter
    __exit__ = helpers._sync_exit
github LonamiWebs / Telethon / telethon / client / downloads.py View on Github external
def _download_cached_photo_size(self: 'TelegramClient', size, file):
        # No need to download anything, simply write the bytes
        if isinstance(size, types.PhotoStrippedSize):
            data = utils.stripped_photo_to_jpg(size.bytes)
        else:
            data = size.bytes

        if file is bytes:
            return data
        elif isinstance(file, str):
            helpers.ensure_parent_dir_exists(file)
            f = open(file, 'wb')
        else:
            f = file

        try:
            f.write(data)
        finally:
            if isinstance(file, str):
                f.close()
        return file
github LonamiWebs / Telethon / telethon / tl / custom / conversation.py View on Github external
"""
        chat_id = await self._client.get_peer_id(self._input_chat)
        for conv in self._client._conversations[chat_id]:
            conv.cancel()

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        chat_id = utils.get_peer_id(self._chat_peer)
        conv_set = self._client._conversations[chat_id]
        conv_set.discard(self)
        if not conv_set:
            del self._client._conversations[chat_id]

        self._cancel_all()

    __enter__ = helpers._sync_enter
    __exit__ = helpers._sync_exit
github LonamiWebs / Telethon / telethon / client / downloads.py View on Github external
return None

        file = self._get_proper_filename(
            file, 'profile_photo', '.jpg',
            possible_names=possible_names
        )

        try:
            result = await self.download_file(loc, file, dc_id=dc_id)
            return result if file is bytes else file
        except errors.LocationInvalidError:
            # See issue #500, Android app fails as of v4.6.0 (1155).
            # The fix seems to be using the full channel chat photo.
            ie = await self.get_input_entity(entity)
            ty = helpers._entity_type(ie)
            if ty == helpers._EntityType.CHANNEL:
                full = await self(functions.channels.GetFullChannelRequest(ie))
                return await self._download_photo(
                    full.full_chat.chat_photo, file,
                    date=None, progress_callback=None,
                    thumb=thumb
                )
            else:
                # Until there's a report for chats, no need to.
                return None
github LonamiWebs / Telethon / telethon / network / mtprotosender.py View on Github external
self._log.info('Disconnecting from %s...', self._connection)
        self._user_connected = False
        try:
            self._log.debug('Closing current connection...')
            await self._connection.disconnect()
        finally:
            self._log.debug('Cancelling %d pending message(s)...', len(self._pending_state))
            for state in self._pending_state.values():
                if error and not state.future.done():
                    state.future.set_exception(error)
                else:
                    state.future.cancel()

            self._pending_state.clear()
            await helpers._cancel(
                self._log,
                send_loop_handle=self._send_loop_handle,
                recv_loop_handle=self._recv_loop_handle
            )

            self._log.info('Disconnection from %s complete!', self._connection)
            self._connection = None

        if self._disconnected and not self._disconnected.done():
            if error:
                self._disconnected.set_exception(error)
            else:
                self._disconnected.set_result(None)