telethon package

telethon.telegram_client module

class telethon.telegram_client.TelegramClient(session, api_id, api_hash, connection_mode=<ConnectionMode.TCP_FULL: 1>, use_ipv6=False, proxy=None, update_workers=None, timeout=datetime.timedelta(0, 10), spawn_read_thread=True, report_errors=True, **kwargs)

Bases: telethon.telegram_bare_client.TelegramBareClient

Initializes the Telegram client with the specified API ID and Hash.

Args:
session (str | telethon.sessions.abstract.Session, None):
The file name of the session file to be used if a string is given (it may be a full path), or the Session instance to be used otherwise. If it’s None, the session will not be saved, and you should call log_out() when you’re done.
api_id (int | str):
The API ID you obtained from https://my.telegram.org.
api_hash (str):
The API ID you obtained from https://my.telegram.org.
connection_mode (ConnectionMode, optional):
The connection mode to be used when creating a new connection to the servers. Defaults to the TCP_FULL mode. This will only affect how messages are sent over the network and how much processing is required before sending them.
use_ipv6 (bool, optional):
Whether to connect to the servers through IPv6 or not. By default this is False as IPv6 support is not too widespread yet.
proxy (tuple | dict, optional):
A tuple consisting of (socks.SOCKS5, 'host', port). See https://github.com/Anorov/PySocks#usage-1 for more.
update_workers (int, optional):
If specified, represents how many extra threads should be spawned to handle incoming updates, and updates will be kept in memory until they are processed. Note that you must set this to at least 0 if you want to be able to process updates through updates.poll().
timeout (int | float | timedelta, optional):
The timeout to be used when receiving responses from the network. Defaults to 5 seconds.
spawn_read_thread (bool, optional):
Whether to use an extra background thread or not. Defaults to True so receiving items from the network happens instantly, as soon as they arrive. Can still be disabled if you want to run the library without any additional thread.
report_errors (bool, optional):
Whether to report RPC errors or not. Defaults to True, see API Status for more information.
Kwargs:

Some extra parameters are required when establishing the first connection. These are are (along with their default values):

device_model     = platform.node()
system_version   = platform.system()
app_version      = TelegramClient.__version__
lang_code        = 'en'
system_lang_code = lang_code
add_event_handler(callback, event=None)

Registers the given callback to be called on the specified event.

Args:
callback (callable):
The callable function accepting one parameter to be used.
event (_EventBuilder | type, optional):

The event builder class or instance to be used, for instance events.NewMessage.

If left unspecified, events.Raw (the Update objects with no further processing) will be passed instead.

add_update_handler(handler)
delete_messages(entity, message_ids, revoke=True)

Deletes a message from a chat, optionally “for everyone”.

Args:
entity (entity):
From who the message will be deleted. This can actually be None for normal chats, but must be present for channels and megagroups.
message_ids (list | int | Message):
The IDs (or ID) or messages to be deleted.
revoke (bool, optional):
Whether the message should be deleted for everyone or not. By default it has the opposite behaviour of official clients, and it will delete the message for everyone. This has no effect on channels or megagroups.
Returns:
The AffectedMessages.
download_file(input_location, file, part_size_kb=None, file_size=None, progress_callback=None)

Downloads the given input location to a file.

Args:
input_location (InputFileLocation):
The file location from which the file will be downloaded.
file (str | file):
The output file path, directory, or stream-like object. If the path exists and is a file, it will be overwritten.
part_size_kb (int, optional):
Chunk size when downloading files. The larger, the less requests will be made (up to 512KB maximum).
file_size (int, optional):
The file size that is about to be downloaded, if known. Only used if progress_callback is specified.
progress_callback (callable, optional):
A callback function accepting two parameters: (downloaded bytes, total). Note that the total is the provided file_size.
download_media(message, file=None, progress_callback=None)

Downloads the given media, or the media from a specified Message.

message (Message | Media):
The media or message containing the media that will be downloaded.
file (str | file, optional):
The output file path, directory, or stream-like object. If the path exists and is a file, it will be overwritten.
progress_callback (callable, optional):
A callback function accepting two parameters: (received bytes, total).
Returns:
None if no media was provided, or if it was Empty. On success the file path is returned since it may differ from the one given.
download_profile_photo(entity, file=None, download_big=True)

Downloads the profile photo of the given entity (user/chat/channel).

