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 ifblacklist_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
- chats (
-
__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 currentupdate
.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.
-
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 withoutgoing
(can only set one of either). - outgoing (
bool
, optional): - If set to
True
, only outgoing messages will be handled. Mutually exclusive withincoming
(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. Usechats
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’sFalse
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.
- incoming (
- 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:
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 thetelethon.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)) ... >>>
- message (
-
__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 currentupdate
.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:
telethon.events.common.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:
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.
- new_score (
str
, optional): - The new score string for the game, if applicable.
- unpin (
bool
): True
if the existing pin gets unpinned.
-
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
withentity
andmessage_ids
already set.Does nothing if no message action triggered this event.
-
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.
-
input_user
¶ Input version of the
self.user
property.
-
input_users
¶ Input version of the
self.users
property.
-
reply
(*args, **kwargs)¶ Replies to the chat action message (as a reply). Shorthand for
telethon.client.messages.MessageMethods.send_message
with bothentity
andreply_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
withentity
already set.
-
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.
-
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. For example, who 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 currentupdate
.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.
- 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:
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.
-
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.
-
until
¶ The
datetime.datetime
until when the user should appear online.
-
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 currentupdate
.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 aMessage
.Warning
On channels,
Message.out
will beTrue
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 usingfrom_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:
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 currentupdate
.self_id
should be the current user’s ID, since it is required for some events which lack this information but still need it.
- You send a message “A”,
-
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.- 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)¶
-
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 currentupdate
.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:
- 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:
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 oninbox
events.
- max_id (
-
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.
-
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 currentupdate
.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:
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. Thechats
parameter also supports checking against thechat_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 usere.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.
- data (
- 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:
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 topattern_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
.
- message (
-
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
withentity
andmessage_ids
already set.If you need to delete more than one message at once, don’t use this
delete
method. Use atelethon.client.telegramclient.TelegramClient
instance directly.This method also creates a task to
answer
the callback.This method will likely fail if
via_inline
isTrue
.
-
edit
(*args, **kwargs)¶ Edits the message. Shorthand for
telethon.client.messages.MessageMethods.edit_message
with theentity
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.
-
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 bothentity
andreply_to
already set.This method also creates a task to
answer
the callback.This method will likely fail if
via_inline
isTrue
.
-
respond
(*args, **kwargs)¶ Responds to the message (not as a reply). Shorthand for
telethon.client.messages.MessageMethods.send_message
withentity
already set.This method also creates a task to
answer
the callback.This method will likely fail if
via_inline
isTrue
.
-
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 beTrue
.If it’s
True
, it’s likely that the bot is not in the chat, so methods likerespond
ordelete
won’t work (butedit
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 currentupdate
.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:
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 ifblacklist_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.
- users (
- 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:
telethon.events.common.EventCommon
,telethon.tl.custom.sendergetter.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 isre.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.
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 usingnext_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.
- results (
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 currentupdate
.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:
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.
- 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:
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.
- messages (Sequence[
-
__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
withentity
andmessage_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 bothentity
andmessage
already set.Returns
None
if the message was incoming, or the editedMessage
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 toTrue
if you want it.This is generally the most desired and convenient behaviour, and will work for link previews and message buttons.
-
forward_to
(*args, **kwargs)¶ Forwards the entire album. Shorthand for
telethon.client.messages.MessageMethods.forward_messages
with bothmessages
andfrom_peer
already set.
-
get_reply_message
()¶ The
Message
that this album is replying to, orNone
.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 theMessage
object withget_reply_message()
.
-
mark_read
()¶ Marks the entire album as read. Shorthand for
client.send_read_acknowledge()
with bothentity
andmessage
already set.
-
pin
(*, notify=False)¶ Pins the first photo in the album. Shorthand for
telethon.client.messages.MessageMethods.pin_message
with bothentity
andmessage
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 bothentity
andreply_to
already set.
-
respond
(*args, **kwargs)¶ Responds to the album (not as a reply). Shorthand for
telethon.client.messages.MessageMethods.send_message
withentity
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 currentupdate
.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)
-
deliver_event
()¶
-
extend
(messages)¶
-
-
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:
- Example
from telethon import events @client.on(events.Raw) async def handler(update): # Print all incoming updates print(update.stringify())
-
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 currentupdate
.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.
-
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 usedregister
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
.
- event (
-
telethon.events.
unregister
(callback, event=None)¶ Inverse operation of
register
(though not a decorator). Client-lessremove_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.