Docs revamp. Part 4

This commit is contained in:
Dan 2019-05-16 21:28:34 +02:00
parent a5e42572f6
commit 944b672fe5
35 changed files with 402 additions and 279 deletions

View File

@ -1,5 +1,5 @@
{title}
{title_markup}
.. autoclass:: {full_class_path}
.. autoclass:: {full_class_path}()
:members:

View File

@ -0,0 +1,102 @@
Bound Methods
=============
Some Pyrogram types define what are called bound methods. Bound methods are functions attached to a class which are
accessed via an instance of that class. They make it even easier to call specific methods by automatically inferring
some of the required arguments.
.. code-block:: python
:emphasize-lines: 8
from pyrogram import Client
app = Client("my_account")
@app.on_message()
def hello(client, message)
message.reply("hi")
app.run()
.. currentmodule:: pyrogram
- Message_
- CallbackQuery_
- InlineQuery_
.. _Message:
Message
-------
- :meth:`Message.click()`
- :meth:`Message.delete()`
- :meth:`Message.download()`
- :meth:`Message.edit()`
- :meth:`Message.edit_caption()`
- :meth:`Message.edit_media()`
- :meth:`Message.edit_reply_markup()`
- :meth:`Message.forward()`
- :meth:`Message.pin()`
- :meth:`Message.reply()`
- :meth:`Message.reply_animation()`
- :meth:`Message.reply_audio()`
- :meth:`Message.reply_cached_media()`
- :meth:`Message.reply_chat_action()`
- :meth:`Message.reply_contact()`
- :meth:`Message.reply_document()`
- :meth:`Message.reply_game()`
- :meth:`Message.reply_inline_bot_result()`
- :meth:`Message.reply_location()`
- :meth:`Message.reply_media_group()`
- :meth:`Message.reply_photo()`
- :meth:`Message.reply_poll()`
- :meth:`Message.reply_sticker()`
- :meth:`Message.reply_venue()`
- :meth:`Message.reply_video()`
- :meth:`Message.reply_video_note()`
- :meth:`Message.reply_voice()`
.. automethod:: Message.click()
.. automethod:: Message.delete()
.. automethod:: Message.download()
.. automethod:: Message.edit()
.. automethod:: Message.edit_caption()
.. automethod:: Message.edit_media()
.. automethod:: Message.edit_reply_markup()
.. automethod:: Message.forward()
.. automethod:: Message.pin()
.. automethod:: Message.reply()
.. automethod:: Message.reply_animation()
.. automethod:: Message.reply_audio()
.. automethod:: Message.reply_cached_media()
.. automethod:: Message.reply_chat_action()
.. automethod:: Message.reply_contact()
.. automethod:: Message.reply_document()
.. automethod:: Message.reply_game()
.. automethod:: Message.reply_inline_bot_result()
.. automethod:: Message.reply_location()
.. automethod:: Message.reply_media_group()
.. automethod:: Message.reply_photo()
.. automethod:: Message.reply_poll()
.. automethod:: Message.reply_sticker()
.. automethod:: Message.reply_venue()
.. automethod:: Message.reply_video()
.. automethod:: Message.reply_video_note()
.. automethod:: Message.reply_voice()
.. _CallbackQuery:
CallbackQuery
-------------
.. automethod:: CallbackQuery.answer()
.. _InlineQuery:
InlineQuery
-----------
.. automethod:: InlineQuery.answer()

View File

@ -1,7 +1,16 @@
Pyrogram Client
===============
The :class:`Client <pyrogram.Client>` is the main class. It exposes easy-to-use methods that are named
after the well established Telegram Bot API methods, thus offering a familiar look to Bot developers.
This class exposes high-level methods for an easy access to the API.
.. code-block:: python
:emphasize-lines: 1-3
from pyrogram import Client
app = Client("my_account")
with app:
app.send_message("me", "Hi!")
.. autoclass:: pyrogram.Client()

View File

@ -1,7 +1,7 @@
Decorators
==========
While still being methods bound to the :obj:`Client` class, decorators are of a special kind and thus deserve a
While still being methods bound to the :obj:`Client <pyrogram.Client>` class, decorators are of a special kind and thus deserve a
dedicated page.
Decorators are able to register callback functions for handling updates in a much easier and cleaner way compared to
@ -9,13 +9,12 @@ Decorators are able to register callback functions for handling updates in a muc
:meth:`add_handler() <pyrogram.Client.add_handler>`, automatically. All you need to do is adding the decorators on top
of your functions.
**Example:**
.. code-block:: python
:emphasize-lines: 6
from pyrogram import Client
app = Client(...)
app = Client("my_account")
@app.on_message()

View File

