Created Accessing the Full API (markdown)

Lonami 2017-09-10 15:10:29 +02:00
parent 784bcf18b7
commit 1440168474

47
Accessing-the-Full-API.md Normal file

@ -0,0 +1,47 @@
The `TelegramClient` doesn't offer a method for every single request the Telegram API supports. However, it's very simple to `.invoke()` any request. Whenever you need something, don't forget to [check the documentation](https://lonamiwebs.github.io/Telethon) and look for the [method you need](https://lonamiwebs.github.io/Telethon/methods/index.html). There you can go through a sorted list of everything you can do.
You should also refer to the documentation to see what the objects (constructors) Telegram returns look like. Every constructor inherits from a common type, and that's the reason for this distinction.
Say `client.send_message()` didn't exist, we could use the [search](https://lonamiwebs.github.io/Telethon/?q=message) to look for "message". There we would find [`SendMessageRequest`](https://lonamiwebs.github.io/Telethon/methods/messages/send_message.html), which we can work with.
Every request is a Python class, and has the parameters needed for you to invoke it. You can also call `help(request)` for information on what input parameters it takes. Remember to "Copy import to the clipboard", or your script won't be aware of this class! Now we have:
```python
from telethon.tl.functions.messages import SendMessageRequest
```
If you're going to use a lot of these, you may do:
```python
import telethon.tl.functions as tl
# We now have access to 'tl.messages.SendMessageRequest'
```
We see that this request must take at least two parameters, a `peer` of type [`InputPeer`](https://lonamiwebs.github.io/Telethon/types/input_peer.html), and a `message` which is just a Python `str`ing.
How can we retrieve this `InputPeer`? We have two options. We manually [construct one](https://lonamiwebs.github.io/Telethon/constructors/input_peer_user.html), for instance:
```python
from telethon.tl.types import InputPeerUser
peer = InputPeerUser(user_id, user_hash)
```
Or we call `.get_entity()`:
```python
peer = client.get_entity('someone')
```
The library will cast the [`User`](https://lonamiwebs.github.io/Telethon/types/user) that `.get_entity()` returns into the appropriated `InputPeer`. If performance is uttermost, you should do this conversion yourself:
```python
from telethon import utils
user = client.get_entity('someone')
peer = utils.get_input_user(user)
```
Now you the library will avoid converting the user into the right type every time you need an `InputPeer`.
Finally, we have everything we need. To `.invoke()` our request we do:
```python
result = client(SendMessageRequest(peer, 'Hello there!'))
# __call__ is an alias for client.invoke(request). Both will work
```
Message sent! Of course, this is only an example. There are over 240 methods available as of layer 71, and you can use every single of them as you wish. Remember to use the right types!