-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Home
This wiki page is meant to be a place where everyone can find and contribute examples on how to use Telethon. All examples shown here assume that you've successfully created a client as follows:
from telethon import TelegramClient
# Use your own values here
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
phone_number = '+34600000000'
client = TelegramClient('some_name', api_id, api_hash)
client.connect() # Must return True, otherwise, try again
if not client.is_user_authorized():
client.send_code_request(phone_number)
client.sign_in(phone_number, input('Enter code: '))
# The `client´ is now ready
The online documentation for all available requests, types and constructors is available online at https://lonamiwebs.github.io/Telethon/.
Although Python will probably clean up the resources used by the TelegramClient
, you should always .disconnect()
it once you're done:
client.disconnect()
As a side note, you may often need these lines:
from telethon.utils import xyz
from telethon.helpers import zyx
The first one utils
are only utilities, which are not related per se to the Telegram API. On the other hand, the helpers
are indeed helpers to work with the Telegram API, and to make some tasks less cumbersome.
The most common imports are the following:
from telethon.utils import generate_random_long
from telethon.helpers import get_input_peer
The first one generates a random long, as its name says, and will be called automatically if a Request
has a parameter called random_id
, so you can leave this unspecified.
On the later case, get_input_peer
will convert an entity, such as an User
, a Chat
or a Channel
into its correspondent InputPeer
type to save you from the hassle of writing it manually. You can either call get_input_peer
to save a few isinstance
checks which would otherwise be executed when constructing a Request
, or leave the requests do its work. Note that types requiring an InputPeer
as a parameter will not call this method, so you do have to call it on those cases.
If you ever receive a PEER_FLOOD
error or aren't able to perform certain requests, it might mean that your account is limited, and there's not much Telethon can do about this. Talk to @SpamBot for more information, or refer to the spam FAQ.