2
0
mirror of https://github.com/pyrogram/pyrogram synced 2025-09-05 08:45:13 +00:00

Docs revamp. Part 3

This commit is contained in:
Dan
2019-05-12 19:26:55 +02:00
parent f7cdc7ac3c
commit eadda551c6
25 changed files with 235 additions and 109 deletions

View File

@@ -1,11 +0,0 @@
Changelog
=========
Currently, all Pyrogram release notes live inside the GitHub repository web page:
https://github.com/pyrogram/pyrogram/releases
(You will be automatically redirected in 10 seconds.)
.. raw:: html
<meta http-equiv="refresh" content="10; URL=https://github.com/pyrogram/pyrogram/releases"/>

View File

@@ -1,59 +0,0 @@
Error Handling
==============
Errors are inevitable when working with the API, and they must be correctly handled with ``try..except`` blocks.
There are many errors that Telegram could return, but they all fall in one of these categories
(which are in turn children of the :obj:`RPCError <pyrogram.RPCError>` superclass):
- :obj:`303 - See Other <pyrogram.errors.SeeOther>`
- :obj:`400 - Bad Request <pyrogram.errors.BadRequest>`
- :obj:`401 - Unauthorized <pyrogram.errors.Unauthorized>`
- :obj:`403 - Forbidden <pyrogram.errors.Forbidden>`
- :obj:`406 - Not Acceptable <pyrogram.errors.NotAcceptable>`
- :obj:`420 - Flood <pyrogram.errors.Flood>`
- :obj:`500 - Internal Server Error <pyrogram.errors.InternalServerError>`
As stated above, there are really many (too many) errors, and in case Pyrogram does not know anything yet about a
specific one, it raises a special :obj:`520 Unknown Error <pyrogram.errors.UnknownError>` exception and logs it
in the ``unknown_errors.txt`` file. Users are invited to report these unknown errors; in later versions of Pyrogram
some kind of automatic error reporting module might be implemented.
Examples
--------
.. code-block:: python
from pyrogram.errors import (
BadRequest, Flood, InternalServerError,
SeeOther, Unauthorized, UnknownError
)
try:
...
except BadRequest:
pass
except Flood:
pass
except InternalServerError:
pass
except SeeOther:
pass
except Unauthorized:
pass
except UnknownError:
pass
Exception objects may also contain some informative values.
E.g.: :obj:`FloodWait <pyrogram.errors.exceptions.flood_420.FloodWait>` holds the amount of seconds you have to wait
before you can try again. The value is always stored in the ``x`` field of the returned exception object:
.. code-block:: python
import time
from pyrogram.errors import FloodWait
try:
...
except FloodWait as e:
time.sleep(e.x)

107
docs/source/topics/faq.rst Normal file
View File

@@ -0,0 +1,107 @@
Pyrogram FAQ
============
This FAQ page provides answers to common questions about Pyrogram and, to some extent, Telegram in general.
.. contents:: Contents
:backlinks: none
:local:
What is Pyrogram?
-----------------
**Pyrogram** is an elegant, easy-to-use Telegram_ client library and framework written from the ground up in Python and
C. It enables you to easily create custom applications using both user and bot identities (bot API alternative) via the
`MTProto API`_ with the Python programming language.
.. _Telegram: https://telegram.org
.. _MTProto API: https://core.telegram.org/api#telegram-api
What does "Pyrogram" mean?
--------------------------
The word "Pyrogram" is composed by **pyro**, which comes from the Greek word *πῦρ (pyr)*, meaning fire, and **gram**,
from *Telegram*. The word *pyro* itself is built from *Python*, **py** for short, and the suffix **ro** to come up with
the word *fire*, which also inspired the project logo.
How old is Pyrogram?
--------------------
Pyrogram was first released on December 12, 2017. The actual work on the framework began roughly three months prior the
initial public release on `GitHub`_.
.. _GitHub: <https://github.com/pyrogram/pyrogram>
Why do I need an API key for bots?
----------------------------------
Requests against the official bot API endpoint are made via JSON/HTTP, but are handled by a backend application that
implements the MTProto protocol -- just like Pyrogram -- and uses its own API key, which is always required, but hidden
to the public.
.. figure:: https://i.imgur.com/C108qkX.png
:align: center
Using MTProto is the only way to communicate with the actual Telegram servers, and the main API requires developers to
identify applications by means of a unique key; the bot token identifies a bot as a user and replaces the user's phone
number only.
I started a client but nothing happens!
---------------------------------------
If you are connecting from Russia, China or Iran `you need a proxy`_, because Telegram could be partially or
totally blocked in those countries.
Another possible cause might be network issues, either yours or Telegram's. To confirm this, add the following code on
the top of your script and run it again. You should see some error mentioning a socket timeout or an unreachable network
in a bunch of seconds:
.. code-block:: python
import logging
logging.basicConfig(level=logging.INFO)
|bug report|
.. _you need a proxy: proxy
I keep getting [400 PEER_ID_INVALID] error!
-------------------------------------------
The error in question is ``[400 PEER_ID_INVALID]: The id/access_hash combination is invalid``, and could mean several
things:
- The chat id you tried to use is simply wrong, double check it.
- The chat id refers to a group or channel you are not a member of.
- The chat id refers to a user you have't seen yet (from contacts, groups in common, forwarded messages or private
chats).
|bug report|
.. |bug report| replace::
**Note:** If you really believe this should not happen, kindly open a `Bug Report`_.
.. _Bug Report: https://github.com/pyrogram/pyrogram/issues/new?labels=bug&template=bug_report.md
My account has been deactivated/limited!
----------------------------------------
First of all, you should understand that Telegram wants to be a safe place for people to stay in, and to pursue this
goal there are automatic protection systems running to prevent flood and spam, as well as a moderation team of humans
who reviews reports.
**Pyrogram is a tool at your commands; it only does what you tell it to do, the rest is up to you.**
Having said that, here's how a list of what Telegram definitely doesn't like:
- Flood, abusing the API.
- Spam, sending unsolicited messages or adding people to unwanted groups and channels.
- Virtual/VoIP and cheap real numbers, because they are relatively easy to get and likely used for spam/flood.
However, you might be right, and your account was deactivated/limited without any reason. This could happen because of
mistakes by either the automatic systems or a moderator. In such cases you can kindly email Telegram at
recover@telegram.org, contact `@smstelegram`_ on Twitter or use `this form`_.
.. _@smstelegram: https://twitter.com/smstelegram
.. _this form: https://telegram.org/support

