Docs revamp. Part 2

This commit is contained in:
Dan 2019-05-10 16:14:10 +02:00
parent 559eaa2d03
commit e4b0a78f1a
33 changed files with 447 additions and 315 deletions

View File

@ -6,15 +6,7 @@ In this section you can find a detailed description of the Pyrogram package and
:class:`Client <pyrogram.Client>` is the main class. It exposes easy-to-use methods that are named :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. after the well established Telegram Bot API methods, thus offering a familiar look to Bot developers.
.. toctree:: Client
:maxdepth: 1 ------
types
methods
handlers
decorators
filters
errors
.. autoclass:: pyrogram.Client() .. autoclass:: pyrogram.Client()

View File

@ -1,5 +1,5 @@
Handlers Update Handlers
======== ===============
Handlers are used to instruct Pyrogram about which kind of updates you'd like to handle with your callback functions. Handlers are used to instruct Pyrogram about which kind of updates you'd like to handle with your callback functions.

View File

@ -1,5 +1,5 @@
Methods Available Methods
======= =================
All Pyrogram methods listed here are bound to a :obj:`Client <pyrogram.Client>` instance. All Pyrogram methods listed here are bound to a :obj:`Client <pyrogram.Client>` instance.

View File

@ -1,5 +1,5 @@
Types Available Types
===== ===============
All Pyrogram types listed here are accessible through the main package directly. All Pyrogram types listed here are accessible through the main package directly.

View File

@ -13,16 +13,21 @@ Welcome to Pyrogram
<b>Telegram MTProto API Framework for Python</b> <b>Telegram MTProto API Framework for Python</b>
<br> <br>
<a href="https://docs.pyrogram.ml"> <a href="https://github.com/pyrogram/pyrogram">
Documentation GitHub
</a> </a>
<a href="https://t.me/PyrogramChat">
Community
</a>
<a href="https://github.com/pyrogram/pyrogram/releases"> <a href="https://github.com/pyrogram/pyrogram/releases">
Changelog Changelog
</a> </a>
<a href="https://t.me/PyrogramChat"> <a href="https://pypi.org/project/Pyrogram">
Community PyPI
</a> </a>
<br> <br>
<a href="compiler/api/source/main_api.tl"> <a href="compiler/api/source/main_api.tl">
@ -49,64 +54,69 @@ Welcome to Pyrogram
app.run() app.run()
Welcome to Pyrogram's Documentation! Here you can find resources for learning how to use the framework.
Contents are organized into self-contained topics and can be accessed from the sidebar, or by following them in order
using the Next button at the end of each page. But first, here's a brief overview of what is this all about.
About
-----
**Pyrogram** is an elegant, easy-to-use Telegram_ client library and framework written from the ground up in Python and C. **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 apps using both user and bot identities (bot API alternative) via the `MTProto API`_. It enables you to easily create custom apps using both user and bot identities (bot API alternative) via the `MTProto API`_.
Features How the documentation is organized
-------- ----------------------------------
- **Easy**: You can install Pyrogram with pip and start building your applications right away. Contents are organized into self-contained topics and can be accessed from the sidebar, or by following them in order
- **Elegant**: Low-level details are abstracted and re-presented in a much nicer and easier way. using the Next button at the end of each page.
- **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 the latest Telegram API version, currently Layer 97 on top of `MTProto 2.0`_.
- **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.
To get started, press the Next button. Relevant Pages
^^^^^^^^^^^^^^
- `Quick Start`_ - Concise steps to get you started as fast as possible.
- `API Usage`_ - Guide on how to use Pyrogram's API.
- `Update Handling`_ - Guide on how to handle Telegram updates.
- Client_ - Reference details about the Client class.
- Types_ - All the available Pyrogram types.
- Methods_ - All the available Pyrogram methods.
**To get started, press the Next button**
.. toctree:: .. toctree::
:hidden: :hidden:
:caption: Quick Start :caption: Introduction
start/installation intro/start
start/setup intro/install
start/usage intro/setup
intro/auth
.. toctree:: .. toctree::
:hidden: :hidden:
:caption: Resources :caption: Topic Guides
resources/update-handling topics/usage
resources/using-filters topics/update-handling
resources/more-on-updates topics/using-filters
resources/configuration-file topics/more-on-updates
resources/smart-plugins topics/configuration-file
resources/auto-authorization topics/smart-plugins
resources/customize-sessions topics/auto-authorization
resources/tgcrypto topics/customize-sessions
resources/text-formatting topics/tgcrypto
resources/socks5-proxy topics/text-formatting
resources/bots-interaction topics/socks5-proxy
resources/error-handling topics/bots-interaction
resources/test-servers topics/error-handling
resources/advanced-usage topics/test-servers
resources/voice-calls topics/advanced-usage
resources/changelog topics/voice-calls
topics/changelog
.. toctree:: .. toctree::
:hidden: :hidden:
:caption: Main Package :caption: API Reference
pyrogram/index core/client
core/types
core/methods
core/handlers
core/decorators
core/filters
core/errors
.. toctree:: .. toctree::
:hidden: :hidden:
@ -115,7 +125,12 @@ To get started, press the Next button.
functions/index functions/index
types/index types/index
.. _`Telegram`: https://telegram.org .. _Telegram: https://telegram.org
.. _TgCrypto: https://docs.pyrogram.ml/resources/TgCrypto .. _TgCrypto: https://docs.pyrogram.ml/resources/TgCrypto
.. _`MTProto API`: https://core.telegram.org/api#telegram-api .. _MTProto API: https://core.telegram.org/api#telegram-api
.. _`MTProto 2.0`: https://core.telegram.org/mtproto .. _Quick Start: intro/start.html
.. _API Usage: topics/usage.html
.. _Update Handling: topics/update-handling.html
.. _Client: core/client.html
.. _Types: core/types.html
.. _Methods: core/methods

