Update Events

Every event (builder) subclasses common.EventBuilder, so all the methods in it can be used from any event builder/event instance.

class telethon.events.common.EventBuilder(chats=None, *, blacklist_chats=False, func=None)

Bases: abc.ABC

The common event builder, with builtin support to filter per chat.

Args:
chats (entity, optional):
May be one or more entities (username/peer/etc.), preferably IDs. By default, only matching chats will be handled.
blacklist_chats (bool, optional):
Whether to treat the chats as a blacklist instead of as a whitelist (default). This means that every chat will be handled except those specified in chats which will be ignored if blacklist_chats=True.
func (callable, optional):

A callable function that should accept the event as input parameter, and return a value indicating whether the event should be dispatched or not (any truthy value will do, it does not need to be a bool). It works like a custom filter:

@client.on(events.NewMessage(func=lambda e: e.is_private))
async def handler(event):
    pass  # code here
__weakref__

list of weak references to the object (if defined)

classmethod build(update, others=None, self_id=None)

Builds an event for the given update if possible, or returns None.

others are the rest of updates that came in the same container as the current update.

self_id should be the current user’s ID, since it is required for some events which lack this information but still need it.

filter(event)

If the ID of event._chat_peer isn’t in the chats set (or it is but the set is a blacklist) returns None, otherwise the event.

The events must have been resolved before this can be called.

resolve(client)

Helper method to allow event builders to be resolved before usage

class telethon.events.common.EventCommon(chat_peer=None, msg_id=None, broadcast=None)

Bases: telethon.tl.custom.chatgetter.ChatGetter, abc.ABC

Intermediate class with common things to all events.

Remember that this class implements ChatGetter which means you have access to all chat properties and methods.

In addition, you can access the original_update field which contains the original Update.

__str__()

Return str(self).

client

The telethon.TelegramClient that created this event.

stringify()
to_dict()
telethon.events.common.name_inner_event(cls)

Decorator to rename cls.Event ‘Event’ as ‘cls.Event’

class telethon.events.newmessage.NewMessage(chats=None, *, blacklist_chats=False, func=None, incoming=None, outgoing=None, from_users=None, forwards=None, pattern=None)

Bases: telethon.events.common.EventBuilder

Occurs whenever a new text message or a message with media arrives.

Args:
incoming (bool, optional):
If set to True, only incoming messages will be handled. Mutually exclusive with outgoing (can only set one of either).
outgoing (bool, optional):
If set to True, only outgoing messages will be handled. Mutually exclusive with incoming (can only set one of either).
from_users (entity, optional):
Unlike chats, this parameter filters the senders of the message. That is, only messages sent by these users will be handled. Use chats if you want private messages with this/these users. from_users lets you filter by messages sent by one or more users across the desired chats (doesn’t need a list).
forwards (bool, optional):
Whether forwarded messages should be handled or not. By default, both forwarded and normal messages are included. If it’s True only forwards will be handled. If it’s False only messages that are not forwards will be handled.
pattern (str, callable, Pattern, optional):
If set, only messages matching this pattern will be handled. You can specify a regex-like string which will be matched against the message, a callable function that returns True if a message is acceptable, or a compiled regex pattern.
class Event(message)

Bases: telethon.events.common.EventCommon

Represents the event of a new message. This event can be treated to all effects as a Message, so please refer to its documentation to know what you can do with this event.

Members:
message (Message):

This is the only difference with the received Message, and will return the telethon.tl.custom.message.Message itself, not the text.

See Message for the rest of available members and methods.

pattern_match (obj):

The resulting object from calling the passed pattern function. Here’s an example using a string (defaults to regex match):

>>> from telethon import TelegramClient, events
>>> client = TelegramClient(...)
>>>
>>> @client.on(events.NewMessage(pattern=r'hi (\w+)!'))
... async def handler(event):
...     # In this case, the result is a ``Match`` object
...     # since the `str` pattern was converted into
...     # the ``re.compile(pattern).match`` function.
...     print('Welcomed', event.pattern_match.group(1))
...
>>>
__getattr__(item)
__setattr__(name, value)

Implement setattr(self, name, value).

classmethod build(update, others=None, self_id=None)

Builds an event for the given update if possible, or returns None.

others are the rest of updates that came in the same container as the current update.

self_id should be the current user’s ID, since it is required for some events which lack this information but still need it.

filter(event)

If the ID of event._chat_peer isn’t in the chats set (or it is but the set is a blacklist) returns None, otherwise the event.