View File

@@ -0,0 +1,13 @@
Release Notes
=============
Release notes for Pyrogram releases will describe what's new in each version, and will also make you aware of any
backwards-incompatible changes made in that version.
When upgrading to a new version of Pyrogram, you will need to check all the breaking changes in order to find
incompatible code in your application, but also to take advantage of new features and improvements.
.. note::
Currently, all Pyrogram release notes live inside the GitHub repository web page:
https://github.com/pyrogram/pyrogram/releases.

View File

@@ -1,5 +1,5 @@
Customize Sessions
==================
Session Settings
================
As you may probably know, Telegram allows users (and bots) having more than one session (authorizations) registered
in the system at the same time.
@@ -8,7 +8,6 @@ Briefly explaining, sessions are simply new logins in your account. They can be
app (or by invoking `GetAuthorizations <../functions/account/GetAuthorizations.html>`_ with Pyrogram). They store some
useful information such as the client who's using them and from which country and IP address.
.. figure:: https://i.imgur.com/lzGPCdZ.png
:width: 70%
:align: center

View File

@@ -11,7 +11,7 @@ Beside bold, italic, and pre-formatted code, **Pyrogram does also support inline
Markdown Style
--------------
To use this mode, pass :obj:`MARKDOWN <pyrogram.ParseMode.MARKDOWN>` or "markdown" in the *parse_mode* field when using
To use this mode, pass "markdown" in the *parse_mode* field when using
:obj:`send_message() <pyrogram.Client.send_message>`. Use the following syntax in your message:
.. code-block:: text
@@ -34,8 +34,8 @@ To use this mode, pass :obj:`MARKDOWN <pyrogram.ParseMode.MARKDOWN>` or "markdow
HTML Style
----------
To use this mode, pass :obj:`HTML <pyrogram.ParseMode.HTML>` or "html" in the *parse_mode* field when using
:obj:`send_message() <pyrogram.Client.send_message>`. The following tags are currently supported:
To use this mode, pass "html" in the *parse_mode* field when using :obj:`send_message() <pyrogram.Client.send_message>`.
The following tags are currently supported:
.. code-block:: text

View File