View File

@ -0,0 +1,68 @@
Authorization
=============
Once a `project is set up`_, you will still have to follow a few steps before you can actually use Pyrogram to make
API calls. This section provides all the information you need in order to authorize yourself as user or a bot.
User Authorization
------------------
In order to use the API, Telegram requires that users be authorized via their phone numbers.
Pyrogram automatically manages this access, all you need to do is create an instance of the
:class:`Client <pyrogram.Client>` class by passing to it a ``session_name`` of your choice (e.g.: "my_account") and call
the :meth:`run() <pyrogram.Client.run>` method:
.. code-block:: python
from pyrogram import Client
app = Client("my_account")
app.run()
This starts an interactive shell asking you to input your **phone number** (including your `Country Code`_) and the
**phone code** you will receive in your devices that are already authorized or via SMS:
.. code-block:: text
Enter phone number: +39**********
Is "+39**********" correct? (y/n): y
Enter phone code: 32768
Logged in successfully as Dan
After successfully authorizing yourself, a new file called ``my_account.session`` will be created allowing Pyrogram to
execute API calls with your identity. This file will be loaded again when you restart your app, and as long as you
keep the session alive, Pyrogram won't ask you again to enter your phone number.
.. important::
Your ``*.session`` files are personal and must be kept secret.
.. note::
The code above does nothing except asking for credentials and keeping the client online, hit ``CTRL+C`` now to stop
your application and keep reading.
Bot Authorization
-----------------
Bots are a special kind of users that are authorized via their tokens (instead of phone numbers), which are created by
the `Bot Father`_. Bot tokens replace the users' phone numbers only — you still need to
`configure a Telegram API key <setup.html#configuration>`_ with Pyrogram, even when using bots.
The authorization process is automatically managed. All you need to do is choose a ``session_name`` (can be anything,
usually your bot username) and pass your bot token using the ``bot_token`` parameter. The session file will be named
after the session name, which will be ``pyrogrambot.session`` for the example below.
.. code-block:: python
from pyrogram import Client
app = Client(
"my_bot",
bot_token="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
)
app.run()
.. _project is set up: setup.html
.. _Country Code: https://en.wikipedia.org/wiki/List_of_country_calling_codes
.. _Bot Father: https://t.me/botfather

View File

@ -1,8 +1,8 @@
Installation Install Guide
============ =============
Being a Python library, **Pyrogram** requires Python to be installed in your system. Being a Python library, **Pyrogram** requires Python to be installed in your system.
We recommend using the latest version of Python 3 and pip. We recommend using the latest versions of both Python 3 and pip.
- Get **Python 3** from https://www.python.org/downloads/ (or with your package manager) - Get **Python 3** from https://www.python.org/downloads/ (or with your package manager)
- Get **pip** by following the instructions at https://pip.pypa.io/en/latest/installing/. - Get **pip** by following the instructions at https://pip.pypa.io/en/latest/installing/.
@ -88,5 +88,5 @@ If no error shows up you are good to go.
>>> pyrogram.__version__ >>> pyrogram.__version__
'0.12.0' '0.12.0'
.. _TgCrypto: https://docs.pyrogram.ml/resources/TgCrypto .. _TgCrypto: ../resources/tgcrypto.html
.. _`Github repo`: http://github.com/pyrogram/pyrogram .. _`Github repo`: http://github.com/pyrogram/pyrogram

View File

