INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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`. Args: entity (`entity`): The entity from whom to retrieve the message histor...
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. 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 ...
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). 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...
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. 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....
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). 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 ...
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". 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...
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"). 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 ...
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. 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 ...
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). Uploading a file will simply return a "handle" to the file stored remotely in the Teleg...
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. If the loop is already running, this method returns a corout...
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: >>> from telethon import TelegramClient, events >>> client = TelegramClient(...) >>> >>> @client.on(events.NewMessage) ... async def handler(event): ... ... ... >>> Args: ...
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. Args: callback (`callable`): The callable function accepting one parameter to be used. Note that if you have used `telethon.events.register` in the callback, ``event`` will be ignored,...
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`. If no event is given, all events for this callback are removed. Returns how many callbacks were removed.
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. This can also be used to forcibly fetch new updates if there are any.
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. Returns the message id.
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. Note that the file is parsed completely before the function yields because references to other objects may appear later in the 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`. Args: entity (`entity`): The entity to which the message of this result should be sent. reply_to (`int` | `Message <telethon.tl.custom.message.Message>`, optional): If present, the sent message will ...
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). This is a wrapper around `client.download_media <telethon.client.downloads.DownloadMethods.download_media>`.
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. Args: limit (`int` | `None`): How many dialogs to be retrieved as maximum. Can ...
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. Args: entity (`entity`): The entity with which a new convers...
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() ...
This method enqueues the given request to be sent. Its send state will be saved until a response arrives, and a ``Future`` that will be resolved when the response arrives will be returned: .. code-block:: python async def method(): # Sending (enqueued for the send l...
def send(self, request, ordered=False): """ This method enqueues the given request to be sent. Its send state will be saved until a response arrives, and a ``Future`` that will be resolved when the response arrives will be returned: .. code-block:: python async def ...
Performs the actual connection, retrying, generating the authorization key if necessary, and starting the send and receive loops.
async def _connect(self): """ Performs the actual connection, retrying, generating the authorization key if necessary, and starting the send and receive loops. """ self._log.info('Connecting to %s...', self._connection) for attempt in retry_range(self._retries): ...
Cleanly disconnects and then reconnects.
async def _reconnect(self, last_error): """ Cleanly disconnects and then reconnects. """ self._log.debug('Closing current connection...') await self._connection.disconnect() await helpers._cancel( self._log, send_loop_handle=self._send_loop_handle...
Starts a reconnection in the background.
def _start_reconnect(self, error): """Starts a reconnection in the background.""" if self._user_connected and not self._reconnecting: # We set reconnecting to True here and not inside the new task # because it may happen that send/recv loop calls this again # while th...
This loop is responsible for popping items off the send queue, encrypting them, and sending them over the network. Besides `connect`, only this method ever sends data.
async def _send_loop(self): """ This loop is responsible for popping items off the send queue, encrypting them, and sending them over the network. Besides `connect`, only this method ever sends data. """ while self._user_connected and not self._reconnecting: ...
Adds the given message to the list of messages that must be acknowledged and dispatches control to different ``_handle_*`` method based on its type.
async def _process_message(self, message): """ Adds the given message to the list of messages that must be acknowledged and dispatches control to different ``_handle_*`` method based on its type. """ self._pending_ack.add(message.msg_id) handler = self._handlers.g...
Pops the states known to match the given ID from pending messages. This method should be used when the response isn't specific.
def _pop_states(self, msg_id): """ Pops the states known to match the given ID from pending messages. This method should be used when the response isn't specific. """ state = self._pending_state.pop(msg_id, None) if state: return [state] to_pop = [] ...
Handles the result for Remote Procedure Calls: rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult; This is where the future results for sent requests are set.
async def _handle_rpc_result(self, message): """ Handles the result for Remote Procedure Calls: rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult; This is where the future results for sent requests are set. """ rpc_result = message.obj state = sel...
Processes the inner messages of a container with many of them: msg_container#73f1f8dc messages:vector<%Message> = MessageContainer;
async def _handle_container(self, message): """ Processes the inner messages of a container with many of them: msg_container#73f1f8dc messages:vector<%Message> = MessageContainer; """ self._log.debug('Handling container') for inner_message in message.obj.messages: ...
Unpacks the data from a gzipped object and processes it: gzip_packed#3072cfa1 packed_data:bytes = Object;
async def _handle_gzip_packed(self, message): """ Unpacks the data from a gzipped object and processes it: gzip_packed#3072cfa1 packed_data:bytes = Object; """ self._log.debug('Handling gzipped data') with BinaryReader(message.obj.data) as reader: message...
Handles pong results, which don't come inside a ``rpc_result`` but are still sent through a request: pong#347773c5 msg_id:long ping_id:long = Pong;
async def _handle_pong(self, message): """ Handles pong results, which don't come inside a ``rpc_result`` but are still sent through a request: pong#347773c5 msg_id:long ping_id:long = Pong; """ pong = message.obj self._log.debug('Handling pong for message %d...
Corrects the currently used server salt to use the right value before enqueuing the rejected message to be re-sent: bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;
async def _handle_bad_server_salt(self, message): """ Corrects the currently used server salt to use the right value before enqueuing the rejected message to be re-sent: bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadM...
Adjusts the current state to be correct based on the received bad message notification whenever possible: bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;
async def _handle_bad_notification(self, message): """ Adjusts the current state to be correct based on the received bad message notification whenever possible: bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification; "...
Updates the current status with the received detailed information: msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;
async def _handle_detailed_info(self, message): """ Updates the current status with the received detailed information: msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo; """ # TODO https://goo.gl/VvpCC6 msg_i...
Updates the current status with the received session information: new_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;
async def _handle_new_session_created(self, message): """ Updates the current status with the received session information: new_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession; """ # TODO https://goo.gl/LMyN7A self....
Handles a server acknowledge about our messages. Normally these can be ignored except in the case of ``auth.logOut``: auth.logOut#5717da40 = Bool; Telegram doesn't seem to send its result so we need to confirm it manually. No other request is known to have this behaviour. ...
async def _handle_ack(self, message): """ Handles a server acknowledge about our messages. Normally these can be ignored except in the case of ``auth.logOut``: auth.logOut#5717da40 = Bool; Telegram doesn't seem to send its result so we need to confirm it manually. N...
Handles future salt results, which don't come inside a ``rpc_result`` but are still sent through a request: future_salts#ae500895 req_msg_id:long now:int salts:vector<future_salt> = FutureSalts;
async def _handle_future_salts(self, message): """ Handles future salt results, which don't come inside a ``rpc_result`` but are still sent through a request: future_salts#ae500895 req_msg_id:long now:int salts:vector<future_salt> = FutureSalts; """ # TOD...
Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by enqueuing a :tl:`MsgsStateInfo` to be sent at a later point.
async def _handle_state_forgotten(self, message): """ Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by enqueuing a :tl:`MsgsStateInfo` to be sent at a later point. """ self._send_queue.append(RequestState(MsgsStateInfo( req_msg_id=message.msg_id, info=chr(1) ...
Creates new inline result of article type. Args: title (`str`): The title to be shown for this result. description (`str`, optional): Further explanation of what this result means. url (`str`, optional): The URL to be shown f...
async def article( self, title, description=None, *, url=None, thumb=None, content=None, id=None, text=None, parse_mode=(), link_preview=True, geo=None, period=60, contact=None, game=False, buttons=None ): """ Creates new inline result of article type....
Creates a new inline result of photo type. Args: file (`obj`, optional): Same as ``file`` for `client.send_file <telethon.client.uploads.UploadMethods.send_file>`.
async def photo( self, file, *, id=None, text=None, parse_mode=(), link_preview=True, geo=None, period=60, contact=None, game=False, buttons=None ): """ Creates a new inline result of photo type. Args: file (`obj`, optional): S...
Creates a new inline result of document type. `use_cache`, `mime_type`, `attributes`, `force_document`, `voice_note` and `video_note` are described in `client.send_file <telethon.client.uploads.UploadMethods.send_file>`. Args: file (`obj`): Same as ``file`` ...
async def document( self, file, title=None, *, description=None, type=None, mime_type=None, attributes=None, force_document=False, voice_note=False, video_note=False, use_cache=True, id=None, text=None, parse_mode=(), link_preview=True, geo=None, period=60, co...
Creates a new inline result of game type. Args: short_name (`str`): The short name of the game to use.
async def game( self, short_name, *, id=None, text=None, parse_mode=(), link_preview=True, geo=None, period=60, contact=None, game=False, buttons=None ): """ Creates a new inline result of game type. Args: short_name (`str`): T...
Sends a message to this dialog. This is just a wrapper around ``client.send_message(dialog.input_entity, *args, **kwargs)``.
async def send_message(self, *args, **kwargs): """ Sends a message to this dialog. This is just a wrapper around ``client.send_message(dialog.input_entity, *args, **kwargs)``. """ return await self._client.send_message( self.input_entity, *args, **kwargs)
Deletes the dialog from your dialog list. If you own the channel this won't destroy it, only delete it from the list.
async def delete(self): """ Deletes the dialog from your dialog list. If you own the channel this won't destroy it, only delete it from the list. """ if self.is_channel: await self._client(functions.channels.LeaveChannelRequest( self.input_entity)) ...
Reads an integer (4 bytes) value.
def read_int(self, signed=True): """Reads an integer (4 bytes) value.""" return int.from_bytes(self.read(4), byteorder='little', signed=signed)
Reads a long integer (8 bytes) value.
def read_long(self, signed=True): """Reads a long integer (8 bytes) value.""" return int.from_bytes(self.read(8), byteorder='little', signed=signed)
Reads a n-bits long integer value.
def read_large_int(self, bits, signed=True): """Reads a n-bits long integer value.""" return int.from_bytes( self.read(bits // 8), byteorder='little', signed=signed)
Read the given amount of bytes.
def read(self, length=None): """Read the given amount of bytes.""" if length is None: return self.reader.read() result = self.reader.read(length) if len(result) != length: raise BufferError( 'No more data left to read (need {}, got {}: {}); last r...
Reads a Telegram-encoded byte array, without the need of specifying its length.
def tgread_bytes(self): """ Reads a Telegram-encoded byte array, without the need of specifying its length. """ first_byte = self.read_byte() if first_byte == 254: length = self.read_byte() | (self.read_byte() << 8) | ( self.read_byte() << 16) ...
Reads a Telegram boolean value.
def tgread_bool(self): """Reads a Telegram boolean value.""" value = self.read_int(signed=False) if value == 0x997275b5: # boolTrue return True elif value == 0xbc799737: # boolFalse return False else: raise RuntimeError('Invalid boolean code ...
Reads and converts Unix time (used by Telegram) into a Python datetime object.
def tgread_date(self): """Reads and converts Unix time (used by Telegram) into a Python datetime object. """ value = self.read_int() if value == 0: return None else: return datetime.fromtimestamp(value, tz=timezone.utc)
Reads a Telegram object.
def tgread_object(self): """Reads a Telegram object.""" constructor_id = self.read_int(signed=False) clazz = tlobjects.get(constructor_id, None) if clazz is None: # The class was None, but there's still a # chance of it being a manually parsed value like bool! ...
Reads a vector (a list) of Telegram objects.
def tgread_vector(self): """Reads a vector (a list) of Telegram objects.""" if 0x1cb5c415 != self.read_int(signed=False): raise RuntimeError('Invalid constructor code, vector was expected') count = self.read_int() return [self.tgread_object() for _ in range(count)]
Factorizes the given large integer. :param pq: the prime pair pq. :return: a tuple containing the two factors p and q.
def factorize(cls, pq): """ Factorizes the given large integer. :param pq: the prime pair pq. :return: a tuple containing the two factors p and q. """ if pq % 2 == 0: return 2, pq // 2 y, c, m = randint(1, pq - 1), randint(1, pq - 1), randint(1, pq -...
Calculates the Greatest Common Divisor. :param a: the first number. :param b: the second number. :return: GCD(a, b)
def gcd(a, b): """ Calculates the Greatest Common Divisor. :param a: the first number. :param b: the second number. :return: GCD(a, b) """ while b: a, b = b, a % b return a
Creates a proxy object over the current :ref:`TelegramClient` through which making requests will use :tl:`InvokeWithTakeoutRequest` to wrap them. In other words, returns the current client modified so that requests are done as a takeout: >>> from telethon.sync import TelegramClient ...
def takeout( self, finalize=True, *, contacts=None, users=None, chats=None, megagroups=None, channels=None, files=None, max_file_size=None): """ Creates a proxy object over the current :ref:`TelegramClient` through which making requests will use :tl:`InvokeWithTakeoutRequ...
Finishes a takeout, with specified result sent back to Telegram. Returns: ``True`` if the operation was successful, ``False`` otherwise.
async def end_takeout(self, success): """ Finishes a takeout, with specified result sent back to Telegram. Returns: ``True`` if the operation was successful, ``False`` otherwise. """ try: async with _TakeoutClient(True, self, None) as takeout: ...
Converts all the methods in the given types (class definitions) into synchronous, which return either the coroutine or the result based on whether ``asyncio's`` event loop is running.
def syncify(*types): """ Converts all the methods in the given types (class definitions) into synchronous, which return either the coroutine or the result based on whether ``asyncio's`` event loop is running. """ # Our asynchronous generators all are `RequestIter`, which already # provide a ...
Returns (batch, data) if one or more items could be retrieved. If the cancellation occurs or only invalid items were in the queue, (None, None) will be returned instead.
async def get(self): """ Returns (batch, data) if one or more items could be retrieved. If the cancellation occurs or only invalid items were in the queue, (None, None) will be returned instead. """ if not self._deque: self._ready.clear() await se...
Establishes a connection with the server.
async def connect(self, timeout=None, ssl=None): """ Establishes a connection with the server. """ await self._connect(timeout=timeout, ssl=ssl) self._connected = True self._send_task = self._loop.create_task(self._send_loop()) self._recv_task = self._loop.create...
Disconnects from the server, and clears pending outgoing and incoming messages.
async def disconnect(self): """ Disconnects from the server, and clears pending outgoing and incoming messages. """ self._connected = False await helpers._cancel( self._log, send_task=self._send_task, recv_task=self._recv_task ...
Sends a packet of data through this connection mode. This method returns a coroutine.
def send(self, data): """ Sends a packet of data through this connection mode. This method returns a coroutine. """ if not self._connected: raise ConnectionError('Not connected') return self._send_queue.put(data)
Receives a packet of data through this connection mode. This method returns a coroutine.
async def recv(self): """ Receives a packet of data through this connection mode. This method returns a coroutine. """ while self._connected: result = await self._recv_queue.get() if result: # None = sentinel value = keep trying return re...
This loop is constantly popping items off the queue to send them.
async def _send_loop(self): """ This loop is constantly popping items off the queue to send them. """ try: while self._connected: self._send(await self._send_queue.get()) await self._writer.drain() except asyncio.CancelledError: ...
This loop is constantly putting items on the queue as they're read.
async def _recv_loop(self): """ This loop is constantly putting items on the queue as they're read. """ while self._connected: try: data = await self._recv() except asyncio.CancelledError: break except Exception as e: ...
This method will be called after `connect` is called. After this method finishes, the writer will be drained. Subclasses should make use of this if they need to send data to Telegram to indicate which connection mode will be used.
def _init_conn(self): """ This method will be called after `connect` is called. After this method finishes, the writer will be drained. Subclasses should make use of this if they need to send data to Telegram to indicate which connection mode will be used. """ ...
Calls bytes(request), and based on a certain threshold, optionally gzips the resulting data. If the gzipped data is smaller than the original byte array, this is returned instead. Note that this only applies to content related requests.
def gzip_if_smaller(content_related, data): """Calls bytes(request), and based on a certain threshold, optionally gzips the resulting data. If the gzipped data is smaller than the original byte array, this is returned instead. Note that this only applies to content related requ...
Returns the arguments properly sorted and ready to plug-in into a Python's method header (i.e., flags and those which can be inferred will go last so they can default =None)
def sorted_args(self): """Returns the arguments properly sorted and ready to plug-in into a Python's method header (i.e., flags and those which can be inferred will go last so they can default =None) """ return sorted(self.args, key=lambda x: x.is_flag...
Asserts that the connection is open and returns a cursor
def _cursor(self): """Asserts that the connection is open and returns a cursor""" if self._conn is None: self._conn = sqlite3.connect(self.filename, check_same_thread=False) return self._conn.cursor()
Closes the connection unless we're working in-memory
def close(self): """Closes the connection unless we're working in-memory""" if self.filename != ':memory:': if self._conn is not None: self._conn.commit() self._conn.close() self._conn = None
Gets a cursor, executes `stmt` and closes the cursor, fetching one row afterwards and returning its result.
def _execute(self, stmt, *values): """ Gets a cursor, executes `stmt` and closes the cursor, fetching one row afterwards and returning its result. """ c = self._cursor() try: return c.execute(stmt, values).fetchone() finally: c.close()
Deletes the current session file
def delete(self): """Deletes the current session file""" if self.filename == ':memory:': return True try: os.remove(self.filename) return True except OSError: return False
Lists all the sessions of the users who have ever connected using this client and never logged out
def list_sessions(cls): """Lists all the sessions of the users who have ever connected using this client and never logged out """ return [os.path.splitext(os.path.basename(f))[0] for f in os.listdir('.') if f.endswith(EXTENSION)]
Processes all the found entities on the given TLObject, unless .enabled is False. Returns True if new input entities were added.
def process_entities(self, tlo): """Processes all the found entities on the given TLObject, unless .enabled is False. Returns True if new input entities were added. """ if not self.save_entities: return rows = self._entities_to_rows(tlo) if not...
Parses the input CSV file with columns (method, usability, errors) and yields `MethodInfo` instances as a result.
def parse_methods(csv_file, errors_dict): """ Parses the input CSV file with columns (method, usability, errors) and yields `MethodInfo` instances as a result. """ with csv_file.open(newline='') as f: f = csv.reader(f) next(f, None) # header for line, (method, usability, err...
Connects to Telegram.
async def connect(self): """ Connects to Telegram. """ await self._sender.connect(self._connection( self.session.server_address, self.session.port, self.session.dc_id, loop=self._loop, loggers=self._log, proxy=self._...
Disconnect only, without closing the session. Used in reconnections to different data centers, where we don't want to close the session file; user disconnects however should close it since it means that their job with the client is complete and we should clean it up all.
async def _disconnect(self): """ Disconnect only, without closing the session. Used in reconnections to different data centers, where we don't want to close the session file; user disconnects however should close it since it means that their job with the client is complete and we...
Disconnects from Telegram. If the event loop is already running, this method returns a coroutine that you should await on your own code; otherwise the loop is ran until said coroutine completes.
def disconnect(self): """ Disconnects from Telegram. If the event loop is already running, this method returns a coroutine that you should await on your own code; otherwise the loop is ran until said coroutine completes. """ if self._loop.is_running(): ...
Permanently switches the current connection to the new data center.
async def _switch_dc(self, new_dc): """ Permanently switches the current connection to the new data center. """ self._log[__name__].info('Reconnecting to new data center %s', new_dc) dc = await self._get_dc(new_dc) self.session.set_dc(dc.id, dc.ip_address, dc.port) ...
Callback from the sender whenever it needed to generate a new authorization key. This means we are not authorized.
def _auth_key_callback(self, auth_key): """ Callback from the sender whenever it needed to generate a new authorization key. This means we are not authorized. """ self.session.auth_key = auth_key self.session.save()
Gets the Data Center (DC) associated to 'dc_id
async def _get_dc(self, dc_id, cdn=False): """Gets the Data Center (DC) associated to 'dc_id'""" cls = self.__class__ if not cls._config: cls._config = await self(functions.help.GetConfigRequest()) if cdn and not self._cdn_config: cls._cdn_config = await self(fun...
Creates a new exported `MTProtoSender` for the given `dc_id` and returns it. This method should be used by `_borrow_exported_sender`.
async def _create_exported_sender(self, dc_id): """ Creates a new exported `MTProtoSender` for the given `dc_id` and returns it. This method should be used by `_borrow_exported_sender`. """ # Thanks badoualy/kotlogram on /telegram/api/DefaultTelegramClient.kt # for clearl...
Borrows a connected `MTProtoSender` for the given `dc_id`. If it's not cached, creates a new one if it doesn't exist yet, and imports a freshly exported authorization key for it to be usable. Once its job is over it should be `_return_exported_sender`.
async def _borrow_exported_sender(self, dc_id): """ Borrows a connected `MTProtoSender` for the given `dc_id`. If it's not cached, creates a new one if it doesn't exist yet, and imports a freshly exported authorization key for it to be usable. Once its job is over it should be `...