The events must have been resolved before this can be called.

class telethon.events.chataction.ChatAction(chats=None, *, blacklist_chats=False, func=None)

Bases: telethon.events.common.EventBuilder

Occurs whenever a user joins or leaves a chat, or a message is pinned.

class Event(where, new_pin=None, new_photo=None, added_by=None, kicked_by=None, created=None, users=None, new_title=None, unpin=None)

Bases: telethon.events.common.EventCommon

Represents the event of a new chat action.

Members:
action_message (MessageAction):
The message invoked by this Chat Action.
new_pin (bool):
True if there is a new pin.
new_photo (bool):
True if there’s a new chat photo (or it was removed).
photo (Photo, optional):
The new photo (or None if it was removed).
user_added (bool):
True if the user was added by some other.
user_joined (bool):
True if the user joined on their own.
user_left (bool):
True if the user left on their own.
user_kicked (bool):
True if the user was kicked by some other.
created (bool, optional):
True if this chat was just created.
new_title (str, optional):
The new title string for the chat, if applicable.
unpin (bool):
True if the existing pin gets unpinned.
added_by

The user who added users, if applicable (None otherwise).

delete(*args, **kwargs)

Deletes the chat action message. You’re responsible for checking whether you have the permission to do so, or to except the error otherwise. Shorthand for telethon.client.messages.MessageMethods.delete_messages with entity and message_ids already set.

Does nothing if no message action triggered this event.

get_added_by()

Returns added_by but will make an API call if necessary.

get_input_user()

Returns input_user but will make an API call if necessary.

get_input_users()

Returns input_users but will make an API call if necessary.

get_kicked_by()

Returns kicked_by but will make an API call if necessary.

get_pinned_message()

If new_pin is True, this returns the Message object that was pinned.

get_user()

Returns user but will make an API call if necessary.

get_users()

Returns users but will make an API call if necessary.

input_user

Input version of the self.user property.

input_users

Input version of the self.users property.

kicked_by

The user who kicked users, if applicable (None otherwise).

reply(*args, **kwargs)

Replies to the chat action message (as a reply). Shorthand for telethon.client.messages.MessageMethods.send_message with both entity and reply_to already set.

Has the same effect as respond if there is no message.

respond(*args, **kwargs)

Responds to the chat action message (not as a reply). Shorthand for telethon.client.messages.MessageMethods.send_message with entity already set.

user

The first user that takes part in this action (e.g. joined).

Might be None if the information can’t be retrieved or there is no user taking part.

user_id

Returns the marked signed ID of the first user, if any.

user_ids

Returns the marked signed ID of the users, if any.

users

A list of users that take part in this action (e.g. joined).

Might be empty if the information can’t be retrieved or there are no users taking part.

classmethod build(update, others=None, self_id=None)

Builds an event for the given update if possible, or returns None.

others are the rest of updates that came in the same container as the current update.

self_id should be the current user’s ID, since it is required for some events which lack this information but still need it.

class telethon.events.userupdate.UserUpdate(chats=None, *, blacklist_chats=False, func=None)

Bases: telethon.events.common.EventBuilder

Occurs whenever a user goes online, starts typing, etc.

class Event(user_id, *, status=None, chat_id=None, typing=None)

Bases: telethon.events.common.EventCommon, telethon.tl.custom.sendergetter.SenderGetter

Represents the event of a user update such as gone online, started typing, etc.

Members:
status (UserStatus, optional):

The user status if the update is about going online or offline.

You should check this attribute first before checking any of the seen within properties, since they will all be None if the status is not set.

action (SendMessageAction, optional):

The “typing” action if any the user is performing if any.

You should check this attribute first before checking any of the typing properties, since they will all be None if the action is not set.

audio

True if what’s being recorded/uploaded is an audio.

cancel

True if the action was cancelling other actions.

contact

True if what’s being uploaded (selected) is a contact.

document

True if what’s being uploaded is document.

geo

True if what’s being uploaded is a geo.

get_input_user()

Alias for get_input_sender.

get_user()

Alias for get_sender.

input_user

Alias for input_sender.

last_seen

Exact datetime.datetime when the user was last seen if known.

online

True if the user is currently online,

photo

True if what’s being uploaded is a photo.

playing

True if the action is playing a game.

recently

True if the user was seen within a day.

recording

True if the action is recording something.

round

True if what’s being recorded/uploaded is a round video.