Args:
entity (entity):
From who the photo will be downloaded.
file (str | file, optional):
The output file path, directory, or stream-like object. If the path exists and is a file, it will be overwritten.
download_big (bool, optional):
Whether to use the big version of the available photos.
Returns:
None if no photo was provided, or if it was Empty. On success the file path is returned since it may differ from the one given.
edit_2fa(current_password=None, new_password=None, hint='', email=None)

Changes the 2FA settings of the logged in user, according to the passed parameters. Take note of the parameter explanations.

Has no effect if both current and new password are omitted.

current_password (str, optional):
The current password, to authorize changing to new_password. Must be set if changing existing 2FA settings. Must not be set if 2FA is currently disabled. Passing this by itself will remove 2FA (if correct).
new_password (str, optional):
The password to set as 2FA. If 2FA was already enabled, current_password must be set. Leaving this blank or None will remove the password.
hint (str, optional):
Hint to be displayed by Telegram when it asks for 2FA. Leaving unspecified is highly discouraged. Has no effect if new_password is not set.
email (str, optional):
Recovery and verification email. Raises EmailUnconfirmedError if value differs from current one, and has no effect if new_password is not set.
Returns:
True if successful, False otherwise.
edit_message(entity, message_id, message=None, parse_mode='md', link_preview=True)

Edits the given message ID (to change its contents or disable preview).

Args:
entity (entity):
From which chat to edit the message.
message_id (str):
The ID of the message (or Message itself) to be edited.
message (str, optional):
The new text of the message.
parse_mode (str, optional):
Can be ‘md’ or ‘markdown’ for markdown-like parsing (default), or ‘htm’ or ‘html’ for HTML-like parsing. If None or any other false-y value is provided, the message will be sent with no formatting.
link_preview (bool, optional):
Should the link preview be shown?
Raises:

MessageAuthorRequiredError if you’re not the author of the message but try editing it anyway.

MessageNotModifiedError if the contents of the message were not modified at all.

Returns:
The edited Message.
forward_messages(entity, messages, from_peer=None)

Forwards the given message(s) to the specified entity.

Args:
entity (entity):
To which entity the message(s) will be forwarded.
messages (list | int | Message):
The message(s) to forward, or their integer IDs.
from_peer (entity):
If the given messages are integer IDs and not instances of the Message class, this must be specified in order for the forward to work.
Returns:
The list of forwarded Message, or a single one if a list wasn’t provided as input.
get_dialogs(*args, **kwargs)

Same as iter_dialogs(), but returns a list instead with an additional .total attribute on the list.

get_drafts()

Same as iter_drafts(), but returns a list instead.

get_entity(entity)

Turns the given entity into a valid Telegram user or chat.

entity (str | int | Peer | InputPeer):

The entity (or iterable of entities) to be transformed. If it’s a string which can be converted to an integer or starts with ‘+’ it will be resolved as if it were a phone number.

If it doesn’t start with ‘+’ or starts with a ‘@’ it will be be resolved from the username. If no exact match is returned, an error will be raised.

If the entity is an integer or a Peer, its information will be returned through a call to self.get_input_peer(entity).

If the entity is neither, and it’s not a TLObject, an error will be raised.

Returns:
User, Chat or Channel corresponding to the input entity. A list will be returned if more than one was given.
get_input_entity(peer)

Turns the given peer into its input entity version. Most requests use this kind of InputUser, InputChat and so on, so this is the most suitable call to make for those cases.

entity (str | int | Peer | InputPeer):

The integer ID of an user or otherwise either of a PeerUser, PeerChat or PeerChannel, for which to get its Input* version.

If this Peer hasn’t been seen before by the library, the top dialogs will be loaded and their entities saved to the session file (unless this feature was disabled explicitly).

If in the end the access hash required for the peer was not found, a ValueError will be raised.

Returns:
InputPeerUser, InputPeerChat or InputPeerChannel.
get_me(input_peer=False)

Gets “me” (the self user) which is currently authenticated, or None if the request fails (hence, not authenticated).

Args:
input_peer (bool, optional):
Whether to return the InputPeerUser version or the normal User. This can be useful if you just need to know the ID of yourself.
Returns:
Your own User.
get_message_history(*args, **kwargs)
get_messages(*args, **kwargs)

Same as iter_messages(), but returns a list instead with an additional .total attribute on the list.

