2
0
mirror of https://github.com/pyrogram/pyrogram synced 2025-08-22 09:57:19 +00:00
2
Update Handling
Dan edited this page 2017-12-25 13:32:07 +01:00

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 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:

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, client.idle() is not strictly necessary but highly recommended; it will block your script execution until you press CTRLC and automatically call the stop method which stops the Client and gently close the underlying connection.

Examples

  • Echo:

    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 UpdateShortMessage and that the update is not generated by yourself (i.e., the message is not outgoing), then sends back the same message.