@ -0,0 +1,61 @@
Project Setup
=============
We have just `installed Pyrogram`_. In this page we'll discuss what you need to do in order to set up a project with
the library. Let's see how it's done.
API Keys
--------
The very first step requires you to obtain a valid Telegram API key (API id/hash pair):
#. Visit https://my.telegram.org/apps and log in with your Telegram Account.
#. Fill out the form to register a new Telegram application.
#. Done! The API key consists of two parts: **api_id** and **api_hash**.
.. important::
The API key is personal and must be kept secret.
.. note::
The API key is unique for each user, but defines a token for a Telegram *application* you are going to build. This
means that you are able to authorize multiple users (and bots too) to access the Telegram database through the
MTProto API by a single API key.
Configuration
-------------
Having the API key from the `previous step <#api-keys>`_ in handy, we can now begin to configure a Pyrogram project.
There are two ways to do so, and you can choose what fits better for you:
- First option (recommended): create a new ``config.ini`` file at the root of your working directory, copy-paste the
following and replace the **api_id** and **api_hash** values with your own. This is the preferred method because
allows you to keep your credentials out of your code without having to deal with how to load them:
.. code-block:: ini
[pyrogram]
api_id = 12345
api_hash = 0123456789abcdef0123456789abcdef
- Alternatively, you can pass your API key to Pyrogram by simply using the *api_id* and *api_hash* parameters of the
Client class. This way you can have full control on how to store and load your credentials (e.g.:, you can load the
credentials from the environment variables and directly pass the values into Pyrogram):
.. code-block:: python
from pyrogram import Client
app = Client(
"my_account",
api_id=12345,
api_hash="0123456789abcdef0123456789abcdef"
)
.. note::
To keep code snippets clean and concise, from now on it is assumed you are making use of the ``config.ini`` file,
thus, the *api_id* and *api_hash* parameters usage won't be shown anymore.
.. _installed Pyrogram: install.html

View File

@ -0,0 +1,45 @@
Quick Start
===========
The next few steps serve as a quick start for all new Pyrogrammers that want to get something done as fast as possible!
Get Pyrogram Real Fast
----------------------
1. Install Pyrogram with ``pip3 install -U pyrogram``.
2. Get your own Telegram API key from https://my.telegram.org/apps.
3. Open your best text editor and paste the following:
.. code-block:: python
from pyrogram import Client
api_id = 12345
api_hash = "0123456789abcdef0123456789abcdef"
with Client("my_account", api_id, api_hash) as app:
app.send_message("me", "Greetings from **Pyrogram**!")
4. Replace *api_id* and *api_hash* values with your own.
5. Save the file as ``pyro.py``.
6. Run the script with ``python3 pyro.py``
7. Follow the instructions on your terminal to login.
8. Watch Pyrogram send a message to yourself.
9. Join our `community <//t.me/pyrogramchat>`_.
10. Say, "hi!".
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.
Feeling eager? You can take a shortcut to `API Usage <../topics/usage.html>`_ and come back later to learn some more details.

View File

@ -1,72 +0,0 @@
Update Handling
===============
Let's now dive right into the core of the framework.
Updates are events that happen in your Telegram account (incoming messages, new channel posts, new members join, ...)
and 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.
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()
Using Decorators
----------------
A much nicer way to register a MessageHandler is by decorating your callback function with the
:meth:`on_message() <pyrogram.Client.on_message>` decorator, which will still make use of add_handler() under the hood.
.. 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.

View File