typing

True if the action is typing a message.

until

The datetime.datetime until when the user should appear online.

uploading

True if the action is uploading something.

user

Alias for sender.

user_id

Alias for sender_id.

video

True if what’s being recorded/uploaded is an video.

within_months

True if the user was seen within 30 days.

within_weeks

True if the user was seen within 7 days.

classmethod build(update, others=None, self_id=None)

Builds an event for the given update if possible, or returns None.

others are the rest of updates that came in the same container as the current update.

self_id should be the current user’s ID, since it is required for some events which lack this information but still need it.

class telethon.events.messageedited.MessageEdited(chats=None, *, blacklist_chats=False, func=None, incoming=None, outgoing=None, from_users=None, forwards=None, pattern=None)

Bases: telethon.events.newmessage.NewMessage

Occurs whenever a message is edited. Just like NewMessage, you should treat this event as a Message.

Warning

On channels, Message.out will be True if you sent the message originally, not if you edited it! This can be dangerous if you run outgoing commands on edits.

Some examples follow:

  • You send a message “A”, out is True.
  • You edit “A” to “B”, out is True.
  • Someone else edits “B” to “C”, out is True (be careful!).
  • Someone sends “X”, out is False.
  • Someone edits “X” to “Y”, out is False.
  • You edit “Y” to “Z”, out is False.

Since there are useful cases where you need the right out value, the library cannot do anything automatically to help you. Instead, consider using from_users='me' (it won’t work in broadcast channels at all since the sender is the channel and not you).

class Event(message)

Bases: telethon.events.newmessage.Event

classmethod build(update, others=None, self_id=None)

Builds an event for the given update if possible, or returns None.

others are the rest of updates that came in the same container as the current update.

self_id should be the current user’s ID, since it is required for some events which lack this information but still need it.

class telethon.events.messagedeleted.MessageDeleted(chats=None, *, blacklist_chats=False, func=None)

Bases: telethon.events.common.EventBuilder

Occurs whenever a message is deleted. Note that this event isn’t 100% reliable, since Telegram doesn’t always notify the clients that a message was deleted.

Important

Telegram does not send information about where a message was deleted if it occurs in private conversations with other users or in small group chats, because message IDs are unique and you can identify the chat with the message ID alone if you saved it previously.

Telethon does not save information of where messages occur, so it cannot know in which chat a message was deleted (this will only work in channels, where the channel ID is present).

This means that the chats= parameter will not work reliably, unless you intend on working with channels and super-groups only.

class Event(deleted_ids, peer)

Bases: telethon.events.common.EventCommon

classmethod build(update, others=None, self_id=None)

Builds an event for the given update if possible, or returns None.

others are the rest of updates that came in the same container as the current update.

self_id should be the current user’s ID, since it is required for some events which lack this information but still need it.

class telethon.events.messageread.MessageRead(chats=None, *, blacklist_chats=False, func=None, inbox=False)

Bases: telethon.events.common.EventBuilder

Occurs whenever one or more messages are read in a chat.

Args:
inbox (bool, optional):
If this argument is True, then when you read someone else’s messages the event will be fired. By default (False) only when messages you sent are read by someone else will fire it.
class Event(peer=None, max_id=None, out=False, contents=False, message_ids=None)

Bases: telethon.events.common.EventCommon

Represents the event of one or more messages being read.

Members:
max_id (int):
Up to which message ID has been read. Every message with an ID equal or lower to it have been read.
outbox (bool):
True if someone else has read your messages.
contents (bool):
True if what was read were the contents of a message. This will be the case when e.g. you play a voice note. It may only be set on inbox events.
__contains__(message)

True if the message(s) are read message.

get_messages()

Returns the list of Message which contents’ were read.

Use is_read() if you need to check whether a message was read instead checking if it’s in here.

inbox

True if you have read someone else’s messages.

is_read(message)

Returns True if the given message (or its ID) has been read.

If a list-like argument is provided, this method will return a list of booleans indicating which messages have been read.

message_ids

The IDs of the messages which contents’ were read.

Use is_read() if you need to check whether a message was read instead checking if it’s in here.

classmethod build(update, others=None, self_id=None)

Builds an event for the given update if possible, or returns None.

others are the rest of updates that came in the same container as the current update.

self_id should be the current user’s ID, since it is required for some events which lack this information but still need it.

filter(event)

If the ID of event._chat_peer isn’t in the chats set (or it is but the set is a blacklist) returns None, otherwise the event.

