pyrogram/docs/source/resources/UpdateHandling.rst

60 lines
1.8 KiB
ReStructuredText
Raw Normal View History

2018-01-06 11:18:15 +00:00
Update Handling
===============
2018-04-12 11:43:16 +00:00
Updates are events that happen in your Telegram account (incoming messages, new channel posts, new members join, ...)
2018-08-19 15:25:09 +00:00
and can be handled by registering one or more callback functions in your app by using an `Handler <../pyrogram/Handlers.html>`_.
2018-04-16 17:48:50 +00:00
2018-08-19 15:25:09 +00:00
To put it simply, whenever an update is received from Telegram it will be dispatched and your previously defined callback
function(s) will be called back with the update itself as argument.
2018-01-06 11:18:15 +00:00
2018-04-11 21:18:17 +00:00
Registering an Handler
----------------------
2018-01-06 11:18:15 +00:00
2018-08-19 15:25:09 +00:00
To explain how `Handlers <../pyrogram/Handlers.html>`_ 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.
2018-04-11 21:18:17 +00:00
2018-01-06 11:18:15 +00:00
2018-08-19 15:25:09 +00:00
Using Decorators
2018-04-12 11:43:16 +00:00
----------------
2018-08-19 15:25:09 +00:00
The easiest and nicest way to register a MessageHandler is by decorating your function with the
:meth:`on_message() <pyrogram.Client.on_message>` decorator. Here's a full example that prints out the content
of a message as soon as it arrives.
2018-04-12 11:43:16 +00:00
.. code-block:: python
2018-08-19 15:25:09 +00:00
from pyrogram import Client
2018-04-12 11:43:16 +00:00
2018-08-19 15:25:09 +00:00
app = Client("my_account")
2018-04-12 11:43:16 +00:00
2018-08-19 15:25:09 +00:00
@app.on_message()
def my_handler(client, message):
print(message)
2018-04-16 17:48:50 +00:00
2018-08-19 15:25:09 +00:00
app.run()
2018-04-16 17:48:50 +00:00
2018-08-19 15:25:09 +00:00
Using add_handler()
-------------------
2018-04-16 17:48:50 +00:00
2018-08-19 15:25:09 +00:00
If you prefer not to use decorators for any reason, there is an alternative way for registering Handlers.
This is useful, for example, when you want to keep your callback functions in separate files.
2018-04-16 17:48:50 +00:00
.. code-block:: python
2018-08-19 15:25:09 +00:00
from pyrogram import Client, MessageHandler
2018-04-16 17:48:50 +00:00
2018-08-19 15:25:09 +00:00
def my_handler(client, message):
print(message)
2018-04-16 17:48:50 +00:00
2018-08-19 15:25:09 +00:00
app = Client("my_account")
2018-04-16 17:48:50 +00:00
2018-08-19 15:25:09 +00:00
app.add_handler(MessageHandler(my_handler))
2018-04-16 17:48:50 +00:00
2018-08-19 15:25:09 +00:00
app.run()