text
stringlengths
81
112k
Inverse operation of `register` (though not a decorator). Client-less `remove_event_handler <telethon.client.updates.UpdateMethods.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 hand...
Parses the given markdown message and returns its stripped representation plus a list of the MessageEntity's that were found. :param message: the message with markdown-like syntax to be parsed. :param delimiters: the delimiters to be used, {delimiter: type}. :param url_re: the URL bytes regex to be use...
Performs the reverse operation to .parse(), effectively returning markdown-like syntax given a normal text and its MessageEntity's. :param text: the text to be reconverted into markdown. :param entities: the MessageEntity's applied to the text. :return: a markdown-like text representing the combination...
Calculates the new nonce hash based on the current attributes. :param new_nonce: the new nonce to be hashed. :param number: number to prepend before the hash. :return: the hash for the given new nonce. def calc_new_nonce_hash(self, new_nonce, number): """ Calculates the new non...
Return the variable length bytes corresponding to the given int def get_byte_array(integer): """Return the variable length bytes corresponding to the given int""" # Operate in big endian (unlike most of Telegram API) since: # > "...pq is a representation of a natural number # (in binary *big endian*...
Given a RSA key, computes its fingerprint like Telegram does. :param key: the Crypto.RSA key. :return: its 8-bytes-long fingerprint. def _compute_fingerprint(key): """ Given a RSA key, computes its fingerprint like Telegram does. :param key: the Crypto.RSA key. :return: its 8-bytes-long finge...
Adds a new public key to be used when encrypting new data is needed def add_key(pub): """Adds a new public key to be used when encrypting new data is needed""" global _server_keys key = rsa.PublicKey.load_pkcs1(pub) _server_keys[_compute_fingerprint(key)] = key
Encrypts the given data known the fingerprint to be used in the way Telegram requires us to do so (sha1(data) + data + padding) :param fingerprint: the fingerprint of the RSA key. :param data: the data to be encrypted. :return: the cipher text, or None if no key matching this fingerprint is fou...
Sends a message in the context of this conversation. Shorthand for `telethon.client.messages.MessageMethods.send_message` with ``entity`` already set. async def send_message(self, *args, **kwargs): """ Sends a message in the context of this conversation. Shorthand for `telethon....
Marks as read the latest received message if ``message is None``. Otherwise, marks as read until the given message (or message ID). This is equivalent to calling `client.send_read_acknowledge <telethon.client.messages.MessageMethods.send_read_acknowledge>`. def mark_read(self, message=None): ...
Returns a coroutine that will resolve once a response arrives. Args: message (`Message <telethon.tl.custom.message.Message>` | `int`, optional): The message (or the message ID) for which a response is expected. By default this is the last sent message. t...
Returns a coroutine that will resolve once a reply (that is, a message being a reply) arrives. The arguments are the same as those for `get_response`. async def get_reply(self, message=None, *, timeout=None): """ Returns a coroutine that will resolve once a reply (that is, a mes...
Gets the next desired message under the desired condition. Args: target_message (`object`): The target message for which we want to find another response that applies based on `condition`. indices (`dict`): This dictionary remembers the l...
Awaits for an edit after the last message to arrive. The arguments are the same as those for `get_response`. async def get_edit(self, message=None, *, timeout=None): """ Awaits for an edit after the last message to arrive. The arguments are the same as those for `get_response`. ...
Awaits for the sent message to be read. Note that receiving a response doesn't imply the message was read, and this action will also trigger even without a response. async def wait_read(self, message=None, *, timeout=None): """ Awaits for the sent message to be read. Note that receiving...
Waits for a custom event to occur. Timeouts still apply. Unless you're certain that your code will run fast enough, generally you should get a "handle" of this special coroutine before acting. Generally, you should do this: >>> from telethon import TelegramClient, events >>> ...
Convenience method to interactively connect and sign in if required, also taking into consideration that 2FA may be enabled in the account. If the phone doesn't belong to an existing account (and will hence `sign_up` for a new one), **you are agreeing to Telegram's Terms of Service. Th...
Helper method to both parse and validate phone and its hash. def _parse_phone_and_hash(self, phone, phone_hash): """ Helper method to both parse and validate phone and its hash. """ phone = utils.parse_phone(phone) or self._phone if not phone: raise ValueError( ...
Starts or completes the sign in process with the given phone number or code that Telegram sent. Args: phone (`str` | `int`): The phone to send the code to if no code was provided, or to override the phone that was previously used with these re...
Signs up to Telegram if you don't have an account yet. You must call .send_code_request(phone) first. **By using this method you're agreeing to Telegram's Terms of Service. This is required and your account will be banned otherwise.** See https://telegram.org/tos and https://cor...
Callback called whenever the login or sign up process completes. Returns the input user parameter. def _on_login(self, user): """ Callback called whenever the login or sign up process completes. Returns the input user parameter. """ self._bot = bool(user.bot) s...
Sends a code request to the specified phone number. Args: phone (`str` | `int`): The phone to which the code will be sent. force_sms (`bool`, optional): Whether to force sending as SMS. Returns: An instance of :tl:`SentCode`. async ...
Logs out Telegram and deletes the current ``*.session`` file. Returns: ``True`` if the operation was successful. async def log_out(self): """ Logs out Telegram and deletes the current ``*.session`` file. Returns: ``True`` if the operation was successful. ...
Changes the 2FA settings of the logged in user, according to the passed parameters. Take note of the parameter explanations. Note that this method may be *incredibly* slow depending on the prime numbers that must be used during the process to make sure that everything is safe. ...
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(...
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='') ...
Executes the authentication process with the Telegram servers. :param sender: a connected `MTProtoPlainSender`. :return: returns a (authorization key, time offset) tuple. async def do_authentication(sender): """ Executes the authentication process with the Telegram servers. :param sender: a conne...
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 representing the given byte array. def get_int(byte...
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 wr...
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(): ...
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 # ...
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 a code was sent or a bot token is input, or sends...
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). """ ...
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...
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: ...
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.Chan...
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, ...
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: ...
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_t...
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 mak...
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 s...
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.cust...
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. """ ...
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 = ...
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 wil...
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...
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(...
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, ...
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 following will print the text for all ``co...
The `Message` that this message is replying to, or ``None``. The result will be cached after its first use. 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._r...
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.MessageMeth...
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.M...
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 `forward_to` method. Use a `telethon.client.telegramclient.Te...
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` otherwise. .. note:: This is different ...
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. If you need to delete more th...
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 f...
Calls `telethon.tl.custom.messagebutton.MessageButton.click` for the specified button. Does nothing if the message has no buttons. Args: i (`int`): Clicks the i'th button (starting from the index 0). Will ``raise IndexError`` if out of bounds. Exampl...
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.g...
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)): ...
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 ``None`` if it's not needed. def _needed_markup_...
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 k...
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. def make_link_node(rawtext, app, name, options): """ Create a link to...
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. :param rawtext: The entire markup snippet, with role. :param text: The text marked with ...
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`): The bot entity to which the inline query should be made. quer...
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 normal :tl:`User`. This can be useful if you jus...
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.upda...
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:`InputPeer`): If a username is given, **the usernam...
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 ...
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 False``, then a positive ID will be returned instead. By default...
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 effect of adding the found users to the session database, so it ...
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 acc...
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 acc...
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...
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._cl...
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 left as None. :param int reply_to: Message ID to reply to. Preserved if left as 0, erased if s...
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....
Downloads the profile photo of the given entity (user/chat/channel). Args: entity (`entity`): From who the photo will be downloaded. .. note:: This method expects the full entity (which has the data to download the photo), no...
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 install cryptg``) so that decrypting the received data is done in C instead of Python (much faster). message (`Message <tele...
Downloads the given input location to a file. Args: input_location (:tl:`InputFileLocation`): The file location from which the file will be downloaded. See `telethon.utils.get_input_location` source for a complete list of supported types. ...
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...
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): ...
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.doc...
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...
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 documen...
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 file if the filename doesn't have any yet 'date' should be when this file was originally...
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 en...
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 w...
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`. Args: entity (`entity`): The entity from whom to retrieve the message histor...
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 case the entire range will be returned. This is so because ...
Sends the given message to the specified entity (user/chat/channel). The default parse mode is the same as the official applications (a custom flavour of markdown). ``**bold**, `code` or __italic__`` are available. In addition you can send ``[links](https://example.com)`` and ``[mention...
Forwards the given message(s) to the specified entity. Args: entity (`entity`): To which entity the message(s) will be forwarded. messages (`list` | `int` | `Message <telethon.tl.custom.message.Message>`): The message(s) to forward, or their integer IDs....
Edits the given message ID (to change its contents or disable preview). Args: entity (`entity` | `Message <telethon.tl.custom.message.Message>`): From which chat to edit the message. This can also be the message to be edited, and the entity will be inferred ...
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 **must** be present for channels and megagroups. message_ids (`li...
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 more than one) in the given conversation. If neither message nor maximum ID are provided, all messages will be ...
Sends a file to the specified entity. Args: entity (`entity`): Who will receive the file. file (`str` | `bytes` | `file` | `media`): The file to send, which can be one of: * A local file path to an in-disk file. The file name ...
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 want...
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). Uploading a file will simply return a "handle" to the file stored remotely in the Teleg...
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, ...