The events must have been resolved before this can be called.

class telethon.events.callbackquery.CallbackQuery(chats=None, *, blacklist_chats=False, func=None, data=None, pattern=None)

Bases: telethon.events.common.EventBuilder

Occurs whenever you sign in as a bot and a user clicks one of the inline buttons on your messages.

Note that the chats parameter will not work with normal IDs or peers if the clicked inline button comes from a “via bot” message. The chats parameter also supports checking against the chat_instance which should be used for inline callbacks.

Args:
data (bytes, str, callable, optional):
If set, the inline button payload data must match this data. A UTF-8 string can also be given, a regex or a callable. For instance, to check against 'data_1' and 'data_2' you can use re.compile(b'data_').
pattern (bytes, str, callable, Pattern, optional):
If set, only buttons with payload matching this pattern will be handled. You can specify a regex-like string which will be matched against the payload data, a callable function that returns True if a the payload data is acceptable, or a compiled regex pattern.
class Event(query, peer, msg_id)

Bases: telethon.events.common.EventCommon, telethon.tl.custom.sendergetter.SenderGetter

Represents the event of a new callback query.

Members:
query (UpdateBotCallbackQuery):
The original UpdateBotCallbackQuery.
data_match (obj, optional):
The object returned by the data= parameter when creating the event builder, if any. Similar to pattern_match for the new message event.
pattern_match (obj, optional):
Alias for data_match.
answer(message=None, cache_time=0, *, url=None, alert=False)

Answers the callback query (and stops the loading circle).

Args:
message (str, optional):
The toast message to show feedback to the user.
cache_time (int, optional):
For how long this result should be cached on the user’s client. Defaults to 0 for no cache.
url (str, optional):
The URL to be opened in the user’s client. Note that the only valid URLs are those of games your bot has, or alternatively a ‘t.me/your_bot?start=xyz’ parameter.
alert (bool, optional):
Whether an alert (a pop-up dialog) should be used instead of showing a toast. Defaults to False.
chat_instance

Unique identifier for the chat where the callback occurred. Useful for high scores in games.

data

Returns the data payload from the original inline button.

delete(*args, **kwargs)

Deletes the message. Shorthand for telethon.client.messages.MessageMethods.delete_messages with entity and message_ids already set.

If you need to delete more than one message at once, don’t use this delete method. Use a telethon.client.telegramclient.TelegramClient instance directly.

This method also creates a task to answer the callback.

This method will likely fail if via_inline is True.

edit(*args, **kwargs)

Edits the message. Shorthand for telethon.client.messages.MessageMethods.edit_message with the entity set to the correct InputBotInlineMessageID.

Returns True if the edit was successful.

This method also creates a task to answer the callback.

Note

This method won’t respect the previous message unlike Message.edit, since the message object is normally not present.

get_message()

Returns the message to which the clicked inline button belongs.

id

Returns the query ID. The user clicking the inline button is the one who generated this random ID.

message_id

Returns the message ID to which the clicked inline button belongs.

reply(*args, **kwargs)

Replies to the message (as a reply). Shorthand for telethon.client.messages.MessageMethods.send_message with both entity and reply_to already set.

This method also creates a task to answer the callback.

This method will likely fail if via_inline is True.

respond(*args, **kwargs)

Responds to the message (not as a reply). Shorthand for telethon.client.messages.MessageMethods.send_message with entity already set.

This method also creates a task to answer the callback.

This method will likely fail if via_inline is True.

via_inline

Whether this callback was generated from an inline button sent via an inline query or not. If the bot sent the message itself with buttons, and one of those is clicked, this will be False. If a user sent the message coming from an inline query to the bot, and one of those is clicked, this will be True.

If it’s True, it’s likely that the bot is not in the chat, so methods like respond or delete won’t work (but edit will always work).

classmethod build(update, others=None, self_id=None)

Builds an event for the given update if possible, or returns None.

others are the rest of updates that came in the same container as the current update.

self_id should be the current user’s ID, since it is required for some events which lack this information but still need it.

filter(event)

If the ID of event._chat_peer isn’t in the chats set (or it is but the set is a blacklist) returns None, otherwise the event.

The events must have been resolved before this can be called.

class telethon.events.inlinequery.InlineQuery(users=None, *, blacklist_users=False, func=None, pattern=None)

Bases: telethon.events.common.EventBuilder

