Utilities

These are the utilities that the library has to offer.

Utilities for working with the Telegram API itself (such as handy methods to convert between an entity like a User, Chat, etc. into its Input version)

class telethon.utils.AsyncClassWrapper(wrapped)

Bases: object

__getattr__(item)
__weakref__

list of weak references to the object (if defined)

telethon.utils.chunks(iterable, size=100)

Turns the given iterable into chunks of the specified size, which is 100 by default since that’s what Telegram uses the most.

telethon.utils.decode_waveform(waveform)

Inverse operation of encode_waveform.

telethon.utils.encode_waveform(waveform)

Encodes the input bytes into a 5-bit byte-string to be used as a voice note’s waveform. See decode_waveform for the reverse operation.

Example
chat = ...
file = 'my.ogg'

# Send 'my.ogg' with a ascending-triangle waveform
await client.send_file(chat, file, attributes=[types.DocumentAttributeAudio(
    duration=7,
    voice=True,
    waveform=utils.encode_waveform(bytes(range(2 ** 5))  # 2**5 because 5-bit
)]

# Send 'my.ogg' with a square waveform
await client.send_file(chat, file, attributes=[types.DocumentAttributeAudio(
    duration=7,
    voice=True,
    waveform=utils.encode_waveform(bytes((31, 31, 15, 15, 15, 15, 31, 31)) * 4)
)]
telethon.utils.get_appropriated_part_size(file_size)

Gets the appropriated part size when uploading or downloading files, given an initial file size.

telethon.utils.get_attributes(file, *, attributes=None, mime_type=None, force_document=False, voice_note=False, video_note=False, supports_streaming=False)

Get a list of attributes for the given file and the mime type as a tuple ([attribute], mime_type).

telethon.utils.get_display_name(entity)

Gets the display name for the given User, Chat or Channel. Returns an empty string otherwise.

telethon.utils.get_extension(media)

Gets the corresponding extension for any Telegram media.

telethon.utils.get_inner_text(text, entities)

Gets the inner text that’s surrounded by the given entities. For instance: text = ‘hey!’, entity = MessageEntityBold(2, 2) -> ‘y!’.

Parameters:
  • text – the original text.
  • entities – the entity or entities that must be matched.
Returns:

a single result or a list of the text surrounded by the entities.

telethon.utils.get_input_channel(entity)

Similar to get_input_peer(), but for InputChannel’s alone.

Important

This method does not validate for invalid general-purpose access hashes, unlike get_input_peer. Consider using instead: get_input_channel(get_input_peer(channel)).

telethon.utils.get_input_chat_photo(photo)

Similar to get_input_peer(), but for chat photos

telethon.utils.get_input_dialog(dialog)

Similar to get_input_peer(), but for dialogs

telethon.utils.get_input_document(document)

Similar to get_input_peer(), but for documents

telethon.utils.get_input_geo(geo)

Similar to get_input_peer(), but for geo points

telethon.utils.get_input_location(location)

Similar to get_input_peer(), but for input messages.

Note that this returns a tuple (dc_id, location), the dc_id being present if known.

telethon.utils.get_input_media(media, *, is_photo=False, attributes=None, force_document=False, voice_note=False, video_note=False, supports_streaming=False)

Similar to get_input_peer(), but for media.

If the media is InputFile and is_photo is known to be True, it will be treated as an InputMediaUploadedPhoto. Else, the rest of parameters will indicate how to treat it.

telethon.utils.get_input_message(message)

Similar to get_input_peer(), but for input messages.

telethon.utils.get_input_peer(entity, allow_self=True, check_hash=True)

Gets the input peer for the given “entity” (user, chat or channel).

A TypeError is raised if the given entity isn’t a supported type or if check_hash is True but the entity’s access_hash is None or the entity contains min information. In this case, the hash cannot be used for general purposes, and thus is not returned to avoid any issues which can derive from invalid access hashes.

Note that check_hash is ignored if an input peer is already passed since in that case we assume the user knows what they’re doing. This is key to getting entities by explicitly passing hash = 0.

telethon.utils.get_input_photo(photo)

Similar to get_input_peer(), but for photos

telethon.utils.get_input_user(entity)

Similar to get_input_peer(), but for InputUser’s alone.

Important

This method does not validate for invalid general-purpose access hashes, unlike get_input_peer. Consider using instead: get_input_channel(get_input_peer(channel)).

telethon.utils.get_message_id(message)

Similar to get_input_peer(), but for message IDs.

telethon.utils.get_peer(peer)
telethon.utils.get_peer_id(peer, add_mark=True)

Convert the given peer into its marked ID by default.

This “mark” comes from the “bot api” format, and with it the peer type can be identified back. User ID is left unmodified, chat ID is negated, and channel ID is prefixed with -100:

  • user_id
  • -chat_id
  • -100channel_id

The original ID and the peer type class can be returned with a call to resolve_id(marked_id)().

telethon.utils.is_audio(file)

Returns True if the file extension looks like an audio file.

telethon.utils.is_gif(file)

Returns True if the file extension looks like a gif file to Telegram.

telethon.utils.is_image(file)

Returns True if the file extension looks like an image file to Telegram.

telethon.utils.is_list_like(obj)

Returns True if the given object looks like a list.

Checking if hasattr(obj, '__iter__') and ignoring str/bytes is not enough. Things like open() are also iterable (and probably many other things), so just support the commonly known list-like objects.

telethon.utils.is_video(file)

Returns True if the file extension looks like a video file.

telethon.utils.pack_bot_file_id(file)

Inverse operation for resolve_bot_file_id.

The only parameters this method will accept are Document and Photo, and it will return a variable-length file_id string.

If an invalid parameter is given, it will return None.

telethon.utils.parse_phone(phone)

Parses the given phone, or returns None if it’s invalid.

telethon.utils.parse_username(username)

Parses the given username or channel access hash, given a string, username or URL. Returns a tuple consisting of both the stripped, lowercase username and whether it is a joinchat/ hash (in which case is not lowercase’d).

Returns (None, False) if the username or link is not valid.

telethon.utils.resolve_bot_file_id(file_id)

Given a Bot API-style file_id, returns the media it represents. If the file_id is not valid, None is returned instead.

Note that the file_id does not have information such as image dimensions or file size, so these will be zero if present.

For thumbnails, the photo ID and hash will always be zero.

telethon.utils.resolve_id(marked_id)

Given a marked ID, returns the original ID and its Peer type.

telethon.utils.resolve_inline_message_id(inline_msg_id)

Resolves an inline message ID. Returns a tuple of (message id, peer, dc id, access hash)

The peer may either be a PeerUser referencing the user who sent the message via the bot in a private conversation or small group chat, or a PeerChannel if the message was sent in a channel.

The access_hash does not have any use yet.

Resolves the given invite link. Returns a tuple of (link creator user id, global chat id, random int).

Note that for broadcast channels, the link creator user ID will be zero to protect their identity. Normal chats and megagroup channels will have such ID.

Note that the chat ID may not be accurate for chats with a link that were upgraded to megagroup, since the link can remain the same, but the chat ID will be correct once a new link is generated.

telethon.utils.sanitize_parse_mode(mode)

Converts the given parse mode into an object with parse and unparse callable properties.

telethon.utils.stripped_photo_to_jpg(stripped)

Adds the JPG header and footer to a stripped image.

Ported from https://github.com/telegramdesktop/tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225