Events and filters
Events
Classes related to the different event types that wrap incoming Telegram updates.
See also
The Updates concept to learn how to listen to these events.
- class telethon.events.ButtonCallback(*args, **kwds)
Bases:
EventOccurs when the user
click()s aCallbackbutton.Only bot accounts can receive this event, because only bots can send
Callbackbuttons.- async answer(text=None, alert=False)
Answer the callback query.
Important
You must call this function for the loading circle to stop on the user’s side.
- class telethon.events.Continue
Bases:
objectThis is not an event type you can listen to.
This is a sentinel value used to signal that the library should Continue calling other handlers.
You can
returnthis from your handlers if you want handlers registered after to also run.The primary use case is having asynchronous filters inside your handler:
from telethon import events @client.on(events.NewMessage) async def admin_only_handler(event): allowed = await database.is_user_admin(event.sender.id) if not allowed: # this user is not allowed, fall-through the handlers return events.Continue @client.on(events.NewMessage) async def everyone_else_handler(event): ... # runs if admin_only_handler was not allowed
- class telethon.events.InlineQuery(*args, **kwds)
Bases:
EventOccurs when users type
@bot queryin their chat box.Only bot accounts can receive this event.
- class telethon.events.MessageDeleted(*args, **kwds)
Bases:
EventOccurs when one or more messages are deleted.
Note
Telegram does not send the contents of the deleted messages. Because they are deleted, it’s also impossible to fetch them.
The chat is only known when the deletion occurs in broadcast channels or supergroups.
- class telethon.events.MessageEdited(*args, **kwds)
-
Occurs when a new message is sent or received.
This event can be treated as the
Messageitself.
- class telethon.events.MessageRead(*args, **kwds)
Bases:
EventOccurs both when your messages are read by others, and when you read messages.
- property max_message_id_read: int
The highest message identifier of the messages that have been marked as read.
In other words, messages with an identifier below or equal (
<=) to this value are considered read. Messages with an identifier higher (>) to this value are considered unread.Example
if message.id <= event.max_message_id_read: print('message is marked as read') else: print('message is not yet marked as read')
- class telethon.events.NewMessage(*args, **kwds)
-
Occurs when a new message is sent or received.
This event can be treated as the
Messageitself.Caution
Messages sent with the
Clientare also caught, so be careful not to enter infinite loops! This is true for all event types, including edits.
- class telethon.events.Raw(*args, **kwds)
Bases:
EventRaw update type received from Telegram.
This event occurs when any update is received.
Like every other event, the raw update type is under the private member
event._raw.Additionally, all peers received along with this update are present under
self._chat_map.
Filters
Filters are functions that accept a single parameter, an Event instance, and return a bool.
When the return value is True, the associated events handler will be invoked.
See also
The Updates concept to learn to combine filters or define your own.
- class telethon.events.filters.All(filter1, filter2, *filters)
Bases:
CombinableCombine multiple filters, returning
Trueif all of the filters pass.When either filter is
Combinable, you can use the&operator instead.from telethon.events.filters import All, Command, Text @bot.on(events.NewMessage, All(Command('/start'), Text(r'\bdata:\w+'))) async def handler(event): ... # equivalent to: @bot.on(events.NewMessage, Command('/start') & Text(r'\bdata:\w+')) async def handler(event): ...
- Parameters:
filter1 (Callable[[Event], bool | Awaitable[bool]] | Combinable) – The first filter to check.
filter2 (Callable[[Event], bool | Awaitable[bool]] | Combinable) – The second filter to check.
filters (Callable[[Event], bool | Awaitable[bool]] | Combinable) – The rest of filters to check.
- class telethon.events.filters.Any(filter1, filter2, *filters)
Bases:
CombinableCombine multiple filters, returning
Trueif any of the filters pass.When either filter is
Combinable, you can use the|operator instead.from telethon.events.filters import Any, Command @bot.on(events.NewMessage, Any(Command('/start'), Command('/help'))) async def handler(event): ... # equivalent to: @bot.on(events.NewMessage, Command('/start') | Command('/help')) async def handler(event): ...
- Parameters:
filter1 (Callable[[Event], bool | Awaitable[bool]] | Combinable) – The first filter to check.
filter2 (Callable[[Event], bool | Awaitable[bool]] | Combinable) – The second filter to check if the first one failed.
filters (Callable[[Event], bool | Awaitable[bool]] | Combinable) – The rest of filters to check if the first and second one failed.
- class telethon.events.filters.ChatType(type)
Bases:
CombinableFilter by chat type using
isinstance().Example
from telethon import events from telethon.events import filters from telethon.types import Channel # Handle only messages from broadcast channels @client.on(events.NewMessage, filters.ChatType(Channel)) async def handler(event): print(event.text)
- class telethon.events.filters.Chats(chat_ids)
Bases:
CombinableFilter by
event.chat.id, if the event has a chat.
- class telethon.events.filters.Command(command)
Bases:
CombinableFilter by
event.textto make sure the first word matches the command or the command + ‘@’ + username, using the username of the logged-in account.For example, if the logged-in account has an username of “bot”, then the filter
Command('/help')will match both"/help"and"/help@bot", but not"/list"or"/help@other".- Parameters:
command (str) – The command to match on.
Note
The leading forward-slash is not automatically added! This allows for using a different prefix or no prefix at all.
Note
The username is taken from the session to avoid network calls. If a custom storage returns the incorrect username, the filter will misbehave. If there is no username, then the
"/help@other"syntax will be ignored.
- class telethon.events.filters.Data(data)
Bases:
CombinableFilter by
event.datausing a full bytes match, used for events such astelethon.events.ButtonCallback.It checks if
event.datais equal to the data passed to the filter.- Parameters:
data (bytes) – Bytes to match data with.
- class telethon.events.filters.Forward
Bases:
CombinableFilter by
event.forward_info, that is, messages that have been forwarded from elsewhere.
- class telethon.events.filters.Incoming
Bases:
CombinableFilter by
event.incoming, that is, messages sent from others to the logged-in account.
- class telethon.events.filters.Media(*types)
Bases:
CombinableFilter by the media type in the message.
By default, this filter will pass if the message has any media.
Note that link previews are only considered media if they have a photo or document.
When you specify one or more media types, only those types will be considered.
You can use literal strings or the constants defined by the filter.
- Parameters:
types (Literal['photo', 'audio', 'video']) – The media types to filter on. This is all of them if none are specified.
- AUDIO = 'audio'
- PHOTO = 'photo'
- VIDEO = 'video'
- class telethon.events.filters.Not(filter)
Bases:
CombinableNegate the output of a single filter, returning
Trueif the nested filter does not pass.When the filter is
Combinable, you can use the~operator instead.from telethon.events.filters import All, Command @bot.on(events.NewMessage, Not(Command('/start')) async def handler(event): ... # equivalent to: @bot.on(events.NewMessage, ~Command('/start')) async def handler(event): ...
- Parameters:
filter (Callable[[Event], bool | Awaitable[bool]] | Combinable) – The filter to negate.
- class telethon.events.filters.Outgoing
Bases:
CombinableFilter by
event.outgoing, that is, messages sent from the logged-in account.This is not a reliable way to check that the update was not produced by the logged-in account in broadcast channels.
- class telethon.events.filters.Reply
Bases:
CombinableFilter by
event.replied_message_id, that is, messages which are a reply to another message.
- class telethon.events.filters.Senders(sender_ids)
Bases:
CombinableFilter by
event.sender.id, if the event has a sender.
- class telethon.events.filters.Text(regexp)
Bases:
CombinableFilter by
event.textusing a regular expression pattern.The pattern is searched on the text anywhere, not matched at the start. Use the
'^'anchor if you want to match the text from the start.The match, if any, is discarded. If you need to access captured groups, you need to manually perform the check inside the handler instead.
Note that the caption text in messages with media is also searched. If you want to filter based on media, use
Media.- Parameters:
regexp (str | re.Pattern[str]) – The regular expression to
re.search()with on the text.