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

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 (async or not) 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
__annotations__ = {}
__weakref__

list of weak references to the object (if defined)

abstract 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)

Returns a truthy value if the event passed the filter and should be used, or falsy otherwise. The return value may need to be awaited.

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

async 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: ChatGetter, 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.

__annotations__ = {}
__str__()

Return str(self).

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

Example
import asyncio
from telethon import events

@client.on(events.NewMessage(pattern='(?i)hello.+'))
async def handler(event):
    # Respond whenever someone says "Hello" and something else
    await event.reply('Hey!')

@client.on(events.NewMessage(outgoing=True, pattern='!ping'))
async def handler(event):
    # Say "!pong" whenever you send "!ping", then delete both messages
    m = await event.respond('!pong')
    await asyncio.sleep(5)
    await client.delete_messages(event.chat_id, [event.id, m.id])
class Event(message)

Bases: 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))
...
>>>
__annotations__ = {}
__getattr__(item)
__setattr__(name, value)

Implement setattr(self, name, value).

__annotations__ = {}
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)

Returns a truthy value if the event passed the filter and should be used, or falsy otherwise. The return value may need to be awaited.

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

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

Bases: EventBuilder

Occurs on certain chat actions:

  • Whenever a new chat is created.

  • Whenever a chat’s title or photo is changed or removed.

  • Whenever a new message is pinned.

  • Whenever a user scores in a game.

  • Whenever a user joins or is added to the group.

  • Whenever a user is removed or leaves a group if it has less than 50 members or the removed user was a bot.

Note that “chat” refers to “small group, megagroup and broadcast channel”, whereas “group” refers to “small group and megagroup” only.

Example
from telethon import events

@client.on(events.ChatAction)
async def handler(event):
    # Welcome every new user
    if event.user_joined:
        await event.reply('Welcome to the group!')
class Event(where, new_photo=None, added_by=None, kicked_by=None, created=None, users=None, new_title=None, pin_ids=None, pin=None, new_score=None)

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

new_score (str, optional):

The new score string for the game, if applicable.

unpin (bool):

True if the existing pin gets unpinned.

__annotations__ = {}
property added_by

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

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

async get_added_by()

Returns added_by but will make an API call if necessary.

async get_input_user()

Returns input_user but will make an API call if necessary.

async get_input_users()

Returns input_users but will make an API call if necessary.

async get_kicked_by()

Returns kicked_by but will make an API call if necessary.

async get_pinned_message()

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

async get_pinned_messages()

If new_pin is True, this returns a list of Message objects that were pinned.

async get_user()

Returns user but will make an API call if necessary.

async get_users()

Returns users but will make an API call if necessary.

property input_user

Input version of the self.user property.

property input_users

Input version of the self.users property.

property kicked_by

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

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

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

property user

The first user that takes part in this action. For example, who joined.

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

property user_id

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

property user_ids

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

property users

A list of users that take part in this action. For example, who joined.

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

__annotations__ = {}
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: EventBuilder

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

Example
from telethon import events

@client.on(events.UserUpdate)
async def handler(event):
    # If someone is uploading, say something
    if event.uploading:
        await client.send_message(event.user_id, 'What are you sending?')
class Event(peer, *, status=None, chat_peer=None, typing=None)

Bases: EventCommon, 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.

__annotations__ = {}
property audio

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

property cancel

True if the action was cancelling other actions.

property contact

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

property document

True if what’s being uploaded is document.

property geo

True if what’s being uploaded is a geo.

async get_input_user()

Alias for get_input_sender.

async get_user()

Alias for get_sender.

property input_user

Alias for input_sender.

property last_seen

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

property online

True if the user is currently online,

property photo

True if what’s being uploaded is a photo.

property playing

True if the action is playing a game.

property recently

True if the user was seen within a day.

property recording

True if the action is recording something.

property round

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

property sticker

True if what’s being uploaded is a sticker.

property typing

True if the action is typing a message.

property until

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

property uploading

True if the action is uploading something.

property user

Alias for sender.

property user_id

Alias for sender_id.

property video

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

property within_months

True if the user was seen within 30 days.

property within_weeks

True if the user was seen within 7 days.

__annotations__ = {}
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: 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).

Example
from telethon import events

@client.on(events.MessageEdited)
async def handler(event):
    # Log the date of new edits
    print('Message', event.id, 'changed at', event.date)
class Event(message)

Bases: Event

__annotations__ = {}
__annotations__ = {}
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: 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.

Example
from telethon import events

@client.on(events.MessageDeleted)
async def handler(event):
    # Log all deleted message IDs
    for msg_id in event.deleted_ids:
        print('Message', msg_id, 'was deleted in', event.chat_id)