get_participants(*args, **kwargs)

Same as iter_participants(), but returns a list instead with an additional .total attribute on the list.

iter_dialogs(limit=None, offset_date=None, offset_id=0, offset_peer=<telethon.tl.types.InputPeerEmpty object>, _total=None)

Returns an iterator over the dialogs, yielding ‘limit’ at most. Dialogs are the open “chats” or conversations with other people.

Args:
limit (int | None):
How many dialogs to be retrieved as maximum. Can be set to None to retrieve all dialogs. Note that this may take whole minutes if you have hundreds of dialogs, as Telegram will tell the library to slow down through a FloodWaitError.
offset_date (datetime, optional):
The offset date to be used.
offset_id (int, optional):
The message ID to be used as an offset.
offset_peer (InputPeer, optional):
The peer to be used as an offset.
_total (list, optional):
A single-item list to pass the total parameter by reference.
Yields:
Instances of telethon.tl.custom.dialog.Dialog.
iter_drafts()

Iterator over all open draft messages.

Instances of telethon.tl.custom.draft.Draft are yielded. You can call telethon.tl.custom.draft.Draft.set_message to change the message or telethon.tl.custom.draft.Draft.delete among other things.

iter_messages(entity, limit=20, offset_date=None, offset_id=0, max_id=0, min_id=0, add_offset=0, batch_size=100, wait_time=None, _total=None)

Iterator over the message history for the specified entity.

Args:
entity (entity):
The entity from whom to retrieve the message history.
limit (int | None, optional):
Number of messages to be retrieved. Due to limitations with the API retrieving more than 3000 messages will take longer than half a minute (or even more based on previous calls). The limit may also be None, which would eventually return the whole history.
offset_date (datetime):
Offset date (messages previous to this date will be retrieved). Exclusive.
offset_id (int):
Offset message ID (only messages previous to the given ID will be retrieved). Exclusive.
max_id (int):
All the messages with a higher (newer) ID or equal to this will be excluded
min_id (int):
All the messages with a lower (older) ID or equal to this will be excluded.
add_offset (int):
Additional message offset (all of the specified offsets + this offset = older messages).
batch_size (int):
Messages will be returned in chunks of this size (100 is the maximum). While it makes no sense to modify this value, you are still free to do so.
wait_time (int):
Wait time between different GetHistoryRequest. Use this parameter to avoid hitting the FloodWaitError as needed. If left to None, it will default to 1 second only if the limit is higher than 3000.
_total (list, optional):
A single-item list to pass the total parameter by reference.
Yields:

Instances of Message with extra attributes:

  • .sender = entity of the sender.
  • .fwd_from.sender = if fwd_from, who sent it originally.
  • .fwd_from.channel = if fwd_from, original channel.
  • .to = entity to which the message was sent.
Notes:
Telegram’s flood wait limit for GetHistoryRequest seems to be around 30 seconds per 3000 messages, therefore a sleep of 1 second is the default for this limit (or above). You may need an higher limit, so you’re free to set the batch_size that you think may be good.
iter_participants(entity, limit=None, search='', filter=None, aggressive=False, _total=None)

Iterator over the participants belonging to the specified chat.

Args:
entity (entity):
The entity from which to retrieve the participants list.
limit (int):
Limits amount of participants fetched.
search (str, optional):
Look for participants with this string in name/username.
filter (ChannelParticipantsFilter, optional):
The filter to be used, if you want e.g. only admins Note that you might not have permissions for some filter. This has no effect for normal chats or users.
aggressive (bool, optional):

Aggressively looks for all participants in the chat in order to get more than 10,000 members (a hard limit imposed by Telegram). Note that this might take a long time (over 5 minutes), but is able to return over 90,000 participants on groups with 100,000 members.

This has no effect for groups or channels with less than 10,000 members, or if a filter is given.

_total (list, optional):
A single-item list to pass the total parameter by reference.
Yields:
The User objects returned by GetParticipantsRequest with an additional .participant attribute which is the matched ChannelParticipant type for channels/megagroups or ChatParticipants for normal chats.
list_event_handlers()

Lists all added event handlers, returning a list of pairs consisting of (callback, event).

list_update_handlers()
log_out()

Logs out Telegram and deletes the current *.session file.

Returns:
True if the operation was successful.
on(event)

Decorator helper method around add_event_handler().

