INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Gets the corresponding class name for the given error code this either being an integer ( thus base error name ) or str. | def _get_class_name(error_code):
"""
Gets the corresponding class name for the given error code,
this either being an integer (thus base error name) or str.
"""
if isinstance(error_code, int):
return KNOWN_BASE_CLASSES.get(
error_code, 'RPCError' + str(error_code).replace('-', 'N... |
Parses the input CSV file with columns ( name error codes description ) and yields Error instances as a result. | def parse_errors(csv_file):
"""
Parses the input CSV file with columns (name, error codes, description)
and yields `Error` instances as a result.
"""
with csv_file.open(newline='') as f:
f = csv.reader(f)
next(f, None) # header
for line, tup in enumerate(f, start=2):
... |
Executes the authentication process with the Telegram servers. | async def do_authentication(sender):
"""
Executes the authentication process with the Telegram servers.
:param sender: a connected `MTProtoPlainSender`.
:return: returns a (authorization key, time offset) tuple.
"""
# Step 1 sending: PQ Request, endianness doesn't matter since it's random
n... |
Gets the specified integer from its byte array. This should be used by this module alone as it works with big endian. | def get_int(byte_array, signed=True):
"""
Gets the specified integer from its byte array.
This should be used by this module alone, as it works with big endian.
:param byte_array: the byte array representing th integer.
:param signed: whether the number is signed or not.
:return: the integer re... |
This decorator turns func into a callback for Tkinter to be able to use even if func is an awaitable coroutine. | def callback(func):
"""
This decorator turns `func` into a callback for Tkinter
to be able to use, even if `func` is an awaitable coroutine.
"""
@functools.wraps(func)
def wrapped(*args, **kwargs):
result = func(*args, **kwargs)
if inspect.iscoroutine(result):
aio_loo... |
Completes the initialization of our application. Since __init__ cannot be async we use this. | async def post_init(self):
"""
Completes the initialization of our application.
Since `__init__` cannot be `async` we use this.
"""
if await self.cl.is_user_authorized():
self.set_signed_in(await self.cl.get_me())
else:
# User is not logged in, con... |
Event handler that will add new messages to the message log. | async def on_message(self, event):
"""
Event handler that will add new messages to the message log.
"""
# We want to show only messages sent to this chat
if event.chat_id != self.chat_id:
return
# Save the message ID so we know which to reply to
self.... |
Note the event argument. This is required since this callback may be called from a widget. bind ( such as <Return > ) which sends information about the event we don t care about. | async def sign_in(self, event=None):
"""
Note the `event` argument. This is required since this callback
may be called from a ``widget.bind`` (such as ``'<Return>'``),
which sends information about the event we don't care about.
This callback logs out if authorized, signs in if ... |
Configures the application as signed in ( displays user s name and disables the entry to input phone/ bot token/ code ). | def set_signed_in(self, me):
"""
Configures the application as "signed in" (displays user's
name and disables the entry to input phone/bot token/code).
"""
self.me = me
self.sign_in_label.configure(text='Signed in')
self.sign_in_entry.configure(state=tkinter.NORMA... |
Sends a message. Does nothing if the client is not connected. | async def send_message(self, event=None):
"""
Sends a message. Does nothing if the client is not connected.
"""
if not self.cl.is_connected():
return
# The user needs to configure a chat where the message should be sent.
#
# If the chat ID does not ex... |
Checks the input chat where to send and listen messages from. | async def check_chat(self, event=None):
"""
Checks the input chat where to send and listen messages from.
"""
if self.me is None:
return # Not logged in yet
chat = self.chat.get().strip()
try:
chat = int(chat)
except ValueError:
... |
The old value from the event. | def old(self):
"""
The old value from the event.
"""
ori = self.original.action
if isinstance(ori, (
types.ChannelAdminLogEventActionChangeAbout,
types.ChannelAdminLogEventActionChangeTitle,
types.ChannelAdminLogEventActionChangeUse... |
The new value present in the event. | def new(self):
"""
The new value present in the event.
"""
ori = self.original.action
if isinstance(ori, (
types.ChannelAdminLogEventActionChangeAbout,
types.ChannelAdminLogEventActionChangeTitle,
types.ChannelAdminLogEventActionCha... |
Decrypts the given text in 16 - bytes blocks by using the given key and 32 - bytes initialization vector. | def decrypt_ige(cipher_text, key, iv):
"""
Decrypts the given text in 16-bytes blocks by using the
given key and 32-bytes initialization vector.
"""
if cryptg:
return cryptg.decrypt_ige(cipher_text, key, iv)
if libssl.decrypt_ige:
return libssl.dec... |
Encrypts the given text in 16 - bytes blocks by using the given key and 32 - bytes initialization vector. | def encrypt_ige(plain_text, key, iv):
"""
Encrypts the given text in 16-bytes blocks by using the
given key and 32-bytes initialization vector.
"""
padding = len(plain_text) % 16
if padding:
plain_text += os.urandom(16 - padding)
if cryptg:
... |
Finishes the initialization of this message by setting the client that sent the message and making use of the known entities. | def _finish_init(self, client, entities, input_chat):
"""
Finishes the initialization of this message by setting
the client that sent the message and making use of the
known entities.
"""
self._client = client
self._sender = entities.get(self._sender_id)
i... |
The message text formatted using the client s default parse mode. Will be None for: tl: MessageService. | def text(self):
"""
The message text, formatted using the client's default
parse mode. Will be ``None`` for :tl:`MessageService`.
"""
if self._text is None and self._client:
self._text = self._client.parse_mode.unparse(
self.message, self.entities)
... |
Returns a matrix ( list of lists ) containing all buttons of the message as MessageButton <telethon. tl. custom. messagebutton. MessageButton > instances. | def buttons(self):
"""
Returns a matrix (list of lists) containing all buttons of the message
as `MessageButton <telethon.tl.custom.messagebutton.MessageButton>`
instances.
"""
if self._buttons is None and self.reply_markup:
if not self.input_chat:
... |
Returns buttons but will make an API call to find the input chat ( needed for the buttons ) unless it s already cached. | async def get_buttons(self):
"""
Returns `buttons`, but will make an API call to find the
input chat (needed for the buttons) unless it's already cached.
"""
if not self.buttons and self.reply_markup:
chat = await self.get_input_chat()
if not chat:
... |
Returns the total button count. | def button_count(self):
"""
Returns the total button count.
"""
if self._buttons_count is None:
if isinstance(self.reply_markup, (
types.ReplyInlineMarkup, types.ReplyKeyboardMarkup)):
self._buttons_count = sum(
len(row.... |
If the message media is a photo this returns the: tl: Photo object. This will also return the photo for: tl: MessageService if their action is: tl: MessageActionChatEditPhoto. | def photo(self):
"""
If the message media is a photo, this returns the :tl:`Photo` object.
This will also return the photo for :tl:`MessageService` if their
action is :tl:`MessageActionChatEditPhoto`.
"""
if isinstance(self.media, types.MessageMediaPhoto):
if ... |
If the message media is a document this returns the: tl: Document object. | def document(self):
"""
If the message media is a document,
this returns the :tl:`Document` object.
"""
if isinstance(self.media, types.MessageMediaDocument):
if isinstance(self.media.document, types.Document):
return self.media.document
else:
... |
If the message has a loaded web preview this returns the: tl: WebPage object. | def web_preview(self):
"""
If the message has a loaded web preview,
this returns the :tl:`WebPage` object.
"""
if isinstance(self.media, types.MessageMediaWebPage):
if isinstance(self.media.webpage, types.WebPage):
return self.media.webpage |
If the message media is a game this returns the: tl: Game. | def game(self):
"""
If the message media is a game, this returns the :tl:`Game`.
"""
if isinstance(self.media, types.MessageMediaGame):
return self.media.game |
If the message media is geo geo live or a venue this returns the: tl: GeoPoint. | def geo(self):
"""
If the message media is geo, geo live or a venue,
this returns the :tl:`GeoPoint`.
"""
if isinstance(self.media, (types.MessageMediaGeo,
types.MessageMediaGeoLive,
types.MessageMediaVenue)):
... |
Returns a list of tuples [ (: tl: MessageEntity str ) ] the string being the inner text of the message entity ( like bold italics etc ). | def get_entities_text(self, cls=None):
"""
Returns a list of tuples [(:tl:`MessageEntity`, `str`)], the string
being the inner text of the message entity (like bold, italics, etc).
Args:
cls (`type`):
Returns entities matching this type only. For example,
... |
The Message that this message is replying to or None. | async def get_reply_message(self):
"""
The `Message` that this message is replying to, or ``None``.
The result will be cached after its first use.
"""
if self._reply_message is None:
if not self.reply_to_msg_id:
return None
# Bots cannot ... |
Responds to the message ( not as a reply ). Shorthand for telethon. client. messages. MessageMethods. send_message with entity already set. | async def respond(self, *args, **kwargs):
"""
Responds to the message (not as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message`
with ``entity`` already set.
"""
return await self._client.send_message(
await self.get_input_chat(), *... |
Replies to the message ( as a reply ). Shorthand for telethon. client. messages. MessageMethods. send_message with both entity and reply_to already set. | async def reply(self, *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.
"""
kwargs['reply_to'] = self.id
return await self._client.send... |
Forwards the message. Shorthand for telethon. client. messages. MessageMethods. forward_messages with both messages and from_peer already set. | async def forward_to(self, *args, **kwargs):
"""
Forwards the message. Shorthand for
`telethon.client.messages.MessageMethods.forward_messages`
with both ``messages`` and ``from_peer`` already set.
If you need to forward more than one message at once, don't use
this `for... |
Edits the message iff it s outgoing. Shorthand for telethon. client. messages. MessageMethods. edit_message with both entity and message already set. | async def edit(self, *args, **kwargs):
"""
Edits the message 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` ot... |
Deletes the 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. | async def delete(self, *args, **kwargs):
"""
Deletes the 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 ``mess... |
Downloads the media contained in the message if any. Shorthand for telethon. client. downloads. DownloadMethods. download_media with the message already set. | async def download_media(self, *args, **kwargs):
"""
Downloads the media contained in the message, if any. Shorthand
for `telethon.client.downloads.DownloadMethods.download_media`
with the ``message`` already set.
"""
return await self._client.download_media(self, *args, ... |
Calls telethon. tl. custom. messagebutton. MessageButton. click for the specified button. | async def click(self, i=None, j=None,
*, text=None, filter=None, data=None):
"""
Calls `telethon.tl.custom.messagebutton.MessageButton.click`
for the specified button.
Does nothing if the message has no buttons.
Args:
i (`int`):
C... |
Re - fetches this message to reload the sender and chat entities along with their input versions. | async def _reload_message(self):
"""
Re-fetches this message to reload the sender and chat entities,
along with their input versions.
"""
try:
chat = await self.get_input_chat() if self.is_channel else None
msg = await self._client.get_messages(chat, ids=s... |
Helper methods to set the buttons given the input sender and chat. | def _set_buttons(self, chat, bot):
"""
Helper methods to set the buttons given the input sender and chat.
"""
if isinstance(self.reply_markup, (
types.ReplyInlineMarkup, types.ReplyKeyboardMarkup)):
self._buttons = [[
MessageButton(self._client... |
Returns the input peer of the bot that s needed for the reply markup. | def _needed_markup_bot(self):
"""
Returns the input peer of the bot that's needed for the reply markup.
This is necessary for :tl:`KeyboardButtonSwitchInline` since we need
to know what bot we want to start. Raises ``ValueError`` if the bot
cannot be found but is needed. Returns... |
Helper method to return the document only if it has an attribute that s an instance of the given kind and passes the condition. | def _document_by_attribute(self, kind, condition=None):
"""
Helper method to return the document only if it has an attribute
that's an instance of the given kind, and passes the condition.
"""
doc = self.document
if doc:
for attr in doc.attributes:
... |
Create a link to the TL reference. | def make_link_node(rawtext, app, name, options):
"""
Create a link to the TL reference.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param name: Name of the object to link to
:param options: Options dictionary passed to role func.
"""
try:
... |
Link to the TL reference. | def tl_role(name, rawtext, text, lineno, inliner, options=None, content=None):
"""
Link to the TL reference.
Returns 2 part tuple containing list of nodes to insert into the
document and a list of system messages. Both are allowed to be empty.
:param name: The role name used in the document.
:... |
Makes the given inline query to the specified bot i. e. @vote My New Poll would be as follows: | async def inline_query(self, bot, query, *, offset=None, geo_point=None):
"""
Makes the given inline query to the specified bot
i.e. ``@vote My New Poll`` would be as follows:
>>> client = ...
>>> client.inline_query('vote', 'My New Poll')
Args:
bot (`entity... |
Gets me ( the self user ) which is currently authenticated or None if the request fails ( hence not authenticated ). | async def get_me(self, input_peer=False):
"""
Gets "me" (the self user) which is currently authenticated,
or None if the request fails (hence, not authenticated).
Args:
input_peer (`bool`, optional):
Whether to return the :tl:`InputPeerUser` version or the no... |
Return True if the signed - in user is a bot False otherwise. | async def is_bot(self):
"""
Return ``True`` if the signed-in user is a bot, ``False`` otherwise.
"""
if self._bot is None:
self._bot = (await self.get_me()).bot
return self._bot |
Returns True if the user is authorized. | async def is_user_authorized(self):
"""
Returns ``True`` if the user is authorized.
"""
if self._authorized is None:
try:
# Any request that requires authorization will work
await self(functions.updates.GetStateRequest())
self._... |
Turns the given entity into a valid Telegram: tl: User: tl: Chat or: tl: Channel. You can also pass a list or iterable of entities and they will be efficiently fetched from the network. | async def get_entity(self, entity):
"""
Turns the given entity into a valid Telegram :tl:`User`, :tl:`Chat`
or :tl:`Channel`. You can also pass a list or iterable of entities,
and they will be efficiently fetched from the network.
entity (`str` | `int` | :tl:`Peer` | :tl:`InputP... |
Turns the given peer into its input entity version. Most requests use this kind of: tl: InputPeer so this is the most suitable call to make for those cases. ** Generally you should let the library do its job ** and don t worry about getting the input entity first but if you re going to use an entity often consider maki... | async def get_input_entity(self, peer):
"""
Turns the given peer into its input entity version. Most requests
use this kind of :tl:`InputPeer`, so this is the most suitable call
to make for those cases. **Generally you should let the library do
its job** and don't worry about get... |
Gets the ID for the given peer which may be anything entity - like. | async def get_peer_id(self, peer, add_mark=True):
"""
Gets the ID for the given peer, which may be anything entity-like.
This method needs to be ``async`` because `peer` supports usernames,
invite-links, phone numbers (from people in your contact list), etc.
If ``add_mark is Fa... |
Gets a full entity from the given string which may be a phone or a username and processes all the found entities on the session. The string may also be a user link or a channel/ chat invite link. | async def _get_entity_from_string(self, string):
"""
Gets a full entity from the given string, which may be a phone or
a username, and processes all the found entities on the session.
The string may also be a user link, or a channel/chat invite link.
This method has the side eff... |
Returns a: tl: InputDialogPeer. This is a bit tricky because it may or not need access to the client to convert what s given into an input entity. | async def _get_input_dialog(self, dialog):
"""
Returns a :tl:`InputDialogPeer`. This is a bit tricky because
it may or not need access to the client to convert what's given
into an input entity.
"""
try:
if dialog.SUBCLASS_OF_ID == 0xa21c9795: # crc32(b'Input... |
Returns a: tl: InputNotifyPeer. This is a bit tricky because it may or not need access to the client to convert what s given into an input entity. | async def _get_input_notify(self, notify):
"""
Returns a :tl:`InputNotifyPeer`. This is a bit tricky because
it may or not need access to the client to convert what's given
into an input entity.
"""
try:
if notify.SUBCLASS_OF_ID == 0x58981615:
... |
Input version of the entity. | def input_entity(self):
"""
Input version of the entity.
"""
if not self._input_entity:
try:
self._input_entity = self._client._entity_cache[self._peer]
except KeyError:
pass
return self._input_entity |
Returns entity but will make an API call if necessary. | async def get_entity(self):
"""
Returns `entity` but will make an API call if necessary.
"""
if not self.entity and await self.get_input_entity():
try:
self._entity =\
await self._client.get_entity(self._input_entity)
except Val... |
Changes the draft message on the Telegram servers. The changes are reflected in this object. | async def set_message(
self, text=None, reply_to=0, parse_mode=(),
link_preview=None):
"""
Changes the draft message on the Telegram servers. The changes are
reflected in this object.
:param str text: New text of the draft.
Preserved if l... |
Sends the contents of this draft to the dialog. This is just a wrapper around send_message ( dialog. input_entity * args ** kwargs ). | async def send(self, clear=True, parse_mode=()):
"""
Sends the contents of this draft to the dialog. This is just a
wrapper around ``send_message(dialog.input_entity, *args, **kwargs)``.
"""
await self._client.send_message(
self._peer, self.text, reply_to=self.reply_t... |
Downloads the profile photo of the given entity ( user/ chat/ channel ). | async def download_profile_photo(
self, entity, file=None, *, download_big=True):
"""
Downloads the profile photo of the given entity (user/chat/channel).
Args:
entity (`entity`):
From who the photo will be downloaded.
.. note::
... |
Downloads the given media or the media from a specified Message. | async def download_media(self, message, file=None,
*, thumb=None, progress_callback=None):
"""
Downloads the given media, or the media from a specified Message.
Note that if the download is too slow, you should consider installing
``cryptg`` (through ``pip i... |
Downloads the given input location to a file. | async def download_file(
self, input_location, file=None, *, part_size_kb=None,
file_size=None, progress_callback=None, dc_id=None):
"""
Downloads the given input location to a file.
Args:
input_location (:tl:`InputFileLocation`):
The file loc... |
Specialized version of. download_media () for photos | async def _download_photo(self, photo, file, date, thumb, progress_callback):
"""Specialized version of .download_media() for photos"""
# Determine the photo and its largest size
if isinstance(photo, types.MessageMediaPhoto):
photo = photo.photo
if not isinstance(photo, types... |
Gets kind and possible names for: tl: DocumentAttribute. | def _get_kind_and_names(attributes):
"""Gets kind and possible names for :tl:`DocumentAttribute`."""
kind = 'document'
possible_names = []
for attr in attributes:
if isinstance(attr, types.DocumentAttributeFilename):
possible_names.insert(0, attr.file_name)
... |
Specialized version of. download_media () for documents. | async def _download_document(
self, document, file, date, thumb, progress_callback):
"""Specialized version of .download_media() for documents."""
if isinstance(document, types.MessageMediaDocument):
document = document.document
if not isinstance(document, types.Document)... |
Specialized version of. download_media () for contacts. Will make use of the vCard 4. 0 format. | def _download_contact(cls, mm_contact, file):
"""
Specialized version of .download_media() for contacts.
Will make use of the vCard 4.0 format.
"""
first_name = mm_contact.first_name
last_name = mm_contact.last_name
phone_number = mm_contact.phone_number
... |
Specialized version of. download_media () for web documents. | async def _download_web_document(cls, web, file, progress_callback):
"""
Specialized version of .download_media() for web documents.
"""
if not aiohttp:
raise ValueError(
'Cannot download web documents without the aiohttp '
'dependency install ... |
Gets a proper filename for file if this is a path. | def _get_proper_filename(file, kind, extension,
date=None, possible_names=None):
"""Gets a proper filename for 'file', if this is a path.
'kind' should be the kind of the output file (photo, document...)
'extension' should be the extension to be added to the f... |
Determine whether the given message is in the range or it should be ignored ( and avoid loading more chunks ). | def _message_in_range(self, message):
"""
Determine whether the given message is in the range or
it should be ignored (and avoid loading more chunks).
"""
# No entity means message IDs between chats may vary
if self.entity:
if self.reverse:
if ... |
After making the request update its offset with the last message. | def _update_offset(self, last_message):
"""
After making the request, update its offset with the last message.
"""
self.request.offset_id = last_message.id
if self.reverse:
# We want to skip the one we already have
self.request.offset_id += 1
if i... |
Iterator over the message history for the specified entity. If either search filter or from_user are provided: tl: messages. Search will be used instead of: tl: messages. getHistory. | def iter_messages(
self, entity, limit=None, *, offset_date=None, offset_id=0,
max_id=0, min_id=0, add_offset=0, search=None, filter=None,
from_user=None, wait_time=None, ids=None, reverse=False
):
"""
Iterator over the message history for the specified entity.
... |
Same as iter_messages but returns a TotalList <telethon. helpers. TotalList > instead. | async def get_messages(self, *args, **kwargs):
"""
Same as `iter_messages`, but returns a
`TotalList <telethon.helpers.TotalList>` instead.
If the `limit` is not set, it will be 1 by default unless both
`min_id` **and** `max_id` are set (as *named* arguments), in
which c... |
Sends the given message to the specified entity ( user/ chat/ channel ). | async def send_message(
self, entity, message='', *, reply_to=None,
parse_mode=(), link_preview=True, file=None,
force_document=False, clear_draft=False, buttons=None,
silent=None):
"""
Sends the given message to the specified entity (user/chat/channel).
... |
Forwards the given message ( s ) to the specified entity. | async def forward_messages(self, entity, messages, from_peer=None,
*, silent=None, as_album=None):
"""
Forwards the given message(s) to the specified entity.
Args:
entity (`entity`):
To which entity the message(s) will be forwarded.
... |
Edits the given message ID ( to change its contents or disable preview ). | async def edit_message(
self, entity, message=None, text=None,
*, parse_mode=(), link_preview=True, file=None,
buttons=None):
"""
Edits the given message ID (to change its contents or disable preview).
Args:
entity (`entity` | `Message <telethon.t... |
Deletes a message from a chat optionally for everyone. | async def delete_messages(self, entity, message_ids, *, revoke=True):
"""
Deletes a message from a chat, optionally "for everyone".
Args:
entity (`entity`):
From who the message will be deleted. This can actually
be ``None`` for normal chats, but **mu... |
Sends a read acknowledge ( i. e. notifying the given peer that we ve read their messages also known as the double check ). | async def send_read_acknowledge(
self, entity, message=None, *, max_id=None, clear_mentions=False):
"""
Sends a "read acknowledge" (i.e., notifying the given peer that we've
read their messages, also known as the "double check").
This effectively marks a message as read (or ... |
Sends a file to the specified entity. | async def send_file(
self, entity, file, *, caption=None, force_document=False,
progress_callback=None, reply_to=None, attributes=None,
thumb=None, allow_cache=True, parse_mode=(),
voice_note=False, video_note=False, buttons=None, silent=None,
supports_streami... |
Specialized version of. send_file for albums | async def _send_album(self, entity, files, caption='',
progress_callback=None, reply_to=None,
parse_mode=(), silent=None):
"""Specialized version of .send_file for albums"""
# We don't care if the user wants to avoid cache, we will use it
# any... |
Uploads the specified file and returns a handle ( an instance of: tl: InputFile or: tl: InputFileBig as required ) which can be later used before it expires ( they are usable during less than a day ). | async def upload_file(
self, file, *, part_size_kb=None, file_name=None, use_cache=None,
progress_callback=None):
"""
Uploads the specified file and returns a handle (an instance of
:tl:`InputFile` or :tl:`InputFileBig`, as required) which can be
later used before... |
Adds the given entities to the cache if they weren t saved before. | def add(self, entities):
"""
Adds the given entities to the cache, if they weren't saved before.
"""
if not utils.is_list_like(entities):
# Invariant: all "chats" and "users" are always iterables,
# and "user" never is (so we wrap it inside a list).
en... |
Runs the event loop until disconnect is called or if an error while connecting/ sending/ receiving occurs in the background. In the latter case said error will raise so you have a chance to except it on your own code. | def run_until_disconnected(self):
"""
Runs the event loop until `disconnect` is called or if an error
while connecting/sending/receiving occurs in the background. In
the latter case, said error will ``raise`` so you have a chance
to ``except`` it on your own code.
If the... |
Decorator helper method around add_event_handler. Example: | def on(self, event):
"""
Decorator helper method around `add_event_handler`. Example:
>>> from telethon import TelegramClient, events
>>> client = TelegramClient(...)
>>>
>>> @client.on(events.NewMessage)
... async def handler(event):
... ...
... |
Registers the given callback to be called on the specified event. | def add_event_handler(self, callback, event=None):
"""
Registers the given callback to be called on the specified event.
Args:
callback (`callable`):
The callable function accepting one parameter to be used.
Note that if you have used `telethon.event... |
Inverse operation of: meth: add_event_handler. | def remove_event_handler(self, callback, event=None):
"""
Inverse operation of :meth:`add_event_handler`.
If no event is given, all events for this callback are removed.
Returns how many callbacks were removed.
"""
found = 0
if event and not isinstance(event, typ... |
Catches up on the missed updates while the client was offline. You should call this method after registering the event handlers so that the updates it loads can by processed by your script. | async def catch_up(self):
"""
"Catches up" on the missed updates while the client was offline.
You should call this method after registering the event handlers
so that the updates it loads can by processed by your script.
This can also be used to forcibly fetch new updates if th... |
Resets the state. | def reset(self):
"""
Resets the state.
"""
# Session IDs can be random on every connection
self.id = struct.unpack('q', os.urandom(8))[0]
self._sequence = 0
self._last_msg_id = 0 |
Calculate the key based on Telegram guidelines for MTProto 2 specifying whether it s the client or not. See https:// core. telegram. org/ mtproto/ description#defining - aes - key - and - initialization - vector | def _calc_key(auth_key, msg_key, client):
"""
Calculate the key based on Telegram guidelines for MTProto 2,
specifying whether it's the client or not. See
https://core.telegram.org/mtproto/description#defining-aes-key-and-initialization-vector
"""
x = 0 if client else 8
... |
Writes a message containing the given data into buffer. | def write_data_as_message(self, buffer, data, content_related,
*, after_id=None):
"""
Writes a message containing the given data into buffer.
Returns the message id.
"""
msg_id = self._get_new_msg_id()
seq_no = self._get_seq_no(content_relat... |
Encrypts the given message data using the current authorization key following MTProto 2. 0 guidelines core. telegram. org/ mtproto/ description. | def encrypt_message_data(self, data):
"""
Encrypts the given message data using the current authorization key
following MTProto 2.0 guidelines core.telegram.org/mtproto/description.
"""
data = struct.pack('<qq', self.salt, self.id) + data
padding = os.urandom(-(len(data) ... |
Inverse of encrypt_message_data for incoming server messages. | def decrypt_message_data(self, body):
"""
Inverse of `encrypt_message_data` for incoming server messages.
"""
if len(body) < 8:
raise InvalidBufferError(body)
# TODO Check salt, session_id and sequence_number
key_id = struct.unpack('<Q', body[:8])[0]
... |
Generates a new unique message ID based on the current time ( in ms ) since epoch applying a known time offset. | def _get_new_msg_id(self):
"""
Generates a new unique message ID based on the current
time (in ms) since epoch, applying a known time offset.
"""
now = time.time() + self.time_offset
nanoseconds = int((now - int(now)) * 1e+9)
new_msg_id = (int(now) << 32) | (nanos... |
Updates the time offset to the correct one given a known valid message ID. | def update_time_offset(self, correct_msg_id):
"""
Updates the time offset to the correct
one given a known valid message ID.
"""
bad = self._get_new_msg_id()
old = self.time_offset
now = int(time.time())
correct = correct_msg_id >> 32
self.time_of... |
Generates the next sequence number depending on whether it should be for a content - related query or not. | def _get_seq_no(self, content_related):
"""
Generates the next sequence number depending on whether
it should be for a content-related query or not.
"""
if content_related:
result = self._sequence * 2 + 1
self._sequence += 1
return result
... |
This method yields TLObjects from a given. tl file. | def parse_tl(file_path, layer, methods=None, ignored_ids=CORE_TYPES):
"""
This method yields TLObjects from a given .tl file.
Note that the file is parsed completely before the function yields
because references to other objects may appear later in the file.
"""
method_info = {m.name: m for m i... |
Finds the layer used on the specified scheme. tl file. | def find_layer(file_path):
"""Finds the layer used on the specified scheme.tl file."""
layer_regex = re.compile(r'^//\s*LAYER\s*(\d+)$')
with file_path.open('r') as file:
for line in file:
match = layer_regex.match(line)
if match:
return int(match.group(1)) |
The URL present in this inline results. If you want to click this URL to open it in your browser you should use Python s webbrowser. open ( url ) for such task. | def url(self):
"""
The URL present in this inline results. If you want to "click"
this URL to open it in your browser, you should use Python's
`webbrowser.open(url)` for such task.
"""
if isinstance(self.result, types.BotInlineResult):
return self.result.url |
Returns either the: tl: WebDocument thumbnail for normal results or the: tl: Photo for media results. | def photo(self):
"""
Returns either the :tl:`WebDocument` thumbnail for
normal results or the :tl:`Photo` for media results.
"""
if isinstance(self.result, types.BotInlineResult):
return self.result.thumb
elif isinstance(self.result, types.BotInlineMediaResult... |
Returns either the: tl: WebDocument content for normal results or the: tl: Document for media results. | def document(self):
"""
Returns either the :tl:`WebDocument` content for
normal results or the :tl:`Document` for media results.
"""
if isinstance(self.result, types.BotInlineResult):
return self.result.content
elif isinstance(self.result, types.BotInlineMedia... |
Clicks this result and sends the associated message. | async def click(self, entity, reply_to=None,
silent=False, clear_draft=False, hide_via=False):
"""
Clicks this result and sends the associated `message`.
Args:
entity (`entity`):
The entity to which the message of this result should be sent.
... |
Downloads the media in this result ( if there is a document the document will be downloaded ; otherwise the photo will if present ). | async def download_media(self, *args, **kwargs):
"""
Downloads the media in this result (if there is a document, the
document will be downloaded; otherwise, the photo will if present).
This is a wrapper around `client.download_media
<telethon.client.downloads.DownloadMethods.dow... |
Update the state with the given update. | def update(
self,
update,
*,
channel_id=None,
has_pts=(
types.UpdateNewMessage,
types.UpdateDeleteMessages,
types.UpdateReadHistoryInbox,
types.UpdateReadHistoryOutbox,
types.Updat... |
Returns an iterator over the dialogs yielding limit at most. Dialogs are the open chats or conversations with other people groups you have joined or channels you are subscribed to. | def iter_dialogs(
self, limit=None, *, offset_date=None, offset_id=0,
offset_peer=types.InputPeerEmpty(), ignore_migrated=False
):
"""
Returns an iterator over the dialogs, yielding 'limit' at most.
Dialogs are the open "chats" or conversations with other people,
... |
Creates a Conversation <telethon. tl. custom. conversation. Conversation > with the given entity so you can easily send messages and await for responses or other reactions. Refer to its documentation for more. | def conversation(
self, entity,
*, timeout=60, total_timeout=None, max_messages=100,
exclusive=True, replies_are_responses=True):
"""
Creates a `Conversation <telethon.tl.custom.conversation.Conversation>`
with the given entity so you can easily send messages ... |
Connects to the specified given connection using the given auth key. | async def connect(self, connection):
"""
Connects to the specified given connection using the given auth key.
"""
if self._user_connected:
self._log.info('User is already connected!')
return
self._connection = connection
await self._connect()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.