INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
#docs or #ref query: Like #search but shows the query.
async def handler(event): """#docs or #ref query: Like #search but shows the query.""" q1 = event.pattern_match.group(1) q2 = urllib.parse.quote(q1) await asyncio.wait([ event.delete(), event.respond(DOCS.format(q1, q2), reply_to=event.reply_to_msg_id) ])
#rtd: Tells the user to please read the docs.
async def handler(event): """#rtd: Tells the user to please read the docs.""" rtd = RTFD if event.pattern_match.group(1) else RTD await asyncio.wait([ event.delete(), event.respond(rtd, reply_to=event.reply_to_msg_id) ])
#client or #msg query: Looks for the given attribute in RTD.
async def handler(event): """#client or #msg query: Looks for the given attribute in RTD.""" await event.delete() await event.respond( get_docs_message(kind=event.pattern_match.group(1), query=event.pattern_match.group(2)), reply_to=event.reply_to_msg_id )
#ot, #offtopic: Tells the user to move to @TelethonOffTopic.
async def handler(event): """#ot, #offtopic: Tells the user to move to @TelethonOffTopic.""" await asyncio.wait([ event.delete(), event.respond(OFFTOPIC[event.chat_id], reply_to=event.reply_to_msg_id) ])
#learn or #python: Tells the user to learn some Python first.
async def handler(event): """#learn or #python: Tells the user to learn some Python first.""" await asyncio.wait([ event.delete(), event.respond( LEARN_PYTHON, reply_to=event.reply_to_msg_id, link_preview=False) ])
Builds a :tl`ReplyInlineMarkup` or :tl:`ReplyKeyboardMarkup` for the given buttons, or does nothing if either no buttons are provided or the provided argument is already a reply markup. This will add any event handlers defined in the buttons and delete old ones not to call them twice, ...
def build_reply_markup(self, buttons, inline_only=False): """ Builds a :tl`ReplyInlineMarkup` or :tl:`ReplyKeyboardMarkup` for the given buttons, or does nothing if either no buttons are provided or the provided argument is already a reply markup. This will add any event handler...
Pretty formats the given object as a string which is returned. If indent is None, a single line will be returned.
def pretty_format(obj, indent=None): """ Pretty formats the given object as a string which is returned. If indent is None, a single line will be returned. """ if indent is None: if isinstance(obj, TLObject): obj = obj.to_dict() if isinstan...
Write bytes by using Telegram guidelines
def serialize_bytes(data): """Write bytes by using Telegram guidelines""" if not isinstance(data, bytes): if isinstance(data, str): data = data.encode('utf-8') else: raise TypeError( 'bytes or str expected, not {}'.format(type(d...
Represent the current `TLObject` as JSON. If ``fp`` is given, the JSON will be dumped to said file pointer, otherwise a JSON string will be returned. Note that bytes and datetimes cannot be represented in JSON, so if those are found, they will be base64 encoded and ISO-formatte...
def to_json(self, fp=None, default=_json_default, **kwargs): """ Represent the current `TLObject` as JSON. If ``fp`` is given, the JSON will be dumped to said file pointer, otherwise a JSON string will be returned. Note that bytes and datetimes cannot be represented in ...
Helper method to replace ``entities[i]`` to mention ``user``, or do nothing if it can't be found.
async def _replace_with_mention(self, entities, i, user): """ Helper method to replace ``entities[i]`` to mention ``user``, or do nothing if it can't be found. """ try: entities[i] = types.InputMessageEntityMentionName( entities[i].offset, entities[i]....
Returns a (parsed message, entities) tuple depending on ``parse_mode``.
async def _parse_message_text(self, message, parse_mode): """ Returns a (parsed message, entities) tuple depending on ``parse_mode``. """ if parse_mode is (): parse_mode = self._parse_mode else: parse_mode = utils.sanitize_parse_mode(parse_mode) i...
Extracts the response message known a request and Update result. The request may also be the ID of the message to match. If ``request is None`` this method returns ``{id: message}``. If ``request.random_id`` is a list, this method returns a list too.
def _get_response_message(self, request, result, input_chat): """ Extracts the response message known a request and Update result. The request may also be the ID of the message to match. If ``request is None`` this method returns ``{id: message}``. If ``request.random_id`` is a...
Returns `sender`, but will make an API call to find the sender unless it's already cached.
async def get_sender(self): """ Returns `sender`, but will make an API call to find the sender unless it's already cached. """ # ``sender.min`` is present both in :tl:`User` and :tl:`Channel`. # It's a flag that will be set if only minimal information is # availab...
This :tl:`InputPeer` is the input version of the user/channel who sent the message. Similarly to `input_chat`, this doesn't have things like username or similar, but still useful in some cases. Note that this might not be available if the library can't find the input chat, or if the mes...
def input_sender(self): """ This :tl:`InputPeer` is the input version of the user/channel who sent the message. Similarly to `input_chat`, this doesn't have things like username or similar, but still useful in some cases. Note that this might not be available if the library can'...
Returns `input_sender`, but will make an API call to find the input sender unless it's already cached.
async def get_input_sender(self): """ Returns `input_sender`, but will make an API call to find the input sender unless it's already cached. """ if self.input_sender is None and self._sender_id: await self._refetch_sender() return self._input_sender
Decorator method to *register* event handlers. This is the client-less `add_event_handler <telethon.client.updates.UpdateMethods.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 ...
def register(event=None): """ Decorator method to *register* event handlers. This is the client-less `add_event_handler <telethon.client.updates.UpdateMethods.add_event_handler>` variant. Note that this method only registers callbacks as handlers, and does not attach them to any client. This is...
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...
def unregister(callback, event=None): """ 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 w...
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...
def parse(message, delimiters=None, url_re=None): """ 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, {deli...
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...
def unparse(text, entities, delimiters=None, url_fmt=None): """ 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 ...
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 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. """ new...
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* format)..." # > "...current value of dh_prime equals # ...
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 fingerprint. """ n = TLObject.serialize_bytes(get_byte_array(key.n)) e = TLObject.serialize_bytes(get_byte_array(key.e)) # Telegram ...
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...
def encrypt(fingerprint, data): """ 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 Non...
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): """ 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_re...
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...
async def get_response(self, message=None, *, timeout=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 ...
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 message being a reply) arrives. The arguments are the same as those for `get_response`. """ return await self._get_message( message, se...
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...
def _get_message( self, target_message, indices, pending, timeout, condition): """ Gets the next desired message under the desired condition. Args: target_message (`object`): The target message for which we want to find another response th...
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`. """ start_time = time.time() target_id = self._get_message_id(message) target_date = self._ed...
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 a response doesn't imply the message was read, and this action will also trigger even without a response. """ start_time = time.time() future ...
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 >>> ...
async def wait_event(self, event, *, timeout=None): """ 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:...
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...
def start( self, phone=lambda: input('Please enter your phone (or bot token): '), password=lambda: getpass.getpass('Please enter your password: '), *, bot_token=None, force_sms=False, code_callback=None, first_name='New User', last_name='', max_att...
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( 'Please make sure to call send_code_request first.'...
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...
async def sign_up(self, code, first_name, last_name='', *, phone=None, phone_code_hash=None): """ 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 Term...
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) self._self_input_peer = utils.get_input_peer(user, allow_self=False) self._authorized = True ...
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 def send_code_request(self, phone, *, force_sms=False): """ 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 se...
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. """ try: await self(functions.auth.LogOutRequest()) except errors.RPCError: return False ...
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. ...
async def edit_2fa( self, current_password=None, new_password=None, *, hint='', email=None, email_code_callback=None): """ Changes the 2FA settings of the logged in user, according to the passed parameters. Take note of the parameter explanations. Note that this ...
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): ...
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_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. This callback logs out if authorized, signs in if a code was sent or a bot token is input, or sends...
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 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....
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: ...
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). Args: cls (`type`): Returns entities matching this type only. For example, the following will print the text for all ``co...
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``. 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._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. If you need to forward more than one message at once, don't use this `forward_to` method. Use a `telethon.client.telegramclient.Te...
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. Returns ``None`` if the message was incoming, or the edited `Message` otherwise. .. note:: This is different ...
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. If you need to delete more th...
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. 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...
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. 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_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. :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 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. 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 ...
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: >>> client = ... >>> client.inline_query('vote', 'My New Poll') Args: bot (`entity`): The bot entity to which the inline query should be made. quer...
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). Args: input_peer (`bool`, optional): Whether to return the :tl:`InputPeerUser` version or the normal :tl:`User`. This can be useful if you jus...
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. entity (`str` | `int` | :tl:`Peer` | :tl:`InputPeer`): If a username is given, **the usernam...
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 ...
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. 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...
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. This method has the side effect of adding the found users to the session database, so it ...
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. :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...
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 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...
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 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...
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 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. ...
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. '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...
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...