mirror of
https://github.com/LonamiWebs/Telethon.git
synced 2025-08-05 03:22:29 +00:00
Completely overhaul the documentation
This commit is contained in:
77
readthedocs/basic/installation.rst
Normal file
77
readthedocs/basic/installation.rst
Normal file
@@ -0,0 +1,77 @@
|
||||
.. _installation:
|
||||
|
||||
============
|
||||
Installation
|
||||
============
|
||||
|
||||
Telethon is a Python library, which means you need to download and install
|
||||
Python from https://www.python.org/downloads/ if you haven't already. Once
|
||||
you have Python installed, run:
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
pip3 install -U telethon --user
|
||||
|
||||
To install or upgrade the library to the latest version.
|
||||
|
||||
|
||||
Installing Development Versions
|
||||
===============================
|
||||
|
||||
If you want the *latest* unreleased changes,
|
||||
you can run the following command instead:
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
pip3 install -U https://github.com/LonamiWebs/Telethon/archive/master.zip --user
|
||||
|
||||
.. note::
|
||||
|
||||
The development version may have bugs and is not recommended for production
|
||||
use. However, when you are `reporting a library bug`__, you should try if the
|
||||
bug still occurs in this version.
|
||||
|
||||
.. __: https://github.com/LonamiWebs/Telethon/issues/
|
||||
|
||||
|
||||
Verification
|
||||
============
|
||||
|
||||
To verify that the library is installed correctly, run the following command:
|
||||
|
||||
.. code-block:: sh
|
||||
|
||||
python3 -c 'import telethon; print(telethon.__version__)'
|
||||
|
||||
The version number of the library should show in the output.
|
||||
|
||||
|
||||
Optional Dependencies
|
||||
=====================
|
||||
|
||||
If cryptg_ is installed, **the library will work a lot faster**, since
|
||||
encryption and decryption will be made in C instead of Python. If your
|
||||
code deals with a lot of updates or you are downloading/uploading a lot
|
||||
of files, you will notice a considerable speed-up (from a hundred kilobytes
|
||||
per second to several megabytes per second, if your connection allows it).
|
||||
If it's not installed, pyaes_ will be used (which is pure Python, so it's
|
||||
much slower).
|
||||
|
||||
If pillow_ is installed, large images will be automatically resized when
|
||||
sending photos to prevent Telegram from failing with "invalid image".
|
||||
Official clients also do this.
|
||||
|
||||
If aiohttp_ is installed, the library will be able to download
|
||||
:tl:`WebDocument` media files (otherwise you will get an error).
|
||||
|
||||
If hachoir_ is installed, it will be used to extract metadata from files
|
||||
when sending documents. Telegram uses this information to show the song's
|
||||
performer, artist, title, duration, and for videos too (including size).
|
||||
Otherwise, they will default to empty values, and you can set the attributes
|
||||
manually.
|
||||
|
||||
.. _cryptg: https://github.com/Lonami/cryptg
|
||||
.. _pyaes: https://github.com/ricmoo/pyaes
|
||||
.. _pillow: https://python-pillow.org
|
||||
.. _aiohttp: https://docs.aiohttp.org
|
||||
.. _hachoir: https://hachoir.readthedocs.io
|
22
readthedocs/basic/next-steps.rst
Normal file
22
readthedocs/basic/next-steps.rst
Normal file
@@ -0,0 +1,22 @@
|
||||
==========
|
||||
Next Steps
|
||||
==========
|
||||
|
||||
These basic first steps should have gotten you started with the library.
|
||||
|
||||
By now, you should know how to call friendly methods and how to work with
|
||||
the returned objects, how things work inside event handlers, etc.
|
||||
|
||||
Next, we will see a quick reference summary of *all* the methods and
|
||||
properties that you will need when using the library. If you follow
|
||||
the links there, you will expand the documentation for the method
|
||||
and property, with more examples on how to use them.
|
||||
|
||||
Therefore, **you can find an example on every method** of the client
|
||||
to learn how to use it, as well as a description of all the arguments.
|
||||
|
||||
After that, we will go in-depth with some other important concepts
|
||||
that are worth learning and understanding.
|
||||
|
||||
From now on, you can keep pressing the "Next" button if you want,
|
||||
or use the menu on the left, since some pages are quite lengthy.
|
79
readthedocs/basic/quick-start.rst
Normal file
79
readthedocs/basic/quick-start.rst
Normal file
@@ -0,0 +1,79 @@
|
||||
===========
|
||||
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.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from telethon.sync import TelegramClient
|
||||
|
||||
# Remember to use your own values from my.telegram.org!
|
||||
api_id = 12345
|
||||
api_hash = '0123456789abcdef0123456789abcdef'
|
||||
|
||||
with TelegramClient('anon', api_id, api_hash) as client:
|
||||
# Getting information about yourself
|
||||
me = client.get_me()
|
||||
|
||||
# "me" is an 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:
|
||||
for dialog in client.iter_dialogs():
|
||||
print(dialog.name, 'has ID', dialog.id)
|
||||
|
||||
# You can send messages to yourself...
|
||||
client.send_message('me', 'Hello, myself!')
|
||||
# ...to some chat ID
|
||||
client.send_message(-100123456, 'Hello, group!')
|
||||
# ...to your contacts
|
||||
client.send_message('+34600123123', 'Hello, friend!')
|
||||
# ...or even to any username
|
||||
client.send_message('TelethonChat', 'Hello, Telethon!')
|
||||
|
||||
# You can, of course, use markdown in your messages:
|
||||
message = client.send_message(
|
||||
'me',
|
||||
'This message has **bold**, `code`, __italics__ and '
|
||||
'a [nice website](https://lonamiwebs.github.io)!',
|
||||
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
|
||||
message.reply('Cool!')
|
||||
|
||||
# Or send files, songs, documents, albums...
|
||||
client.send_file('me', '/home/me/Pictures/holidays.jpg')
|
||||
|
||||
# You can print the message history of any chat:
|
||||
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 = message.download_media()
|
||||
print('File saved to', path)
|
||||
|
||||
|
||||
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.
|
128
readthedocs/basic/signing-in.rst
Normal file
128
readthedocs/basic/signing-in.rst
Normal file
@@ -0,0 +1,128 @@
|
||||
.. _signing-in:
|
||||
|
||||
==========
|
||||
Signing In
|
||||
==========
|
||||
|
||||
Before working with Telegram's API, you need to get your own API ID and hash:
|
||||
|
||||
1. `Login to your Telegram account <https://my.telegram.org/>`_ with the
|
||||
phone number of the developer account to use.
|
||||
|
||||
2. Click under API Development tools.
|
||||
|
||||
3. A *Create new application* window will appear. Fill in your application
|
||||
details. There is no need to enter any *URL*, and only the first two
|
||||
fields (*App title* and *Short name*) can currently be changed later.
|
||||
|
||||
4. Click on *Create application* at the end. Remember that your
|
||||
**API hash is secret** and Telegram won't let you revoke it.
|
||||
Don't post it anywhere!
|
||||
|
||||
.. note::
|
||||
|
||||
This API ID and hash is the one used by *your application*, not your
|
||||
phone number. You can use this API ID and hash with *any* phone number
|
||||
or even for bot accounts.
|
||||
|
||||
|
||||
Editing the Code
|
||||
================
|
||||
|
||||
This is a little introduction for those new to Python programming in general.
|
||||
|
||||
We will write our code inside ``hello.py``, so you can use any text
|
||||
editor that you like. To run the code, use ``python3 hello.py`` from
|
||||
the terminal.
|
||||
|
||||
.. important::
|
||||
|
||||
Don't call your script ``telethon.py``! Python will try to import
|
||||
the client from there and it will fail with an error such as
|
||||
"ImportError: cannot import name 'TelegramClient' ...".
|
||||
|
||||
|
||||
Signing In
|
||||
==========
|
||||
|
||||
We can finally write some code to log into our account!
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from telethon.sync import TelegramClient
|
||||
|
||||
# Use your own values from my.telegram.org
|
||||
api_id = 12345
|
||||
api_hash = '0123456789abcdef0123456789abcdef'
|
||||
|
||||
# The first parameter is the .session file name (absolute paths allowed)
|
||||
with TelegramClient('anon', api_id, api_hash) as client:
|
||||
client.send_message('me', 'Hello, myself!')
|
||||
|
||||
|
||||
In the first line, we import the class name so we can create an instance
|
||||
of the client. Then, we define variables to store our API ID and hash
|
||||
conveniently.
|
||||
|
||||
At last, we create a new `TelegramClient <telethon.client.telegramclient.TelegramClient>`
|
||||
instance and call it ``client``. We can now use the client variable
|
||||
for anything that we want, such as sending a message to ourselves.
|
||||
|
||||
Using a ``with`` block is the preferred way to use the library. It will
|
||||
automatically `start() <telethon.client.auth.AuthMethods.start>` the client,
|
||||
logging or signing up if necessary.
|
||||
|
||||
If the ``.session`` file already existed, it will not login
|
||||
again, so be aware of this if you move or rename the file!
|
||||
|
||||
|
||||
Signing In as a Bot Account
|
||||
===========================
|
||||
|
||||
You can also use Telethon for your bots (normal bot accounts, not users).
|
||||
You will still need an API ID and hash, but the process is very similar:
|
||||
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from telethon.sync import TelegramClient
|
||||
|
||||
api_id = 12345
|
||||
api_hash = '0123456789abcdef0123456789abcdef'
|
||||
bot_token = '12345:0123456789abcdef0123456789abcdef
|
||||
|
||||
# We have to manually call "start" if we want a explicit bot token
|
||||
bot = TelegramClient('bot', api_id, api_hash).start(bot_token=bot_token)
|
||||
|
||||
# But then we can use the client instance as usual
|
||||
with bot:
|
||||
...
|
||||
|
||||
|
||||
To get a bot account, you need to talk
|
||||
with `@BotFather <https://t.me/BotFather>`_.
|
||||
|
||||
|
||||
Signing In behind a Proxy
|
||||
=========================
|
||||
|
||||
If you need to use a proxy to access Telegram,
|
||||
you will need to `install PySocks`__ and then change:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
TelegramClient('anon', api_id, api_hash)
|
||||
|
||||
with
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
TelegramClient('anon', api_id, api_hash, proxy=(socks.SOCKS5, '127.0.0.1', 4444))
|
||||
|
||||
(of course, replacing the IP and port with the IP and port of the proxye).
|
||||
|
||||
The ``proxy=`` argument should be a tuple, a list or a dict,
|
||||
consisting of parameters described `in PySocks usage`__.
|
||||
|
||||
.. __: https://github.com/Anorov/PySocks#installation
|
||||
.. __: https://github.com/Anorov/PySocks#usage-1
|
161
readthedocs/basic/updates.rst
Normal file
161
readthedocs/basic/updates.rst
Normal file
@@ -0,0 +1,161 @@
|
||||
=======
|
||||
Updates
|
||||
=======
|
||||
|
||||
Updates are an important topic in a messaging platform like Telegram.
|
||||
After all, you want to be notified when a new message arrives, when
|
||||
a member joins, when someone starts typing, etc.
|
||||
For that, you can use **events**.
|
||||
|
||||
.. important::
|
||||
|
||||
It is strongly advised to enable logging when working with events,
|
||||
since exceptions in event handlers are hidden by default. Please
|
||||
add the following snippet to the very top of your file:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import logging
|
||||
logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',
|
||||
level=logging.WARNING)
|
||||
|
||||
|
||||
Getting Started
|
||||
===============
|
||||
|
||||
Let's start things with an example to automate replies:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from telethon import TelegramClient, events
|
||||
|
||||
client = TelegramClient('anon', api_id, api_hash)
|
||||
|
||||
@client.on(events.NewMessage)
|
||||
async def my_event_handler(event):
|
||||
if 'hello' in event.raw_text:
|
||||
await event.reply('hi!')
|
||||
|
||||
client.start()
|
||||
client.run_until_disconnected()
|
||||
|
||||
|
||||
This code isn't much, but there might be some things unclear.
|
||||
Let's break it down:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from telethon import TelegramClient, events
|
||||
|
||||
client = TelegramClient('anon', api_id, api_hash)
|
||||
|
||||
|
||||
This is normal creation (of course, pass session name, API ID and hash).
|
||||
Nothing we don't know already.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@client.on(events.NewMessage)
|
||||
|
||||
|
||||
This Python decorator will attach itself to the ``my_event_handler``
|
||||
definition, and basically means that *on* a `NewMessage
|
||||
<telethon.events.newmessage.NewMessage>` *event*,
|
||||
the callback function you're about to define will be called:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
async def my_event_handler(event):
|
||||
if 'hello' in event.raw_text:
|
||||
await event.reply('hi!')
|
||||
|
||||
|
||||
If a `NewMessage
|
||||
<telethon.events.newmessage.NewMessage>` event occurs,
|
||||
and ``'hello'`` is in the text of the message, we `reply()
|
||||
<telethon.tl.custom.message.Message.reply>` to the event
|
||||
with a ``'hi!'`` message.
|
||||
|
||||
.. note::
|
||||
|
||||
Event handlers **must** be ``async def``. After all,
|
||||
Telethon is an asynchronous library based on asyncio_,
|
||||
which is a safer and often faster approach to threads.
|
||||
|
||||
You **must** ``await`` all method calls that use
|
||||
network requests, which is most of them.
|
||||
|
||||
|
||||
More Examples
|
||||
=============
|
||||
|
||||
Replying to messages with hello is fun, but, can we do more?
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@client.on(events.NewMessage(outgoing=True, pattern=r'\.save'))
|
||||
async def handler(event):
|
||||
if event.is_reply:
|
||||
replied = await event.get_reply_message()
|
||||
sender = replied.sender
|
||||
await client.download_profile_photo(sender)
|
||||
await event.respond('Saved your photo {}'.format(sender.username))
|
||||
|
||||
We could also get replies. This event filters outgoing messages
|
||||
(only those that we send will trigger the method), then we filter
|
||||
by the regex ``r'\.save'``, which will match messages starting
|
||||
with ``".save"``.
|
||||
|
||||
Inside the method, we check whether the event is replying to another message
|
||||
or not. If it is, we get the reply message and the sender of that message,
|
||||
and download their profile photo.
|
||||
|
||||
Let's delete messages which contain "heck". We don't allow swearing here.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@client.on(events.NewMessage(pattern=r'(?i).*heck'))
|
||||
async def handler(event):
|
||||
await event.delete()
|
||||
|
||||
|
||||
With the ``r'(?i).*heck'`` regex, we match case-insensitive
|
||||
"heck" anywhere in the message. Regex is very powerful and you
|
||||
can learn more at https://regexone.com/.
|
||||
|
||||
So far, we have only seen the `NewMessage
|
||||
<telethon.events.newmessage.NewMessage>`, but there are many more
|
||||
which will be covered later. This is only a small introduction to updates.
|
||||
|
||||
Entities
|
||||
========
|
||||
|
||||
When you need the user or chat where an event occurred, you **must** use
|
||||
the following methods:
|
||||
|
||||
.. code-block::
|
||||
|
||||
async def handler(event):
|
||||
# Good
|
||||
chat = await event.get_chat()
|
||||
sender = await event.get_sender()
|
||||
chat_id = event.chat_id
|
||||
sender_id = event.sender_id
|
||||
|
||||
# BAD. Don't do this
|
||||
chat = event.chat
|
||||
sender = event.sender
|
||||
chat_id = event.chat.id
|
||||
sender_id = event.sender.id
|
||||
|
||||
Events are like messages, but don't have all the information a message has!
|
||||
When you manually get a message, it will have all the information it needs.
|
||||
When you receive an update about a message, it **won't** have all the
|
||||
information, so you have to **use the methods**, not the properties.
|
||||
|
||||
Make sure you understand the code seen here before continuing!
|
||||
As a rule of thumb, remember that new message events behave just
|
||||
like message objects, so you can do with them everything you can
|
||||
do with a message object.
|
||||
|
||||
.. _asyncio: https://docs.python.org/3/library/asyncio.html
|
Reference in New Issue
Block a user