class Event(deleted_ids, peer)

Bases: EventCommon

__annotations__ = {}
__annotations__ = {}
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: 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.

Example
from telethon import events

@client.on(events.MessageRead)
async def handler(event):
    # Log when someone reads your messages
    print('Someone has read all your messages until', event.max_id)

@client.on(events.MessageRead(inbox=True))
async def handler(event):
    # Log when you read message in a chat (from your "inbox")
    print('You have read messages until', event.max_id)
class Event(peer=None, max_id=None, out=False, contents=False, message_ids=None)

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

__annotations__ = {}
__contains__(message)

True if the message(s) are read message.

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

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

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

__annotations__ = {}
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)

Returns a truthy value if the event passed the filter and should be used, or falsy otherwise. The return value may need to be awaited.

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

Example
from telethon import events, Button

# Handle all callback queries and check data inside the handler
@client.on(events.CallbackQuery)
async def handler(event):
    if event.data == b'yes':
        await event.answer('Correct answer!')

# Handle only callback queries with data being b'no'
@client.on(events.CallbackQuery(data=b'no'))
async def handler(event):
    # Pop-up message with alert
    await event.answer('Wrong answer!', alert=True)

# Send a message with buttons users can click
async def main():
    await client.send_message(user, 'Yes or no?', buttons=[
        Button.inline('Yes!', b'yes'),
        Button.inline('Nope', b'no')
    ])
class Event(query, peer, msg_id)

Bases: EventCommon, 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.

__annotations__ = {}
async 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.

property chat_instance

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

property data

Returns the data payload from the original inline button.

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

async edit(*args, **kwargs)

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

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.

async get_message()

Returns the message to which the clicked inline button belongs.

property id

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

property message_id

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

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

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

property 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).

__annotations__ = {}
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)

Returns a truthy value if the event passed the filter and should be used, or falsy otherwise. The return value may need to be awaited.

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

Example
from telethon import events

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

    # Two options (convert user text to UPPERCASE or lowercase)
    await event.answer([
        builder.article('UPPERCASE', text=event.text.upper()),
        builder.article('lowercase', text=event.text.lower()),
    ])
class Event(query)

Bases: EventCommon, SenderGetter

Represents the event of a new callback query.

Members:
query (UpdateBotInlineQuery):

The original UpdateBotInlineQuery.

Make sure to access the text property of the query if you want the text rather than the actual query object.

pattern_match (obj, optional):

The resulting object from calling the passed pattern function, which is re.compile(...).match by default.

__annotations__ = {}
async 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.

See the documentation for builder to know what kind of answers can be given.

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')
    ])
property builder

Returns a new InlineBuilder instance.

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

property id

Returns the unique identifier for the query ID.

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

property text

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

__annotations__ = {}
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)

Returns a truthy value if the event passed the filter and should be used, or falsy otherwise. The return value may need to be awaited.

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

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

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

Example
from telethon import events

@client.on(events.Album)
async def handler(event):
    # Counting how many photos or videos the album has
    print('Got an album with', len(event), 'items')

    # Forwarding the album as a whole to some chat
    event.forward_to(chat)

    # Printing the caption
    print(event.text)

    # Replying to the fifth item in the album
    await event.messages[4].reply('Cool!')
class Event(messages)

Bases: EventCommon, SenderGetter

Represents the event of a new album.

Members:
messages (Sequence[Message]):

The list of messages belonging to the same album.

__annotations__ = {}
__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).

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

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

property forward

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

async forward_to(*args, **kwargs)

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

async get_reply_message()

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

The result will be cached after its first use.

property grouped_id

The shared grouped_id between all the messages.

property 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().

async mark_read()

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

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

property raw_text

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

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

async respond(*args, **kwargs)

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

property text

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

__annotations__ = {}
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)

Returns a truthy value if the event passed the filter and should be used, or falsy otherwise. The return value may need to be awaited.

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

class telethon.events.album.AlbumHack(client, event)

Bases: object

When receiving an album from a different data-center, they will come in separate Updates, so we need to temporarily remember them for a while and only after produce the event.

Of course events are not designed for this kind of wizardy, so this is a dirty hack that gets the job done.

When cleaning up the code base we may want to figure out a better way to do this, or just leave the album problem to the users; the update handling code is bad enough as it is.

__weakref__

list of weak references to the object (if defined)

async deliver_event()
extend(messages)
class telethon.events.raw.Raw(types=None, *, func=None)

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

Example
from telethon import events

@client.on(events.Raw)
async def handler(update):
    # Print all incoming updates
    print(update.stringify())
__annotations__ = {}
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)

Returns a truthy value if the event passed the filter and should be used, or falsy otherwise. The return value may need to be awaited.

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

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