@@ -1,109 +0,0 @@
Update Handling
===============
Calling `API methods`_ sequentially is cool, but how to react when, for example, a new message arrives? This page deals
with updates and how to handle them in Pyrogram. Let's have a look at how they work.
First, let's define what are these updates. Updates are simply events that happen in your Telegram account (incoming
messages, new members join, button presses, etc...), which are meant to notify you about a new specific state that
changed. These updates are handled by registering one or more callback functions in your app using
`Handlers <../pyrogram/Handlers.html>`_.
Each handler deals with a specific event and once a matching update arrives from Telegram, your registered callback
function will be called and its body executed.
Registering an Handler
----------------------
To explain how handlers work let's have a look at the most used one, the
:obj:`MessageHandler <pyrogram.MessageHandler>`, which will be in charge for handling :obj:`Message <pyrogram.Message>`
updates coming from all around your chats. Every other handler shares the same setup logic; you should not have troubles
settings them up once you learn from this section.
Using add_handler()
-------------------
The :meth:`add_handler() <pyrogram.Client.add_handler>` method takes any handler instance that wraps around your defined
callback function and registers it in your Client. Here's a full example that prints out the content of a message as
soon as it arrives:
.. code-block:: python
from pyrogram import Client, MessageHandler
def my_function(client, message):
print(message)
app = Client("my_account")
my_handler = MessageHandler(my_function)
app.add_handler(my_handler)
app.run()
Let's examine these four new pieces. First one: a callback function we defined which accepts two arguments -
*(client, message)*. This will be the function that gets executed every time a new message arrives and Pyrogram will
call that function by passing the client instance and the new message instance as argument.
.. code-block:: python
def my_function(client, message):
print(message)
Second one: the :obj:`MessageHandler <pyrogram.MessageHandler>`. This object tells Pyrogram the function we defined
above must only handle updates that are in form of a :obj:`Message <pyrogram.Message>`:
.. code-block:: python
my_handler = MessageHandler(my_function)
Third: the method :meth:`add_handler() <pyrogram.Client.add_handler>`. This method is used to actually register the
handler and let Pyrogram know it needs to be taken into consideration when new updates arrive and the dispatching phase
begins.
.. code-block:: python
app.add_handler(my_handler)
Last one, the :meth:`run() <pyrogram.Client.run>` method. What this does is simply calling
:meth:`start() <pyrogram.Client.start>` and a special method :meth:`idle() <pyrogram.Client.idle>` that keeps your main
scripts alive until you press ``CTRL+C``; the client will be automatically stopped after that.
.. code-block:: python
app.run()
Using Decorators
----------------
All of the above will become quite verbose, especially in case you have lots of handlers to register. A much nicer way
to do so is by decorating your callback function with the :meth:`on_message() <pyrogram.Client.on_message>` decorator.
.. code-block:: python
from pyrogram import Client
app = Client("my_account")
@app.on_message()
def my_handler(client, message):
print(message)
app.run()
.. note::
Due to how these decorators work in Pyrogram, they will wrap your defined callback function in a tuple consisting of
``(handler, group)``; this will be the value held by your function identifier (e.g.: *my_function* from the example
above).
In case, for some reason, you want to get your own function back after it has been decorated, you need to access
``my_function[0].callback``, that is, the *callback* field of the *handler* object which is the first element in the
tuple, accessed by bracket notation *[0]*.
.. _API methods: usage.html

View File

@@ -1,85 +0,0 @@
API Usage
=========
At this point, we have successfully `installed Pyrogram`_ and authorized_ our account and we are now pointing towards
the core of the library. It's time to start playing with the API!
Make API Method Calls
---------------------
Making API method calls with Pyrogram is very simple.
Here's an example we are going to examine:
.. code-block:: python
from pyrogram import Client
app = Client("my_account")
app.start()
print(app.get_me())
app.send_message("me", "Hi, it's me!")
app.send_location("me", 51.500729, -0.124583)
app.send_sticker("me", "CAADBAADyg4AAvLQYAEYD4F7vcZ43AI")
app.stop()
Let's begin by importing the Client class from the Pyrogram package:
.. code-block:: python
from pyrogram import Client
Now instantiate a new Client object, "my_account" is a session name of your choice:
.. code-block:: python
app = Client("my_account")
To actually make use of any method, the client has to be started:
.. code-block:: python
app.start()
Now, you can call any method you like:
.. code-block:: python
print(app.get_me()) # Print information about yourself
# Send messages to yourself:
app.send_message("me", "Hi!") # Text message
app.send_location("me", 51.500729, -0.124583) # Location
app.send_sticker("me", "CAADBAADyg4AAvLQYAEYD4F7vcZ43AI") # Sticker
Finally, when done, simply stop the client:
.. code-block:: python
app.stop()
Context Manager
---------------
You can also use Pyrogram's Client in a context manager with the ``with`` statement. The client will automatically
:meth:`start <pyrogram.Client.start>` and :meth:`stop <pyrogram.Client.stop>` gracefully, even in case of unhandled
exceptions in your code. The example above can be therefore rewritten in a much nicer way, this way:
.. code-block:: python
from pyrogram import Client
app = Client("my_account")
with app:
print(app.get_me())
app.send_message("me", "Hi there! I'm using **Pyrogram**")
app.send_location("me", 51.500729, -0.124583)
app.send_sticker("me", "CAADBAADyg4AAvLQYAEYD4F7vcZ43AI")
More examples can be found on `GitHub <https://github.com/pyrogram/pyrogram/tree/develop/examples>`_.
.. _installed Pyrogram: ../intro/install.html
.. _authorized: ../intro/setup.html