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

Occurs when the user click()s a Callback button.

Only bot accounts can receive this event, because only bots can send Callback buttons.

Parameters:
  • args (Any) –

  • kwds (Any) –

Return type:

Any

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.

Parameters:
  • text (str | None) – The text of the message to display to the user, usually as a toast.

  • alert (bool) – If True, the message will be shown as a pop-up alert that must be dismissed by the user.

Return type:

None

property data: bytes
async get_message()

Get the Message containing the button that was clicked.

If the message is too old and is no longer accessible, None is returned instead.

Return type:

Message | None

class telethon.events.Continue

Bases: object

This 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 return this 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.Event(*args, **kwds)

Bases: object

The base type of all events.

Parameters:
  • args (Any) –

  • kwds (Any) –

Return type:

Any

property client: Client

The Client that received this update.

class telethon.events.InlineQuery(*args, **kwds)

Bases: Event

Occurs when users type @bot query in their chat box.

Only bot accounts can receive this event.

Parameters:
  • args (Any) –

  • kwds (Any) –

Return type:

Any

class telethon.events.MessageDeleted(*args, **kwds)

Bases: Event

Occurs 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.

Parameters:
  • args (Any) –

  • kwds (Any) –

Return type:

Any

property channel_id: int | None

The channel identifier of the supergroup or broadcast channel where the messages were deleted.

This will be None if the messages were deleted anywhere else.

property message_ids: Sequence[int]

The message identifiers of the messages that were deleted.

class telethon.events.MessageEdited(*args, **kwds)

Bases: Event, Message

Occurs when a new message is sent or received.

This event can be treated as the Message itself.

Parameters:
  • args (Any) –

  • kwds (Any) –

Return type:

Any

class telethon.events.MessageRead(*args, **kwds)

Bases: Event

Occurs both when your messages are read by others, and when you read messages.

Parameters:
  • args (Any) –

  • kwds (Any) –

Return type:

Any

property chat: Peer

The peer where the messages were read.

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)

Bases: Event, Message

Occurs when a new message is sent or received.

This event can be treated as the Message itself.

Caution

Messages sent with the Client are also caught, so be careful not to enter infinite loops! This is true for all event types, including edits.

Parameters:
  • args (Any) –

  • kwds (Any) –

Return type:

Any

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

Combine multiple filters, returning True if 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:
property filters: tuple[Callable[[Event], bool], ...]

The filters being checked, in order.

class telethon.events.filters.Any(filter1, filter2, *filters)

Bases: Combinable

Combine multiple filters, returning True if 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]) – The first filter to check.

  • filter2 (Callable[[Event], bool]) – The second filter to check if the first one failed.

  • filters (Callable[[Event], bool]) – The rest of filters to check if the first and second one failed.

property filters: tuple[Callable[[Event], bool], ...]

The filters being checked, in order.

class telethon.events.filters.ChatType(type)

Bases: Combinable

Filter by chat type using isinstance().

Parameters:

type (Type[User | Group | Channel]) – The chat type to filter on.

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)
property type: Type[User | Group | Channel]

The chat type this filter is filtering on.

class telethon.events.filters.Chats(chat_ids)

Bases: Combinable

Filter by event.chat.id, if the event has a chat.

Parameters:

chat_ids (Sequence[int]) – The chat identifiers to filter on.

property chat_ids: set[int]

A copy of the set of chat identifiers this filter is filtering on.

class telethon.events.filters.Command(command)

Bases: Combinable

Filter by event.text to 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: Combinable

Filter by event.data using a full bytes match, used for events such as telethon.events.ButtonCallback.

It checks if event.data is equal to the data passed to the filter.

Parameters:

data (bytes) – Bytes to match data with.

class telethon.events.filters.Forward

Bases: Combinable

Filter by event.forward_info, that is, messages that have been forwarded from elsewhere.

class telethon.events.filters.Incoming

Bases: Combinable

Filter by event.incoming, that is, messages sent from others to the logged-in account.

class telethon.events.filters.Media(*types)

Bases: Combinable

Filter 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'
property types: tuple[Literal['photo', 'audio', 'video'], ...]

The media types being checked.

class telethon.events.filters.Not(filter)

Bases: Combinable

Negate the output of a single filter, returning True if 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]) – The filter to negate.

property filter: Callable[[Event], bool]

The filter being negated.

class telethon.events.filters.Outgoing

Bases: Combinable

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

Filter by event.replied_message_id, that is, messages which are a reply to another message.

class telethon.events.filters.Senders(sender_ids)

Bases: Combinable

Filter by event.sender.id, if the event has a sender.

Parameters:

sender_ids (Sequence[int]) – The sender identifiers to filter on.

property sender_ids: set[int]

A copy of the set of sender identifiers this filter is filtering on.

class telethon.events.filters.Text(regexp)

Bases: Combinable

Filter by event.text using 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.