Occurs whenever you sign in as a bot and a user sends an inline query such as @bot query.

Args:
users (entity, optional):
May be one or more entities (username/peer/etc.), preferably IDs. By default, only inline queries from these users will be handled.
blacklist_users (bool, optional):
Whether to treat the users as a blacklist instead of as a whitelist (default). This means that every chat will be handled except those specified in users which will be ignored if blacklist_users=True.
pattern (str, callable, Pattern, optional):
If set, only queries matching this pattern will be handled. You can specify a regex-like string which will be matched against the message, a callable function that returns True if a message is acceptable, or a compiled regex pattern.
class Event(query)

Bases: telethon.events.common.EventCommon, telethon.tl.custom.sendergetter.SenderGetter

Represents the event of a new callback query.

Members:
query (UpdateBotCallbackQuery):

The original UpdateBotCallbackQuery.

Make sure to access the text of the query if that’s what you want instead working with this.

pattern_match (obj, optional):
The resulting object from calling the passed pattern function, which is re.compile(...).match by default.
answer(results=None, cache_time=0, *, gallery=False, next_offset=None, private=False, switch_pm=None, switch_pm_param='')

Answers the inline query with the given results.

Args:
results (list, optional):

A list of InputBotInlineResult to use. You should use builder to create these:

builder = inline.builder
r1 = builder.article('Be nice', text='Have a nice day')
r2 = builder.article('Be bad', text="I don't like you")
await inline.answer([r1, r2])

You can send up to 50 results as documented in https://core.telegram.org/bots/api#answerinlinequery. Sending more will raise ResultsTooMuchError, and you should consider using next_offset to paginate them.

cache_time (int, optional):
For how long this result should be cached on the user’s client. Defaults to 0 for no cache.
gallery (bool, optional):
Whether the results should show as a gallery (grid) or not.
next_offset (str, optional):
The offset the client will send when the user scrolls the results and it repeats the request.
private (bool, optional):
Whether the results should be cached by Telegram (not private) or by the user’s client (private).
switch_pm (str, optional):
If set, this text will be shown in the results to allow the user to switch to private messages.
switch_pm_param (str, optional):
Optional parameter to start the bot with if switch_pm was used.

Example:

@bot.on(events.InlineQuery)
async def handler(event):
    builder = event.builder

    rev_text = event.text[::-1]
    await event.answer([
        builder.article('Reverse text', text=rev_text),
        builder.photo('/path/to/photo.jpg')
    ])
builder

Returns a new InlineBuilder instance.

geo

If the user location is requested when using inline mode and the user’s device is able to send it, this will return the GeoPoint with the position of the user.

id

Returns the unique identifier for the query ID.

offset

The string the user’s client used as an offset for the query. This will either be empty or equal to offsets passed to answer.

text

Returns the text the user used to make the inline query.

classmethod build(update, others=None, self_id=None)

Builds an event for the given update if possible, or returns None.

others are the rest of updates that came in the same container as the current update.

self_id should be the current user’s ID, since it is required for some events which lack this information but still need it.

filter(event)

If the ID of event._chat_peer isn’t in the chats set (or it is but the set is a blacklist) returns None, otherwise the event.

The events must have been resolved before this can be called.

class telethon.events.album.Album(chats=None, *, blacklist_chats=False, func=None)

Bases: telethon.events.common.EventBuilder

Occurs whenever you receive an album. This event only exists to ease dealing with an unknown amount of messages that belong to the same album.

class Event(messages)

Bases: telethon.events.common.EventCommon, telethon.tl.custom.sendergetter.SenderGetter

Represents the event of a new album.

Members:
messages (Sequence[Message]):
The list of messages belonging to the same album.
__getitem__(n)

Access the n’th message in the album.

Equivalent to event.messages[n].

__iter__()

Iterate over the messages in the album.

Equivalent to iter(self.messages).

__len__()

Return the amount of messages in the album.

Equivalent to len(self.messages).

delete(*args, **kwargs)

Deletes the entire album. You’re responsible for checking whether you have the permission to do so, or to except the error otherwise. Shorthand for telethon.client.messages.MessageMethods.delete_messages with entity and message_ids already set.

edit(*args, **kwargs)

Edits the first caption or the message, or the first messages’ caption if no caption is set, iff it’s outgoing. Shorthand for telethon.client.messages.MessageMethods.edit_message with both entity and message already set.

Returns None if the message was incoming, or the edited Message otherwise.

Note

