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
- 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. Seedecode_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, thumb=None)
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_group_call(call)
Similar to
get_input_peer()
, but for input calls.
- telethon.utils.get_input_location(location)
Similar to
get_input_peer()
, but for input messages.Note that this returns a tuple
(dc_id, location)
, thedc_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, ttl=None)
Similar to
get_input_peer()
, but for media.If the media is InputFile and
is_photo
is known to beTrue
, 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 ifcheck_hash is True
but the entity’saccess_hash is None
or the entity containsmin
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 passinghash = 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_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 ignoringstr/bytes
is not enough. Things likeopen()
are also iterable (and probably many other things), so just support the commonly known list-like objects.
- 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_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 theusername
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 thefile_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_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.
- telethon.utils.resolve_invite_link(link)
Resolves the given invite link. Returns a tuple of
(link creator user id, global chat id, random int)
.Note that for broadcast channels or with the newest link format, 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
andunparse
callable properties.
- telethon.utils.split_text(text, entities, *, limit=4096, max_entities=100, split_at=('\\n', '\\s', '.'))
Split a message text and entities into multiple messages, each with their own set of entities. This allows sending a very large message as multiple messages while respecting the formatting.
- Arguments
- text (
str
): The message text.
- entities (List[MessageEntity])
The formatting entities.
- limit (
int
): The maximum message length of each individual message.
- max_entities (
int
): The maximum amount of entities that will be present in each individual message.
- split_at (Tuplel[
str
]): The list of regular expressions that will determine where to split the text. By default, a newline is searched. If no newline is present, a space is searched. If no space is found, the split will be made at any character.
The last expression should always match a character, or else the text will stop being splitted and the resulting text may be larger than the limit.
- text (
- Yields
Pairs of
(str, entities)
with the split message.- Example
from telethon import utils from telethon.extensions import markdown very_long_markdown_text = "..." text, entities = markdown.parse(very_long_markdown_text) for text, entities in utils.split_text(text, entities): await client.send_message(chat, text, formatting_entities=entities)
- telethon.utils.stripped_photo_to_jpg(stripped)
Adds the JPG header and footer to a stripped image.