46 lines
1.5 KiB
ReStructuredText
46 lines
1.5 KiB
ReStructuredText
Update Handling
|
|
===============
|
|
|
|
Updates are events that happen in your Telegram account (incoming messages, new channel posts, user name changes, ...)
|
|
and can be handled by using a callback function, that is, a function called every time an ``Update`` is received from
|
|
Telegram.
|
|
|
|
To set an update handler simply call :obj:`set_update_handler <pyrogram.Client.set_update_handler>`
|
|
by passing the name of your defined callback function as argument *before* you start the Client.
|
|
|
|
Here's a complete example on how to set it up:
|
|
|
|
.. code-block:: python
|
|
|
|
from pyrogram import Client
|
|
|
|
|
|
def callback(update):
|
|
print(update)
|
|
|
|
|
|
client = Client(session_name="example")
|
|
client.set_update_handler(callback)
|
|
|
|
client.start()
|
|
client.idle()
|
|
|
|
The last line, :obj:`client.idle() <pyrogram.Client.idle>` is not strictly necessary but highly recommended;
|
|
it will block your script execution until you press :obj:`CTRL`:obj:`C` and automatically call the
|
|
:obj:`stop <pyrogram.Client.stop>` method which stops the Client and gently close the underlying connection.
|
|
|
|
Examples
|
|
--------
|
|
|
|
- Echo:
|
|
|
|
.. code-block:: python
|
|
|
|
from pyrogram.api import types
|
|
|
|
def callback(update):
|
|
if isinstance(update, types.UpdateShortMessage) and not update.out:
|
|
client.send_message(update.user_id, update.message)
|
|
|
|
This checks if the update type is :obj:`UpdateShortMessage <pyrogram.api.types.UpdateShortMessage>` and that the
|
|
update is not generated by yourself (i.e., the message is not outgoing), then sends back the same message. |