Args:
event (_EventBuilder | type):
The event builder class or instance to be used, for instance events.NewMessage.
remove_event_handler(callback, event=None)

Inverse operation of add_event_handler().

If no event is given, all events for this callback are removed. Returns how many callbacks were removed.

remove_update_handler(handler)
send_code_request(phone, force_sms=False)

Sends a code request to the specified phone number.

Args:
phone (str | int):
The phone to which the code will be sent.
force_sms (bool, optional):
Whether to force sending as SMS.
Returns:
An instance of SentCode.
send_file(entity, file, caption='', force_document=False, progress_callback=None, reply_to=None, attributes=None, thumb=None, allow_cache=True, parse_mode='md', **kwargs)

Sends a file to the specified entity.

Args:
entity (entity):
Who will receive the file.
file (str | bytes | file | media):

The path of the file, byte array, or stream that will be sent. Note that if a byte array or a stream is given, a filename or its type won’t be inferred, and it will be sent as an “unnamed application/octet-stream”.

Subsequent calls with the very same file will result in immediate uploads, unless .clear_file_cache() is called.

Furthermore the file may be any media (a message, document, photo or similar) so that it can be resent without the need to download and re-upload it again.

If a list or similar is provided, the files in it will be sent as an album in the order in which they appear, sliced in chunks of 10 if more than 10 are given.

caption (str, optional):
Optional caption for the sent media message.
force_document (bool, optional):
If left to False and the file is a path that ends with the extension of an image file or a video file, it will be sent as such. Otherwise always as a document.
progress_callback (callable, optional):
A callback function accepting two parameters: (sent bytes, total).
reply_to (int | Message):
Same as reply_to from .send_message().
attributes (list, optional):
Optional attributes that override the inferred ones, like DocumentAttributeFilename and so on.
thumb (str | bytes | file, optional):
Optional thumbnail (for videos).
allow_cache (bool, optional):
Whether to allow using the cached version stored in the database or not. Defaults to True to avoid re-uploads. Must be False if you wish to use different attributes or thumb than those that were used when the file was cached.
parse_mode (str, optional):
The parse mode for the caption message.
Kwargs:
If “is_voice_note” in kwargs, despite its value, and the file is sent as a document, it will be sent as a voice note.
Notes:
If the hachoir3 package (hachoir module) is installed, it will be used to determine metadata from audio and video files.
Returns:
The Message (or messages) containing the sent file, or messages if a list of them was passed.
send_message(entity, message='', reply_to=None, parse_mode='md', link_preview=True, file=None, force_document=False, clear_draft=False)

Sends the given message to the specified entity (user/chat/channel).