@ -1,120 +0,0 @@
Setup
=====
Once you successfully `installed Pyrogram`_, you will still have to follow a few steps before you can actually use
the library to make API calls. This section provides all the information you need in order to set up a project
with Pyrogram.
API Keys
--------
The very first step requires you to obtain a valid Telegram API key (API id/hash pair).
If you already have one you can skip this step, otherwise:
#. Visit https://my.telegram.org/apps and log in with your Telegram Account.
#. Fill out the form to register a new Telegram application.
#. Done. The API key consists of two parts: **App api_id** and **App api_hash**.
.. important::
This API key is personal and must be kept secret.
Configuration
-------------
The API key obtained in the `previous step <#api-keys>`_ defines a token for your application allowing you to access
the Telegram database using the MTProto API — **it is therefore required for all authorizations of both users and bots**.
Having it handy, it's time to configure your Pyrogram project. There are two ways to do so, and you can choose what
fits better for you:
- Create a new ``config.ini`` file at the root of your working directory, copy-paste the following and replace the
**api_id** and **api_hash** values with your own. This is the preferred method because allows you to keep your
credentials out of your code without having to deal with how to load them:
.. code-block:: ini
[pyrogram]
api_id = 12345
api_hash = 0123456789abcdef0123456789abcdef
- Alternatively, you can pass your API key to Pyrogram by simply using the *api_id* and *api_hash* parameters of the
Client class. This way you can have full control on how to store and load your credentials:
.. code-block:: python
from pyrogram import Client
app = Client(
"my_account",
api_id=12345,
api_hash="0123456789abcdef0123456789abcdef"
)
.. note::
From now on, the code snippets assume you are using the ``config.ini`` file, thus they won't show the *api_id* and
*api_hash* parameters usage to keep them as clean as possible.
User Authorization
------------------
In order to use the API, Telegram requires that users be authorized via their phone numbers.
Pyrogram automatically manages this access, all you need to do is create an instance of the
:class:`Client <pyrogram.Client>` class by passing to it a ``session_name`` of your choice (e.g.: "my_account") and call
the :meth:`run() <pyrogram.Client.run>` method:
.. code-block:: python
from pyrogram import Client
app = Client("my_account")
app.run()
This starts an interactive shell asking you to input your **phone number** (including your `Country Code`_)
and the **phone code** you will receive:
.. code-block:: text
Enter phone number: +39**********
Is "+39**********" correct? (y/n): y
Enter phone code: 32768
Logged in successfully as Dan
After successfully authorizing yourself, a new file called ``my_account.session`` will be created allowing Pyrogram
executing API calls with your identity. This file will be loaded again when you restart your app, and as long as you
keep the session alive, Pyrogram won't ask you again to enter your phone number.
.. important::
Your ``*.session`` files are personal and must be kept secret.
.. note::
The code above does nothing except asking for credentials and keeping the client online, hit ``CTRL+C`` now to stop
your application and keep reading.
Bot Authorization
-----------------
Bots are a special kind of users that are authorized via their tokens (instead of phone numbers), which are created by
BotFather_. Bot tokens replace the users' phone numbers only — you still need to
`configure a Telegram API key <#configuration>`_ with Pyrogram, even when using bots.
The authorization process is automatically managed. All you need to do is choose a ``session_name`` (can be anything,
usually your bot username) and pass your bot token using the ``bot_token`` parameter. The session file will be named
after the session name, which will be ``pyrogrambot.session`` for the example below.
.. code-block:: python
from pyrogram import Client
app = Client(
"pyrogrambot",
bot_token="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
)
app.run()
.. _installed Pyrogram: Installation.html
.. _`Country Code`: https://en.wikipedia.org/wiki/List_of_country_calling_codes
.. _BotFather: https://t.me/botfather

View File

@ -1,51 +0,0 @@
Usage
=====
Having your `project set up`_ and your account authorized_, it's time to start playing with the API. Let's start!
High-level API
--------------
The easiest and recommended way to interact with Telegram is via the high-level Pyrogram methods_ and types_, which are
named after the `Telegram Bot API`_.
Here's a simple example:
.. code-block:: python
from pyrogram import Client
app = Client("my_account")
app.start()
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")
app.stop()
You can also use Pyrogram 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:
.. 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 on `GitHub <https://github.com/pyrogram/pyrogram/tree/develop/examples>`_.
.. _project set up: Setup.html
.. _authorized: Setup.html#user-authorization
.. _Telegram Bot API: https://core.telegram.org/bots/api
.. _methods: ../pyrogram/Client.html#messages
.. _types: ../pyrogram/Types.html

View File

@ -151,9 +151,9 @@ Continue Propagation
As opposed to `stopping the update propagation <#stop-propagation>`_ and also as an alternative to the As opposed to `stopping the update propagation <#stop-propagation>`_ and also as an alternative to the
`handler groups <#handler-groups>`_, you can signal the internal dispatcher to continue the update propagation within `handler groups <#handler-groups>`_, you can signal the internal dispatcher to continue the update propagation within
**the same group** regardless of the next handler's filters. This allows you to register multiple handlers with **the same group** despite having conflicting filters in the next registered handler. This allows you to register
overlapping filters in the same group; to let the dispatcher process the next handler you can do *one* of the following multiple handlers with overlapping filters in the same group; to let the dispatcher process the next handler you can do
in each handler you want to grant permission to continue: *one* of the following in each handler you want to grant permission to continue:
- Call the update's bound-method ``.continue_propagation()`` (preferred way). - Call the update's bound-method ``.continue_propagation()`` (preferred way).
- Manually ``raise ContinuePropagation`` exception (more suitable for raw updates only). - Manually ``raise ContinuePropagation`` exception (more suitable for raw updates only).

View File

@ -0,0 +1,109 @@
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

@ -0,0 +1,85 @@
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

View File

@ -26,7 +26,7 @@ from ...ext import BaseClient
class GetUsers(BaseClient): class GetUsers(BaseClient):
def get_users( def get_users(
self, self,
user_ids: Iterable[Union[int, str]] user_ids: Union[Iterable[Union[int, str]], int, str]
) -> Union["pyrogram.User", List["pyrogram.User"]]: ) -> Union["pyrogram.User", List["pyrogram.User"]]:
"""Use this method to get information about a user. """Use this method to get information about a user.
You can retrieve up to 200 users at once. You can retrieve up to 200 users at once.