@ -5,27 +5,26 @@ All Pyrogram API errors live inside the ``errors`` sub-package: ``pyrogram.error
The errors ids listed here are shown as *UPPER_SNAKE_CASE*, but the actual exception names to import from Pyrogram
follow the usual *PascalCase* convention.
**Example**:
.. code-block:: python
:emphasize-lines: 1, 5
from pyrogram.errors import InternalServerError
from pyrogram.errors import FloodWait
try:
...
except FloodWait:
except FloodWait as e:
...
303 - See Other
---------------
303 - SeeOther
--------------
.. csv-table::
:file: ../../../compiler/error/source/303_SEE_OTHER.tsv
:delim: tab
:header-rows: 1
400 - Bad Request
-----------------
400 - BadRequest
----------------
.. csv-table::
:file: ../../../compiler/error/source/400_BAD_REQUEST.tsv
@ -48,8 +47,8 @@ follow the usual *PascalCase* convention.
:delim: tab
:header-rows: 1
406 - Not Acceptable
--------------------
406 - NotAcceptable
-------------------
.. csv-table::
:file: ../../../compiler/error/source/406_NOT_ACCEPTABLE.tsv
@ -64,8 +63,8 @@ follow the usual *PascalCase* convention.
:delim: tab
:header-rows: 1
500 - Internal Server Error
---------------------------
500 - InternalServerError
-------------------------
.. csv-table::
:file: ../../../compiler/error/source/500_INTERNAL_SERVER_ERROR.tsv

View File

@ -7,13 +7,12 @@ For a much more convenient way of registering callback functions have a look at
In case you decided to manually create an handler, use :meth:`add_handler() <pyrogram.Client.add_handler>` to register
it.
**Example:**
.. code-block:: python
:emphasize-lines: 1, 10
from pyrogram import Client, MessageHandler
app = Client(...)
app = Client("my_account")
def dump(client, message):
@ -34,6 +33,7 @@ it.
CallbackQueryHandler
InlineQueryHandler
UserStatusHandler
PollHandler
DisconnectHandler
RawUpdateHandler
@ -52,6 +52,9 @@ it.
.. autoclass:: UserStatusHandler()
:members:
.. autoclass:: PollHandler()
:members:
.. autoclass:: DisconnectHandler()
:members:

View File

@ -3,13 +3,12 @@ Available Methods
All Pyrogram methods listed here are bound to a :obj:`Client <pyrogram.Client>` instance.
**Example:**
.. code-block:: python
:emphasize-lines: 6
from pyrogram import Client
app = Client(...)
app = Client("my_account")
with app:
app.send_message("haskell", "hi")

View File

@ -3,9 +3,8 @@ Available Types
All Pyrogram types listed here are accessible through the main package directly.
**Example:**
.. code-block:: python
:emphasize-lines: 1
from pyrogram import User, Message, ...
@ -112,167 +111,72 @@ InputMessageContent
------------
.. autoclass:: User()
:members:
.. autoclass:: UserStatus()
:members:
.. autoclass:: Chat()
:members:
.. autoclass:: ChatPreview()
:members:
.. autoclass:: ChatPhoto()
:members:
.. autoclass:: ChatMember()
:members:
.. autoclass:: ChatMembers()
:members:
.. autoclass:: ChatPermissions()
:members:
.. autoclass:: Dialog()
:members:
.. autoclass:: Dialogs()
:members:
.. Messages & Media
----------------
.. autoclass:: Message()
:members:
.. autoclass:: Messages()
:members:
.. autoclass:: MessageEntity()
:members:
.. autoclass:: Photo()
:members:
.. autoclass:: PhotoSize()
:members:
.. autoclass:: UserProfilePhotos()
:members:
.. autoclass:: Audio()
:members:
.. autoclass:: Document()
:members:
.. autoclass:: Animation()
:members:
.. autoclass:: Video()
:members:
.. autoclass:: Voice()
:members:
.. autoclass:: VideoNote()
:members:
.. autoclass:: Contact()
:members:
.. autoclass:: Location()
:members:
.. autoclass:: Venue()
:members:
.. autoclass:: Sticker()
:members:
.. autoclass:: Game()
:members:
.. autoclass:: Poll()
:members:
.. autoclass:: PollOption()
:members:
.. Keyboards
---------
.. autoclass:: ReplyKeyboardMarkup()
:members:
.. autoclass:: KeyboardButton()
:members:
.. autoclass:: ReplyKeyboardRemove()
:members:
.. autoclass:: InlineKeyboardMarkup()
:members:
.. autoclass:: InlineKeyboardButton()
:members:
.. autoclass:: ForceReply()
:members:
.. autoclass:: CallbackQuery()
:members:
.. autoclass:: GameHighScore()
:members:
.. autoclass:: CallbackGame()
:members:
.. Input Media
-----------
.. autoclass:: InputMedia()
:members:
.. autoclass:: InputMediaPhoto()
:members:
.. autoclass:: InputMediaVideo()
:members:
.. autoclass:: InputMediaAudio()
:members:
.. autoclass:: InputMediaAnimation()
:members:
.. autoclass:: InputMediaDocument()
:members:
.. autoclass:: InputPhoneContact()
:members:
.. Inline Mode
-----------
.. autoclass:: InlineQuery()
:members:
.. autoclass:: InlineQueryResult()
:members:
.. autoclass:: InlineQueryResultArticle()
:members:
.. InputMessageContent
-------------------
.. autoclass:: InputMessageContent()
:members:
.. autoclass:: InputTextMessageContent()
:members:

View File