The default parse mode is the same as the official applications (a custom flavour of markdown). **bold**, `code` or __italic__ are available. In addition you can send [links](https://example.com) and [mentions](@username) (or using IDs like in the Bot API: [mention](tg://user?id=123456789)) and pre blocks with three backticks.

Args:
entity (entity):
To who will it be sent.
message (str | Message):
The message to be sent, or another message object to resend.
reply_to (int | Message, optional):
Whether to reply to a message or not. If an integer is provided, it should be the ID of the message that it should reply to.
parse_mode (str, optional):
Can be ‘md’ or ‘markdown’ for markdown-like parsing (default), or ‘htm’ or ‘html’ for HTML-like parsing. If None or any other false-y value is provided, the message will be sent with no formatting.
link_preview (bool, optional):
Should the link preview be shown?
file (file, optional):
Sends a message with a file attached (e.g. a photo, video, audio or document). The message may be empty.
force_document (bool, optional):
Whether to send the given file as a document or not.
clear_draft (bool, optional):
Whether the existing draft should be cleared or not. Has no effect when sending a file.
Returns:
The sent Message.
send_read_acknowledge(entity, message=None, max_id=None, clear_mentions=False)

Sends a “read acknowledge” (i.e., notifying the given peer that we’ve read their messages, also known as the “double check”).

Args:
entity (entity):
The chat where these messages are located.
message (list | Message):
Either a list of messages or a single message.
max_id (int):
Overrides messages, until which message should the acknowledge should be sent.
clear_mentions (bool):

Whether the mention badge should be cleared (so that there are no more mentions) or not for the given entity.

If no message is provided, this will be the only action taken.

send_voice_note(*args, **kwargs)

Wrapper method around send_file() with is_voice_note=True.

sign_in(phone=None, code=None, password=None, bot_token=None, phone_code_hash=None)

Starts or completes the sign in process with the given phone number or code that Telegram sent.

Args:
phone (str | int):
The phone to send the code to if no code was provided, or to override the phone that was previously used with these requests.
code (str | int):
The code that Telegram sent. Note that if you have sent this code through the application itself it will immediately expire. If you want to send the code, obfuscate it somehow. If you’re not doing any of this you can ignore this note.
password (str):
2FA password, should be used if a previous call raised SessionPasswordNeededError.
bot_token (str):
Used to sign in as a bot. Not all requests will be available. This should be the hash the @BotFather gave you.
phone_code_hash (str):
The hash returned by .send_code_request. This can be set to None to use the last hash known.
Returns:
The signed in user, or the information about send_code_request().
sign_up(code, first_name, last_name='')

Signs up to Telegram if you don’t have an account yet. You must call .send_code_request(phone) first.

Args:
code (str | int):
The code sent by Telegram
first_name (str):
The first name to be used by the new account.
last_name (str, optional)
Optional last name.
Returns:
The new created User.
start(phone=<function TelegramClient.<lambda>>, password=<function TelegramClient.<lambda>>, bot_token=None, force_sms=False, code_callback=None, first_name='New User', last_name='')

Convenience method to interactively connect and sign in if required, also taking into consideration that 2FA may be enabled in the account.

Example usage:
>>> client = TelegramClient(session, api_id, api_hash).start(phone)
Please enter the code you received: 12345
Please enter your password: *******
(You are now logged in)
Args:
phone (str | int | callable):
The phone (or callable without arguments to get it) to which the code will be sent.
password (callable, optional):
The password for 2 Factor Authentication (2FA). This is only required if it is enabled in your account.
bot_token (str):
Bot Token obtained by @BotFather to log in as a bot. Cannot be specified with phone (only one of either allowed).
force_sms (bool, optional):
Whether to force sending the code request as SMS. This only makes sense when signing in with a phone.
code_callback (callable, optional):
A callable that will be used to retrieve the Telegram login code. Defaults to input().
first_name (str, optional):
The first name to be used if signing up. This has no effect if the account already exists and you sign in.
last_name (str, optional):
Similar to the first name, but for the last. Optional.
Returns:
This TelegramClient, so initialization can be chained with .start().
upload_file(file, part_size_kb=None, file_name=None, use_cache=None, progress_callback=None)

Uploads the specified file and returns a handle (an instance of InputFile or InputFileBig, as required) which can be later used before it expires (they are usable during less than a day).

Uploading a file will simply return a “handle” to the file stored remotely in the Telegram servers, which can be later used on. This will not upload the file to your own chat or any chat at all.

Args:
file (str | bytes | file):

The path of the file, byte array, or stream that will be sent. Note that if a byte array or a stream is given, a filename or its type won’t be inferred, and it will be sent as an “unnamed application/octet-stream”.

Subsequent calls with the very same file will result in immediate uploads, unless .clear_file_cache() is called.

part_size_kb (int, optional):
Chunk size when uploading files. The larger, the less requests will be made (up to 512KB maximum).
file_name (str, optional):
The file name which will be used on the resulting InputFile. If not specified, the name will be taken from the file and if this is not a str, it will be "unnamed".
use_cache (type, optional):
The type of cache to use (currently either InputDocument or InputPhoto). If present and the file is small enough to need the MD5, it will be checked against the database, and if a match is found, the upload won’t be made. Instead, an instance of type use_cache will be returned.
progress_callback (callable, optional):
A callback function accepting two parameters: (sent bytes, total).
Returns:
InputFileBig if the file size is larger than 10MB, InputSizedFile (subclass of InputFile) otherwise.

telethon.telegram_bare_client module

class telethon.telegram_bare_client.TelegramBareClient(session, api_id, api_hash, connection_mode=<ConnectionMode.TCP_FULL: 1>, use_ipv6=False, proxy=None, update_workers=None, spawn_read_thread=False, timeout=datetime.timedelta(0, 5), report_errors=True, device_model=None, system_version=None, app_version=None, lang_code='en', system_lang_code='en')

Bases: object

Bare Telegram Client with just the minimum -

The reason to distinguish between a MtProtoSender and a TelegramClient itself is because the sender is just that, a sender, which should know nothing about Telegram but rather how to handle this specific connection.

The TelegramClient itself should know how to initialize a proper connection to the servers, as well as other basic methods such as disconnection and reconnection.

This distinction between a bare client and a full client makes it possible to create clones of the bare version (by using the same session, IP address and port) to be able to execute queries on either, without the additional cost that would involve having the methods for signing in, logging out, and such.

connect(_sync_updates=True)

Connects to the Telegram servers, executing authentication if required. Note that authenticating to the Telegram servers is not the same as authenticating the desired user itself, which may require a call (or several) to ‘sign_in’ for the first time.

Note that the optional parameters are meant for internal use.

If ‘_sync_updates’, sync_updates() will be called and a second thread will be started if necessary. Note that this will FAIL if the client is not connected to the user’s native data center, raising a “UserMigrateError”, and calling .disconnect() in the process.

disconnect()

Disconnects from the Telegram server and stops all the spawned threads

get_input_entity(peer)

Stub method, no functionality so that calling .get_input_entity() from .resolve() doesn’t fail.

idle(stop_signals=(<Signals.SIGINT: 2>, <Signals.SIGTERM: 15>, <Signals.SIGIOT: 6>))

Idles the program by looping forever and listening for updates until one of the signals are received, which breaks the loop.

Parameters:stop_signals – Iterable containing signals from the signal module that will be subscribed to TelegramClient.disconnect() (effectively stopping the idle loop), which will be called on receiving one of those signals.
Returns:
invoke(*requests, retries=5)

Invokes (sends) a MTProtoRequest and returns (receives) its result.

The invoke will be retried up to ‘retries’ times before raising RuntimeError().

is_connected()
is_user_authorized()

Has the user been authorized yet (code request sent and confirmed)?

set_proxy(proxy)

Change the proxy used by the connections.

sync_updates()

Synchronizes self.updates to their initial state. Will be called automatically on connection if self.updates.enabled = True, otherwise it should be called manually after enabling updates.

telethon.utils module

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

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_display_name(entity)

Gets the display name for the given entity, if it’s an 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_input_channel(entity)

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

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_media(media, is_photo=False)

Similar to get_input_peer(), but for media.

If the media is a file location and is_photo is known to be True, it will be treated as an InputMediaUploadedPhoto.

telethon.utils.get_input_peer(entity, allow_self=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.

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.

telethon.utils.get_peer_id(peer)

Finds the ID of the given peer, and converts it to the “bot api” format so it the peer can be identified back. User ID is left unmodified, chat ID is negated, and channel ID is prefixed with -100.

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_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.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 if the username is not valid.

telethon.utils.resolve_id(marked_id)

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

telethon.helpers module

Various helpers not related to the Telegram API itself

telethon.helpers.calc_key(auth_key, msg_key, client)

Calculate the key based on Telegram guidelines for MtProto 2, specifying whether it’s the client or not.

telethon.helpers.ensure_parent_dir_exists(file_path)

Ensures that the parent directory exists

telethon.helpers.generate_key_data_from_nonce(server_nonce, new_nonce)

Generates the key data corresponding to the given nonce

telethon.helpers.generate_random_long(signed=True)

Generates a random long integer (8 bytes), which is optionally signed

telethon.helpers.get_password_hash(pw, current_salt)

Gets the password hash for the two-step verification. current_salt should be the byte array provided by invoking GetPasswordRequest()

telethon.helpers.pack_message(session, message)

Packs a message following MtProto 2.0 guidelines

telethon.helpers.unpack_message(session, reader)

Unpacks a message following MtProto 2.0 guidelines

telethon.events package

telethon.update_state module

class telethon.update_state.UpdateState(workers=None)

Bases: object

Used to hold the current state of processed updates. To retrieve an update, poll() should be called.

WORKER_POLL_TIMEOUT = 5.0
can_poll()

Returns True if a call to .poll() won’t lock

get_workers()
poll(timeout=None)

Polls an update or blocks until an update object is available. If ‘timeout is not None’, it should be a floating point value, and the method will ‘return None’ if waiting times out.

process(update)

Processes an update object. This method is normally called by the library itself.

set_workers(n)

Changes the number of workers running. If ‘n is None’, clears all pending updates from memory.

setup_workers()
stop_workers()

Waits for all the worker threads to stop.

workers

telethon.sessions module

Module contents