This is different from client.edit_message and will respect the previous state of the message. For example, if the message didn’t have a link preview, the edit won’t add one by default, and you should force it by setting it to True if you want it.

This is generally the most desired and convenient behaviour, and will work for link previews and message buttons.

forward

The Forward information for the first message in the album if it was forwarded.

forward_to(*args, **kwargs)

Forwards the entire album. Shorthand for telethon.client.messages.MessageMethods.forward_messages with both messages and from_peer already set.

get_reply_message()

The Message that this album is replying to, or None.

The result will be cached after its first use.

grouped_id

The shared grouped_id between all the messages.

is_reply

True if the album is a reply to some other message.

Remember that you can access the ID of the message this one is replying to through reply_to_msg_id, and the Message object with get_reply_message().

mark_read()

Marks the entire album as read. Shorthand for client.send_read_acknowledge() with both entity and message already set.

pin(*, notify=False)

Pins the first photo in the album. Shorthand for telethon.client.messages.MessageMethods.pin_message with both entity and message already set.

raw_text

The raw message text of the first photo with a caption, ignoring any formatting.

reply(*args, **kwargs)

Replies to the first photo in the album (as a reply). Shorthand for telethon.client.messages.MessageMethods.send_message with both entity and reply_to already set.

respond(*args, **kwargs)

Responds to the album (not as a reply). Shorthand for telethon.client.messages.MessageMethods.send_message with entity already set.

text

The message text of the first photo with a caption, formatted using the client’s default parse mode.

classmethod build(update, others=None, self_id=None)

Builds an event for the given update if possible, or returns None.

others are the rest of updates that came in the same container as the current update.

self_id should be the current user’s ID, since it is required for some events which lack this information but still need it.

class telethon.events.raw.Raw(types=None, *, func=None)

Bases: telethon.events.common.EventBuilder

Raw events are not actual events. Instead, they are the raw Update object that Telegram sends. You normally shouldn’t need these.

Args:
types (list | tuple | type, optional):
The type or types that the Update instance must be. Equivalent to if not isinstance(update, types): return.
classmethod build(update, others=None, self_id=None)

Builds an event for the given update if possible, or returns None.

others are the rest of updates that came in the same container as the current update.

self_id should be the current user’s ID, since it is required for some events which lack this information but still need it.

filter(event)

If the ID of event._chat_peer isn’t in the chats set (or it is but the set is a blacklist) returns None, otherwise the event.

The events must have been resolved before this can be called.

resolve(client)

Helper method to allow event builders to be resolved before usage

exception telethon.events.StopPropagation

Bases: Exception

If this exception is raised in any of the handlers for a given event, it will stop the execution of all other registered event handlers. It can be seen as the StopIteration in a for loop but for events.

Example usage:

>>> from telethon import TelegramClient, events
>>> client = TelegramClient(...)
>>>
>>> @client.on(events.NewMessage)
... async def delete(event):
...     await event.delete()
...     # No other event handler will have a chance to handle this event
...     raise StopPropagation
...
>>> @client.on(events.NewMessage)
... async def _(event):
...     # Will never be reached, because it is the second handler
...     pass
__weakref__

list of weak references to the object (if defined)

telethon.events.is_handler(callback)

Returns True if the given callback is an event handler (i.e. you used register on it).

telethon.events.list(callback)

Returns a list containing the registered event builders inside the specified callback handler.

telethon.events.register(event=None)

Decorator method to register event handlers. This is the client-less add_event_handler() variant.

Note that this method only registers callbacks as handlers, and does not attach them to any client. This is useful for external modules that don’t have access to the client, but still want to define themselves as a handler. Example:

>>> from telethon import events
>>> @events.register(events.NewMessage)
... async def handler(event):
...     ...
...
>>> # (somewhere else)
...
>>> from telethon import TelegramClient
>>> client = TelegramClient(...)
>>> client.add_event_handler(handler)

Remember that you can use this as a non-decorator through register(event)(callback).

Args:
event (_EventBuilder | type):
The event builder class or instance to be used, for instance events.NewMessage.
telethon.events.unregister(callback, event=None)

Inverse operation of register (though not a decorator). Client-less remove_event_handler variant. Note that this won’t remove handlers from the client, because it simply can’t, so you would generally use this before adding the handlers to the client.

This method is here for symmetry. You will rarely need to unregister events, since you can simply just not add them to any client.

If no event is given, all events for this callback are removed. Returns how many callbacks were removed.