@ -66,7 +66,7 @@ How the Documentation is Organized
Contents are organized into self-contained topics and can be all accessed from the sidebar, or by following them in
order using the Next button at the end of each page. Here below you can, instead, find a list of the most relevant
pages.
pages for a quick access.
Getting Started
^^^^^^^^^^^^^^^
@ -86,23 +86,27 @@ API Reference
- `Client Class`_ - Details about the Client class.
- `Available Methods`_ - A list of available high-level methods.
- `Available Types`_ - A list of available high-level types.
- `Bound Methods`_ - A list of convenient bound methods.
.. _Client Class: api/client
.. _Available Methods: api/methods
.. _Available Types: api/types
.. _Bound Methods: api/bound-methods
Topics
^^^^^^
Relevant Topics
^^^^^^^^^^^^^^^
- `Smart Plugins`_ - How to modularize your application.
- `Advanced Usage`_ - How to use Telegram's raw API.
- `Release Notes`_ - Release notes for Pyrogram releases.
- `Pyrogram FAQ`_ - Answers to common Pyrogram questions.
- `Pyrogram Glossary`_ - A list of words with brief explanations.
.. _Smart Plugins: topics/smart-plugins
.. _Advanced Usage: topics/advanced-usage
.. _Release Notes: topics/releases
.. _Pyrogram FAQ: topics/faq
.. _Pyrogram Glossary: topics/glossary
.. toctree::
:hidden:
@ -128,6 +132,7 @@ Topics
api/client
api/methods
api/types
api/bound-methods
api/handlers
api/decorators
api/filters
@ -152,6 +157,7 @@ Topics
topics/voice-calls
topics/releases
topics/faq
topics/glossary
.. toctree::
:hidden:

View File

@ -61,6 +61,7 @@ after the session name, which will be ``pyrogrambot.session`` for the example be
"my_bot",
bot_token="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
)
app.run()
.. _project is set up: setup.html

View File

@ -29,12 +29,12 @@ Install Pyrogram
Bleeding Edge
-------------
Things are constantly evolving in Pyrogram, although new releases are published only when enough changes are added,
but this doesn't mean you can't try new features right now!
Pyrogram is always evolving, although new releases on PyPI are published only when enough changes are added, but this
doesn't mean you can't try new features right now!
In case you would like to try out the latest Pyrogram features and additions, the `GitHub repo`_ is always kept updated
with new changes; you can install the development version straight from the ``develop`` branch using this command
(note "develop.zip" in the link):
In case you'd like to try out the latest Pyrogram features, the `GitHub repo`_ is always kept updated with new changes;
you can install the development version straight from the ``develop`` branch using this command (note "develop.zip" in
the link):
.. code-block:: text
@ -44,7 +44,8 @@ Asynchronous
------------
Pyrogram heavily depends on IO-bound network code (it's a cloud-based messaging framework after all), and here's
where asyncio shines the most by providing extra performance while running on a single OS-level thread only.
where asyncio shines the most by providing extra performance and efficiency while running on a single OS-level thread
only.
**A fully asynchronous variant of Pyrogram is therefore available** (Python 3.5.3+ required).
Use this command to install (note "asyncio.zip" in the link):

View File

@ -10,7 +10,7 @@ Get Pyrogram Real Fast
2. Get your own Telegram API key from https://my.telegram.org/apps.
3. Open your best text editor and paste the following:
3. Open your best text editor and paste the following:
.. code-block:: python
@ -40,10 +40,9 @@ Enjoy the API
-------------
That was just a quick overview that barely scratched the surface!
In the next few pages of the introduction, we'll take a much more in-depth look of what we have just done.
In the next few pages of the introduction, we'll take a much more in-depth look of what we have just done above.
Feeling eager? You can take a shortcut to `Calling Methods`_ and come back later to learn some more
details.
Feeling eager to continue? You can take a shortcut to `Calling Methods`_ and come back later to learn some more details.
.. _community: //t.me/pyrogramchat
.. _Calling Methods: ../start/invoking

View File

@ -1,51 +1,57 @@
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 ``RPCError`` superclass):
- `303 - See Other <../api/errors#see-other>`_
- `400 - Bad Request <../api/errors#bad-request>`_
- `401 - Unauthorized <../api/errors#unauthorized>`_
- `403 - Forbidden <../api/errors#forbidden>`_
- `406 - Not Acceptable <../api/errors#not-acceptable>`_
- `420 - Flood <../api/errors#flood>`_
- `500 - Internal Server Error <../api/errors#internal-server-error>`_
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 ``520 Unknown Error`` exception and logs it
in the ``unknown_errors.txt`` file. Users are invited to report these unknown errors.
Examples
--------
Errors are inevitable when working with the API, and they must be correctly handled with ``try..except`` blocks in order
to control the behaviour of your application. Pyrogram errors all live inside the ``errors`` package:
.. code-block:: python
from pyrogram.errors import (
BadRequest, Flood, InternalServerError,
SeeOther, Unauthorized, UnknownError
)
from pyrogram import errors
try:
...
except BadRequest:
pass
except Flood:
pass
except InternalServerError:
pass
except SeeOther:
pass
except Unauthorized:
pass
except UnknownError:
pass
RPCError
--------
Exception objects may also contain some informative values.
E.g.: ``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:
The father of all errors is named ``RPCError``. This error exists in form of a Python exception and is able to catch all
Telegram API related errors.
.. code-block:: python
from pyrogram.errors import RPCError
.. warning::
It must be noted that catching this error is bad practice, especially when no feedback is given (i.e. by
logging/printing the full error traceback), because it makes it impossible to understand what went wrong.
Error Categories
----------------
The ``RPCError`` packs together all the possible errors Telegram could raise, but to make things tidier, Pyrogram
provides categories of errors, which are named after the common HTTP errors:
.. code-block:: python
from pyrogram.errors import BadRequest, Forbidden, ...
- `303 - SeeOther <../api/errors#seeother>`_
- `400 - BadRequest <../api/errors#badrequest>`_
- `401 - Unauthorized <../api/errors#unauthorized>`_
- `403 - Forbidden <../api/errors#forbidden>`_
- `406 - NotAcceptable <../api/errors#notacceptable>`_
- `420 - Flood <../api/errors#flood>`_
- `500 - InternalServerError <../api/errors#internalservererror>`_
Unknown Errors
--------------
In case Pyrogram does not know anything yet about a specific error, it raises a special ``520 - UnknownError`` exception
and logs it in the ``unknown_errors.txt`` file. Users are invited to report these unknown errors.
Errors with Values
------------------
Exception objects may also contain some informative values. For example, ``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
@ -55,4 +61,4 @@ before you can try again. The value is always stored in the ``x`` field of the r
try:
...
except FloodWait as e:
time.sleep(e.x)
time.sleep(e.x) # Wait before trying again

