Quick-Start¶
Let’s see a longer example to learn some of the methods that the library has to offer. These are known as “friendly methods”, and you should always use these if possible.
from telethon import TelegramClient # Remember to use your own values from my.telegram.org! api_id = 12345 api_hash = '0123456789abcdef0123456789abcdef' client = TelegramClient('anon', api_id, api_hash) async def main(): # Getting information about yourself me = await client.get_me() # "me" is a user object. You can pretty-print # any Telegram object with the "stringify" method: print(me.stringify()) # When you print something, you see a representation of it. # You can access all attributes of Telegram objects with # the dot operator. For example, to get the username: username = me.username print(username) print(me.phone) # You can print all the dialogs/conversations that you are part of: async for dialog in client.iter_dialogs(): print(dialog.name, 'has ID', dialog.id) # You can send messages to yourself. await client.send_message('me', 'Hello, myself!') # . to some chat ID await client.send_message(-100123456, 'Hello, group!') # . to your contacts await client.send_message('+34600123123', 'Hello, friend!') # . or even to any username await client.send_message('username', 'Testing Telethon!') # You can, of course, use markdown in your messages: message = await client.send_message( 'me', 'This message has **bold**, `code`, __italics__ and ' 'a [nice website](https://example.com)!', link_preview=False ) # Sending a message returns the sent message object, which you can use print(message.raw_text) # You can reply to messages directly if you have a message object await message.reply('Cool!') # Or send files, songs, documents, albums. await client.send_file('me', '/home/me/Pictures/holidays.jpg') # You can print the message history of any chat: async for message in client.iter_messages('me'): print(message.id, message.text) # You can download media from messages, too! # The method will return the path where the file was saved. if message.photo: path = await message.download_media() print('File saved to', path) # printed after download is done with client: client.loop.run_until_complete(main())
Here, we show how to sign in, get information about yourself, send messages, files, getting chats, printing messages, and downloading files.
You should make sure that you understand what the code shown here does, take note on how methods are called and used and so on before proceeding. We will see all the available methods later on.
Note that Telethon is an asynchronous library, and as such, you should get used to it and learn a bit of basic asyncio . This will help a lot. As a quick start, this means you generally want to write all your code inside some async def like so:
client = . async def do_something(me): . async def main(): # Most of your code should go here. # You can of course make and use your own async def (do_something). # They only need to be async if they need to await things. me = await client.get_me() await do_something(me) with client: client.loop.run_until_complete(main())
After you understand this, you may use the telethon.sync hack if you want do so (see Compatibility and Convenience ), but note you may run into other issues (iPython, Anaconda, etc. have some issues with it).
© Copyright 2017 — 2019, Lonami Revision 6e7423e8 .
Versions stable Downloads pdf html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.
Client Reference¶
This page contains a summary of all the important methods and properties that you may need when using Telethon. They are sorted by relevance and are not in alphabetical order.
You should use this page to learn about which methods are available, and if you need a usage example or further description of the arguments, be sure to follow the links.
TelegramClient¶
This is a summary of the methods and properties you will find at TelegramClient .
Auth¶
start | Starts the client (connects and logs in if necessary). |
send_code_request | Sends the Telegram code needed to login to the given phone number. |
sign_in | Logs in to Telegram to an existing user or bot account. |
qr_login | Initiates the QR login procedure. |
log_out | Logs out Telegram and deletes the current *.session file. |
edit_2fa | Changes the 2FA settings of the logged in user. |
Base¶
connect | Connects to Telegram. |
disconnect | Disconnects from Telegram. |
is_connected | Returns True if the user has connected. |
disconnected | Property with a Future that resolves upon disconnection. |
loop | Property with the asyncio event loop used by this client. |
set_proxy | Changes the proxy which will be used on next (re)connection. |
Messages¶
send_message | Sends a message to the specified user, chat or channel. |
edit_message | Edits the given message to change its text or media. |
delete_messages | Deletes the given messages, optionally “for everyone”. |
forward_messages | Forwards the given messages to the specified entity. |
iter_messages | Iterator over the messages for the given chat. |
get_messages | Same as iter_messages() , but returns a TotalList instead. |
pin_message | Pins a message in a chat. |
unpin_message | Unpins a message in a chat. |
send_read_acknowledge | Marks messages as read and optionally clears mentions. |
Uploads¶
send_file | Sends message with the given file to the specified entity. |
upload_file | Uploads a file to Telegram’s servers, without sending it. |
Downloads¶
download_media | Downloads the given media from a message object. |
download_profile_photo | Downloads the profile photo from the given user, chat or channel. |
download_file | Low-level method to download files from their input location. |
iter_download | Iterates over a file download, yielding chunks of the file. |
Dialogs¶
iter_dialogs | Iterator over the dialogs (open conversations/subscribed channels). |
get_dialogs | Same as iter_dialogs() , but returns a TotalList instead. |
edit_folder | Edits the folder used by one or more dialogs to archive them. |
iter_drafts | Iterator over draft messages. |
get_drafts | Same as iter_drafts() , but returns a list instead. |
delete_dialog | Deletes a dialog (leaves a chat or channel). |
conversation | Creates a Conversation with the given entity. |
Users¶
get_me | Gets “me”, the current User who is logged in. |
is_bot | Return True if the signed-in user is a bot, False otherwise. |
is_user_authorized | Returns True if the user is authorized (logged in). |
get_entity | Turns the given entity into a valid Telegram User, Chat or Channel. |
get_input_entity | Turns the given entity into its input entity version. |
get_peer_id | Gets the ID for the given entity. |
Chats¶
iter_participants | Iterator over the participants belonging to the specified chat. |
get_participants | Same as iter_participants() , but returns a TotalList instead. |
kick_participant | Kicks a user from a chat. |
iter_admin_log | Iterator over the admin log for the specified channel. |
get_admin_log | Same as iter_admin_log() , but returns a list instead. |
iter_profile_photos | Iterator over a user’s profile photos or a chat’s photos. |
get_profile_photos | Same as iter_profile_photos() , but returns a TotalList instead. |
edit_admin | Edits admin permissions for someone in a chat. |
edit_permissions | Edits user restrictions in a chat. |
get_permissions | Fetches the permissions of a user in a specific chat or channel or get Default Restricted Rights of Chat or Channel. |
get_stats | Retrieves statistics from the given megagroup or broadcast channel. |
action | Returns a context-manager object to represent a “chat action”. |
Parse Mode¶
Updates¶
on | Decorator used to add_event_handler more conveniently. |
run_until_disconnected | Runs the event loop until the library is disconnected. |
add_event_handler | Registers a new event handler callback. |
remove_event_handler | Inverse operation of add_event_handler() . |
list_event_handlers | Lists all registered event handlers. |
catch_up | “Catches up” on the missed updates while the client was offline. |
set_receive_updates | Change the value of receive_updates . |