View File

@ -1,9 +1,12 @@
Calling Methods
===============
At this point, we have successfully `installed Pyrogram`_ and authorized_ our account; we are now pointing towards the
At this point, we have successfully `installed Pyrogram`_ and authorized_ our account; we are now aiming towards the
core of the library. It's time to start playing with the API!
Basic Usage
-----------
Making API method calls with Pyrogram is very simple. Here's an example we are going to examine:
.. code-block:: python
@ -60,8 +63,8 @@ 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:
: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:
.. code-block:: python

View File

@ -8,7 +8,7 @@ Defining Updates
----------------
First, let's define what are these updates. As hinted already, 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
account (incoming messages, new members join, bot 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 <../api/handlers>`_.
@ -70,7 +70,7 @@ begins.
app.add_handler(my_handler)
Last one, the :meth:`run() <pyrogram.Client.run>` method. What this does is simply calling
Last one, the :meth:`run() <pyrogram.Client.run>` method. What this does is simply call
: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.

View File

@ -101,9 +101,9 @@ sending messages with IDs only thanks to cached access hashes.
There are three different InputPeer types, one for each kind of Telegram entity.
Whenever an InputPeer is needed you must pass one of these:
- `InputPeerUser <https://docs.pyrogram.ml/types/InputPeerUser>`_ - Users
- `InputPeerChat <https://docs.pyrogram.ml/types/InputPeerChat>`_ - Basic Chats
- `InputPeerChannel <https://docs.pyrogram.ml/types/InputPeerChannel>`_ - Either Channels or Supergroups
- :obj:`InputPeerUser <../telegram/types/InputPeerUser>` - Users
- :obj:`InputPeerChat <../telegram/types/InputPeerChat>` - Basic Chats
- :obj:`InputPeerChannel <../telegram/types/InputPeerChannel>` - Either Channels or Supergroups
But you don't necessarily have to manually instantiate each object because, luckily for you, Pyrogram already provides
:meth:`resolve_peer() <pyrogram.Client.resolve_peer>` as a convenience utility method that returns the correct InputPeer

View File

@ -17,21 +17,51 @@ C. It enables you to easily create custom applications for both user and bot ide
.. _Telegram: https://telegram.org
.. _MTProto API: https://core.telegram.org/api#telegram-api
What does "Pyrogram" mean?
--------------------------
What does the name 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?
--------------------
How old is the project?
-----------------------
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 Pyrogram?
-------------
- **Easy**: You can install Pyrogram with pip and start building your applications right away.
- **Elegant**: Low-level details are abstracted and re-presented in a much nicer and easier way.
- **Fast**: Crypto parts are boosted up by TgCrypto_, a high-performance library written in pure C.
- **Documented**: Pyrogram API methods, types and public interfaces are well documented.
- **Type-hinted**: Exposed Pyrogram types and method parameters are all type-hinted.
- **Updated**, to make use of the latest Telegram API version and features.
- **Pluggable**: The `Smart Plugin`_ system allows to write components with minimal boilerplate code.
- **Comprehensive**: Execute any `advanced action`_ an official client is able to do, and even more.
.. _TgCrypto: https://github.com/pyrogram/tgcrypto
.. _Smart Plugin: smart-plugins
.. _advanced action: advanced-usage
What can MTProto do more than the Bot API?
------------------------------------------
- Authorize both user and bot identities.
- Upload & download any file, up to 1500 MB each.
- Has less overhead due to direct connections to the actual Telegram servers.
- Run multiple sessions at once, up to 10 per account (either bot or user).
- Get information about any public chat by usernames, even if not a member.
- Obtain information about any message existing in a chat using message ids.
- retrieve the whole chat members list of either public or private chats.
- Receive extra updates, such as the one about a user name change.
- More meaningful errors in case something went wrong.
- Get API version updates, and thus new features, sooner.
Why do I need an API key for bots?
----------------------------------
@ -46,6 +76,8 @@ Using MTProto is the only way to communicate with the actual Telegram servers, a
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.
Why is the main API (MTProto) superiod
I started a client but nothing happens!
---------------------------------------
@ -65,7 +97,7 @@ in a bunch of seconds:
.. _you need a proxy: proxy
I keep getting [400 PEER_ID_INVALID] error!
I keep getting PEER_ID_INVALID error!
-------------------------------------------
The error in question is **[400 PEER_ID_INVALID]: The id/access_hash combination is invalid**, and could mean several
@ -104,4 +136,18 @@ mistakes by either the automatic systems or a moderator. In such cases you can k
recover@telegram.org, contact `@smstelegram`_ on Twitter or use `this form`_.
.. _@smstelegram: https://twitter.com/smstelegram
.. _this form: https://telegram.org/support
.. _this form: https://telegram.org/support
About the License
-----------------
.. image:: https://www.gnu.org/graphics/lgplv3-with-text-154x68.png
:align: left
Pyrogram is free software and is currently licensed under the terms of the GNU Lesser General Public License v3 or later
(LGPLv3+). In short: you may use, redistribute and/or modify it provided that modifications are described and licensed
for free under LGPLv3+.
In other words: you can use and integrate Pyrogram into your own code --- either open source, under the same or a
different licence or even proprietary --- without being required to release the source code of your own applications.
However, any modifications to the library itself are required to be published for free under the same LGPLv3+ license.

View File

@ -7,6 +7,9 @@ but there's much more than that to come.
Here we'll discuss about :class:`Filters <pyrogram.Filters>`. Filters enable a fine-grain control over what kind of
updates are allowed or not to be passed in your callback functions, based on their inner details.
Single Filters
--------------
Let's start right away with a simple example:
- This example will show you how to **only** handle messages containing an :obj:`Audio <pyrogram.Audio>` object and

View File

@ -0,0 +1,53 @@
Pyrogram Glossary
-----------------
This page contains a list of common words with brief explanations related to Pyrogram and, to some extent, Telegram in
general.
.. glossary::
API
Application Programming Interface: a set of methods, protocols and tools that make it easier to develop programs
by providing useful building blocks to the developer.
API key
A secret code used to authenticate and/or authorize a specific application to Telegram in order for it to
control how the API is being used, for example, to prevent abuses of the API.
MTProto
The name of the custom-made, open encryption protocol by Telegram, implemented in Pyrogram.
MTProto API
The Telegram main API Pyrogram makes use of, which is able to connect both users and normal bots to Telegram
using MTProto as application layer protocol and execute any method Telegram provides from its public schema.
Bot API
The `Telegram Bot API`_ that is able to only connect normal bots to Telegram using HTTP as application layer
protocol and allows to execute a subset of the main Telegram API.
Pyrogrammer
A developer that uses Pyrogram to build Telegram applications.
Userbot
Also known as *user bot* or *ubot* for short, is a user logged in by third-party Telegram libraries --- such as
Pyrogram --- to automate some behaviours, like sending messages or reacting to text commands or any other event.
Session
Also known as *login session*, is a strictly personal piece of information created and held by both parties
(client and server) which is used to grant permission into a single account without having to start a new
authorization process from scratch.
Callback
Also known as *callback function*, is a user-defined generic function that *can be* registered to and then
called-back by the framework when specific events occurs.
Handler
An object that wraps around a callback function that is *actually meant* to be registered into the framework,
which will then be able to handle a specific kind of events, such as a new incoming message, for example.
Decorator
Also known as *function decorator*, in Python, is a callable object that is used to modify another function.
Decorators in Pyrogram are used to automatically register callback functions for `handling updates`_.
.. _Telegram Bot API: https://core.telegram.org/bots/api
.. _handling updates: ../start/updates

View File

@ -30,7 +30,7 @@ after importing your modules, like this:
handlers.py
main.py
- ``handlers.py``
- ``handlers.py``
.. code-block:: python
@ -41,7 +41,7 @@ after importing your modules, like this:
def echo_reversed(client, message):
message.reply(message.text[::-1])
- ``main.py``
- ``main.py``
.. code-block:: python
@ -91,7 +91,7 @@ Setting up your Pyrogram project to accommodate Smart Plugins is pretty straight
config.ini
main.py
- ``plugins/handlers.py``
- ``plugins/handlers.py``
.. code-block:: python
:emphasize-lines: 4, 9
@ -108,14 +108,14 @@ Setting up your Pyrogram project to accommodate Smart Plugins is pretty straight
def echo_reversed(client, message):
message.reply(message.text[::-1])
- ``config.ini``
- ``config.ini``
.. code-block:: ini
[plugins]
root = plugins
- ``main.py``
- ``main.py``
.. code-block:: python
@ -199,8 +199,8 @@ also organized in subfolders:
...
...
- Load every handler from every module, namely *plugins0.py*, *plugins1.py* and *plugins2.py* in alphabetical order
(files) and definition order (handlers inside files):
- Load every handler from every module, namely *plugins0.py*, *plugins1.py* and *plugins2.py* in alphabetical order
(files) and definition order (handlers inside files):
Using *config.ini* file:
@ -217,7 +217,7 @@ also organized in subfolders:
Client("my_account", plugins=plugins).run()
- Load only handlers defined inside *plugins2.py* and *plugins0.py*, in this order:
- Load only handlers defined inside *plugins2.py* and *plugins0.py*, in this order:
Using *config.ini* file:
@ -243,7 +243,7 @@ also organized in subfolders:
Client("my_account", plugins=plugins).run()
- Load everything except the handlers inside *plugins2.py*:
- Load everything except the handlers inside *plugins2.py*:
Using *config.ini* file:
@ -264,7 +264,7 @@ also organized in subfolders:
Client("my_account", plugins=plugins).run()
- Load only *fn3*, *fn1* and *fn2* (in this order) from *plugins1.py*:
- Load only *fn3*, *fn1* and *fn2* (in this order) from *plugins1.py*:
Using *config.ini* file:
@ -297,7 +297,7 @@ Each function decorated with the usual ``on_message`` decorator (or any other de
*(handler: Handler, group: int)*. The actual callback function is therefore stored inside the handler's *callback*
attribute. Here's an example:
- ``plugins/handlers.py``
- ``plugins/handlers.py``
.. code-block:: python
:emphasize-lines: 5, 6
@ -321,7 +321,7 @@ In order to unload a plugin, or any other handler, all you need to do is obtain
relevant module and call :meth:`remove_handler() <pyrogram.Client.remove_handler>` Client's method with your function
name preceded by the star ``*`` operator as argument. Example:
- ``main.py``
- ``main.py``
.. code-block:: python
@ -345,7 +345,7 @@ Loading
Similarly to the unloading process, in order to load again a previously unloaded plugin you do the same, but this time
using :meth:`add_handler() <pyrogram.Client.add_handler>` instead. Example:
- ``main.py``
- ``main.py``
.. code-block:: python

View File

@ -60,9 +60,7 @@ log = logging.getLogger(__name__)
class Client(Methods, BaseClient):
"""This class represents a Client, the main means for interacting with Telegram.
It exposes bot-like methods for an easy access to the API as well as a simple way to
invoke every single Telegram API method available.
"""Pyrogram Client, the main means for interacting with Telegram.
Parameters:
session_name (``str``):
@ -80,7 +78,7 @@ class Client(Methods, BaseClient):
This is an alternative way to pass it if you don't want to use the *config.ini* file.
app_version (``str``, *optional*):
Application version. Defaults to "Pyrogram \U0001f525 vX.Y.Z"
Application version. Defaults to "Pyrogram :fire: vX.Y.Z"
This is an alternative way to set it if you don't want to use the *config.ini* file.
device_model (``str``, *optional*):
@ -110,6 +108,10 @@ class Client(Methods, BaseClient):
Only applicable for new sessions and will be ignored in case previously
created sessions are loaded.
bot_token (``str``, *optional*):
Pass your Bot API token to create a bot session, e.g.: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
Only applicable for new sessions.
phone_number (``str`` | ``callable``, *optional*):
Pass your phone number as string (with your Country Code prefix included) to avoid entering it manually.
Or pass a callback function which accepts no arguments and must return the correct phone number as string
@ -143,10 +145,6 @@ class Client(Methods, BaseClient):
a new Telegram account in case the phone number you passed is not registered yet.
Only applicable for new sessions.
bot_token (``str``, *optional*):
Pass your Bot API token to create a bot session, e.g.: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
Only applicable for new sessions.
last_name (``str``, *optional*):
Same purpose as *first_name*; pass a Last Name to avoid entering it manually. It can
be an empty string: "". Only applicable for new sessions.
@ -193,12 +191,12 @@ class Client(Methods, BaseClient):
ipv6: bool = False,
proxy: dict = None,
test_mode: bool = False,
bot_token: str = None,
phone_number: str = None,
phone_code: Union[str, callable] = None,
password: str = None,
recovery_code: callable = None,
force_sms: bool = False,
bot_token: str = None,
first_name: str = None,
last_name: str = None,
workers: int = BaseClient.WORKERS,
@ -221,12 +219,12 @@ class Client(Methods, BaseClient):
# TODO: Make code consistent, use underscore for private/protected fields
self._proxy = proxy
self.test_mode = test_mode
self.bot_token = bot_token
self.phone_number = phone_number
self.phone_code = phone_code
self.password = password
self.recovery_code = recovery_code
self.force_sms = force_sms
self.bot_token = bot_token
self.first_name = first_name
self.last_name = last_name
self.workers = workers

View File

@ -191,35 +191,19 @@ class Filters:
"""Filter messages sent via inline bots"""
service = create("Service", lambda _, m: bool(m.service))
"""Filter service messages. A service message contains any of the following fields set
"""Filter service messages.
- left_chat_member
- new_chat_title
- new_chat_photo
- delete_chat_photo
- group_chat_created
- supergroup_chat_created
- channel_chat_created
- migrate_to_chat_id
- migrate_from_chat_id
- pinned_message
- game_score"""
A service message contains any of the following fields set: *left_chat_member*,
*new_chat_title*, *new_chat_photo*, *delete_chat_photo*, *group_chat_created*, *supergroup_chat_created*,
*channel_chat_created*, *migrate_to_chat_id*, *migrate_from_chat_id*, *pinned_message*, *game_score*.
"""
media = create("Media", lambda _, m: bool(m.media))
"""Filter media messages. A media message contains any of the following fields set
"""Filter media messages.
- audio
- document
- photo
- sticker
- video
- animation
- voice
- video_note
- contact
- location
- venue
- poll"""
A media message contains any of the following fields set: *audio*, *document*, *photo*, *sticker*, *video*,
*animation*, *voice*, *video_note*, *contact*, *location*, *venue*, *poll*.
"""
@staticmethod
def command(

View File

@ -30,7 +30,8 @@ class OnCallbackQuery(BaseClient):
filters=None,
group: int = 0
) -> callable:
"""Use this decorator to automatically register a function for handling callback queries.
"""Decorator for handling callback queries.
This does the same thing as :meth:`add_handler` using the :class:`CallbackQueryHandler`.
Parameters:

View File

@ -30,7 +30,8 @@ class OnDeletedMessages(BaseClient):
filters=None,
group: int = 0
) -> callable:
"""Use this decorator to automatically register a function for handling deleted messages.
"""Decorator for handling deleted messages.
This does the same thing as :meth:`add_handler` using the :class:`DeletedMessagesHandler`.
Parameters:

View File

@ -23,7 +23,8 @@ from ...ext import BaseClient
class OnDisconnect(BaseClient):
def on_disconnect(self=None) -> callable:
"""Use this decorator to automatically register a function for handling disconnections.
"""Decorator for handling disconnections.
This does the same thing as :meth:`add_handler` using the :class:`DisconnectHandler`.
"""

View File

@ -30,7 +30,8 @@ class OnInlineQuery(BaseClient):
filters=None,
group: int = 0
) -> callable:
"""Use this decorator to automatically register a function for handling inline queries.
"""Decorator for handling inline queries.
This does the same thing as :meth:`add_handler` using the :class:`InlineQueryHandler`.
Parameters:

View File

@ -30,7 +30,8 @@ class OnMessage(BaseClient):
filters=None,
group: int = 0
) -> callable:
"""Use this decorator to automatically register a function for handling messages.
"""Decorator for handling messages.
This does the same thing as :meth:`add_handler` using the :class:`MessageHandler`.
Parameters:

View File

@ -30,7 +30,8 @@ class OnPoll(BaseClient):
filters=None,
group: int = 0
) -> callable:
"""Use this decorator to automatically register a function for handling poll updates.
"""Decorator for handling poll updates.
This does the same thing as :meth:`add_handler` using the :class:`PollHandler`.
Parameters:

View File

@ -28,7 +28,8 @@ class OnRawUpdate(BaseClient):
self=None,
group: int = 0
) -> callable:
"""Use this decorator to automatically register a function for handling raw updates.
"""Decorator for handling raw updates.
This does the same thing as :meth:`add_handler` using the :class:`RawUpdateHandler`.
Parameters:

View File

@ -30,7 +30,7 @@ class OnUserStatus(BaseClient):
filters=None,
group: int = 0
) -> callable:
"""Use this decorator to automatically register a function for handling user status updates.
"""Decorator for handling user status updates.
This does the same thing as :meth:`add_handler` using the :class:`UserStatusHandler`.
Parameters:

View File

@ -28,7 +28,7 @@ class ForwardMessages(BaseClient):
self,
chat_id: Union[int, str],
from_chat_id: Union[int, str],
message_ids: Iterable[int],
message_ids: Union[int, Iterable[int]],
disable_notification: bool = None,
as_copy: bool = False,
remove_caption: bool = False

View File

@ -46,7 +46,7 @@ class SendDocument(BaseClient):
progress: callable = None,
progress_args: tuple = ()
) -> Union["pyrogram.Message", None]:
"""Send general files.
"""Send generic files.
Parameters:
chat_id (``int`` | ``str``):

View File

@ -30,9 +30,9 @@ from ..user_and_chats import User
class CallbackQuery(PyrogramType, Update):
"""An incoming callback query from a callback button in an inline keyboard.
If the button that originated the query was attached to a message sent by the bot, the field message
will be present. If the button was attached to a message sent via the bot (in inline mode),
the field inline_message_id will be present. Exactly one of the fields data or game_short_name will be present.
If the button that originated the query was attached to a message sent by the bot, the field *message*
will be present. If the button was attached to a message sent via the bot (in inline mode), the field
*inline_message_id* will be present. Exactly one of the fields *data* or *game_short_name* will be present.
Parameters:
id (``str``):

View File

@ -661,7 +661,7 @@ class Message(PyrogramType, Update):
reply_to_message_id: int = None,
reply_markup=None
) -> "Message":
"""Bound method *reply* of :obj:`Message`.
"""Bound method *reply* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -748,7 +748,7 @@ class Message(PyrogramType, Update):
progress: callable = None,
progress_args: tuple = ()
) -> "Message":
"""Bound method *reply_animation* of :obj:`Message`.
"""Bound method *reply_animation* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -882,7 +882,7 @@ class Message(PyrogramType, Update):
progress: callable = None,
progress_args: tuple = ()
) -> "Message":
"""Bound method *reply_audio* of :obj:`Message`.
"""Bound method *reply_audio* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -1010,7 +1010,7 @@ class Message(PyrogramType, Update):
"pyrogram.ForceReply"
] = None
) -> "Message":
"""Bound method *reply_cached_media* of :obj:`Message`.
"""Bound method *reply_cached_media* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -1077,7 +1077,7 @@ class Message(PyrogramType, Update):
)
def reply_chat_action(self, action: str) -> bool:
"""Bound method *reply_chat_action* of :obj:`Message`.
"""Bound method *reply_chat_action* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -1130,7 +1130,7 @@ class Message(PyrogramType, Update):
"pyrogram.ForceReply"
] = None
) -> "Message":
"""Bound method *reply_contact* of :obj:`Message`.
"""Bound method *reply_contact* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -1217,7 +1217,7 @@ class Message(PyrogramType, Update):
progress: callable = None,
progress_args: tuple = ()
) -> "Message":
"""Bound method *reply_document* of :obj:`Message`.
"""Bound method *reply_document* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -1331,7 +1331,7 @@ class Message(PyrogramType, Update):
"pyrogram.ForceReply"
] = None
) -> "Message":
"""Bound method *reply_game* of :obj:`Message`.
"""Bound method *reply_game* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -1396,7 +1396,7 @@ class Message(PyrogramType, Update):
reply_to_message_id: int = None,
hide_via: bool = None
) -> "Message":
"""Bound method *reply_inline_bot_result* of :obj:`Message`.
"""Bound method *reply_inline_bot_result* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -1470,7 +1470,7 @@ class Message(PyrogramType, Update):
"pyrogram.ForceReply"
] = None
) -> "Message":
"""Bound method *reply_location* of :obj:`Message`.
"""Bound method *reply_location* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -1538,7 +1538,7 @@ class Message(PyrogramType, Update):
disable_notification: bool = None,
reply_to_message_id: int = None
) -> "Message":
"""Bound method *reply_media_group* of :obj:`Message`.
"""Bound method *reply_media_group* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -1610,7 +1610,7 @@ class Message(PyrogramType, Update):
progress: callable = None,
progress_args: tuple = ()
) -> "Message":
"""Bound method *reply_photo* of :obj:`Message`.
"""Bound method *reply_photo* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -1724,7 +1724,7 @@ class Message(PyrogramType, Update):
"pyrogram.ForceReply"
] = None
) -> "Message":
"""Bound method *reply_poll* of :obj:`Message`.
"""Bound method *reply_poll* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -1800,7 +1800,7 @@ class Message(PyrogramType, Update):
progress: callable = None,
progress_args: tuple = ()
) -> "Message":
"""Bound method *reply_sticker* of :obj:`Message`.
"""Bound method *reply_sticker* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -1903,7 +1903,7 @@ class Message(PyrogramType, Update):
"pyrogram.ForceReply"
] = None
) -> "Message":
"""Bound method *reply_venue* of :obj:`Message`.
"""Bound method *reply_venue* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -2005,7 +2005,7 @@ class Message(PyrogramType, Update):
progress: callable = None,
progress_args: tuple = ()
) -> "Message":
"""Bound method *reply_video* of :obj:`Message`.
"""Bound method *reply_video* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -2140,7 +2140,7 @@ class Message(PyrogramType, Update):
progress: callable = None,
progress_args: tuple = ()
) -> "Message":
"""Bound method *reply_video_note* of :obj:`Message`.
"""Bound method *reply_video_note* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -2258,7 +2258,7 @@ class Message(PyrogramType, Update):
progress: callable = None,
progress_args: tuple = ()
) -> "Message":
"""Bound method *reply_voice* of :obj:`Message`.
"""Bound method *reply_voice* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -2368,7 +2368,7 @@ class Message(PyrogramType, Update):
"pyrogram.ForceReply"
] = None
) -> "Message":
"""Bound method *edit* of :obj:`Message`
"""Bound method *edit* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -2425,7 +2425,7 @@ class Message(PyrogramType, Update):
"pyrogram.ForceReply"
] = None
) -> "Message":
"""Bound method *edit_caption* of :obj:`Message`
"""Bound method *edit_caption* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -2468,7 +2468,7 @@ class Message(PyrogramType, Update):
)
def edit_media(self, media: InputMedia, reply_markup: "pyrogram.InlineKeyboardMarkup" = None) -> "Message":
"""Bound method *edit_media* of :obj:`Message`
"""Bound method *edit_media* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -2506,7 +2506,7 @@ class Message(PyrogramType, Update):
)
def edit_reply_markup(self, reply_markup: "pyrogram.InlineKeyboardMarkup" = None) -> "Message":
"""Bound method *edit_reply_markup* of :obj:`Message`
"""Bound method *edit_reply_markup* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -2547,7 +2547,7 @@ class Message(PyrogramType, Update):
as_copy: bool = False,
remove_caption: bool = False
) -> "Message":
"""Bound method *forward* of :obj:`Message`.
"""Bound method *forward* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -2690,7 +2690,7 @@ class Message(PyrogramType, Update):
)
def delete(self, revoke: bool = True):
"""Bound method *delete* of :obj:`Message`.
"""Bound method *delete* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -2726,7 +2726,7 @@ class Message(PyrogramType, Update):
)
def click(self, x: int or str, y: int = 0, quote: bool = None, timeout: int = 10):
"""Bound method *click* of :obj:`Message`.
"""Bound method *click* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for clicking a button attached to the message instead of:
@ -2764,6 +2764,7 @@ class Message(PyrogramType, Update):
Parameters:
x (``int`` | ``str``):
Used as integer index, integer abscissa (in pair with y) or as string label.
Defaults to 0 (first button).
y (``int``, *optional*):
Used as ordinate only (in pair with x).
@ -2853,7 +2854,7 @@ class Message(PyrogramType, Update):
progress: callable = None,
progress_args: tuple = ()
) -> str:
"""Bound method *download* of :obj:`Message`.
"""Bound method *download* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
@ -2902,7 +2903,7 @@ class Message(PyrogramType, Update):
)
def pin(self, disable_notification: bool = None) -> "Message":
"""Bound method *pin* of :obj:`Message`.
"""Bound method *pin* :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:

View File

@ -25,7 +25,7 @@ from ...ext.utils import encode
class ChatPhoto(PyrogramType):
"""a chat photo.
"""A chat photo.
Parameters:
small_file_id (``str``):