INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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: | 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. | 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:
... |
This loop is responsible for reading all incoming responses from the network decrypting and handling or dispatching them. | async def _recv_loop(self):
"""
This loop is responsible for reading all incoming responses
from the network, decrypting and handling or dispatching them.
Besides `connect`, only this method ever receives 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. | 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: | 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: | 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: | 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: | 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: | 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: | 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: | 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: | 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: | 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: | 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. | 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. | 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. | 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. | 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. | 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. | 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: | 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. | 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. | 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. | 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. | 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. | 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. | 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() |
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() |
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 |
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. | 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._... |
Disconnects from Telegram. | 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():
... |
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... |
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. | 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 `... |
Returns a borrowed exported sender. If all borrows have been returned the sender is cleanly disconnected. | async def _return_exported_sender(self, sender):
"""
Returns a borrowed exported sender. If all borrows have
been returned, the sender is cleanly disconnected.
"""
async with self._borrow_sender_lock:
dc_id = sender.dc_id
n, _ = self._borrowed_senders[dc_i... |
Similar to. _borrow_exported_client but for CDNs | async def _get_cdn_client(self, cdn_redirect):
"""Similar to ._borrow_exported_client, but for CDNs"""
# TODO Implement
raise NotImplementedError
session = self._exported_sessions.get(cdn_redirect.dc_id)
if not session:
dc = await self._get_dc(cdn_redirect.dc_id, cdn=... |
Turns the given iterable into chunks of the specified size which is 100 by default since that s what Telegram uses the most. | def chunks(iterable, size=100):
"""
Turns the given iterable into chunks of the specified size,
which is 100 by default since that's what Telegram uses the most.
"""
it = iter(iterable)
size -= 1
for head in it:
yield itertools.chain([head], itertools.islice(it, size)) |
Gets the display name for the given entity if it s an: tl: User: tl: Chat or: tl: Channel. Returns an empty string otherwise. | def get_display_name(entity):
"""
Gets the display name for the given entity, if it's an :tl:`User`,
:tl:`Chat` or :tl:`Channel`. Returns an empty string otherwise.
"""
if isinstance(entity, types.User):
if entity.last_name and entity.first_name:
return '{} {}'.format(entity.firs... |
Gets the corresponding extension for any Telegram media. | def get_extension(media):
"""Gets the corresponding extension for any Telegram media."""
# Photos are always compressed as .jpg by Telegram
if isinstance(media, (types.UserProfilePhoto,
types.ChatPhoto, types.MessageMediaPhoto)):
return '.jpg'
# Documents will come wi... |
Gets the input peer for the given entity ( user chat or channel ). | def get_input_peer(entity, allow_self=True, check_hash=True):
"""
Gets the input peer for the given "entity" (user, chat or channel).
A ``TypeError`` is raised if the given entity isn't a supported type
or if ``check_hash is True`` but the entity's ``access_hash is None``.
Note that ``check_hash``... |
Similar to: meth: get_input_peer but for: tl: InputChannel s alone. | def get_input_channel(entity):
"""Similar to :meth:`get_input_peer`, but for :tl:`InputChannel`'s alone."""
try:
if entity.SUBCLASS_OF_ID == 0x40f202fd: # crc32(b'InputChannel')
return entity
except AttributeError:
_raise_cast_fail(entity, 'InputChannel')
if isinstance(enti... |
Similar to: meth: get_input_peer but for: tl: InputUser s alone. | def get_input_user(entity):
"""Similar to :meth:`get_input_peer`, but for :tl:`InputUser`'s alone."""
try:
if entity.SUBCLASS_OF_ID == 0xe669bf46: # crc32(b'InputUser'):
return entity
except AttributeError:
_raise_cast_fail(entity, 'InputUser')
if isinstance(entity, types.U... |
Similar to: meth: get_input_peer but for dialogs | def get_input_dialog(dialog):
"""Similar to :meth:`get_input_peer`, but for dialogs"""
try:
if dialog.SUBCLASS_OF_ID == 0xa21c9795: # crc32(b'InputDialogPeer')
return dialog
if dialog.SUBCLASS_OF_ID == 0xc91c90b6: # crc32(b'InputPeer')
return types.InputDialogPeer(dialo... |
Similar to: meth: get_input_peer but for documents | def get_input_document(document):
"""Similar to :meth:`get_input_peer`, but for documents"""
try:
if document.SUBCLASS_OF_ID == 0xf33fdb68: # crc32(b'InputDocument'):
return document
except AttributeError:
_raise_cast_fail(document, 'InputDocument')
if isinstance(document, ... |
Similar to: meth: get_input_peer but for photos | def get_input_photo(photo):
"""Similar to :meth:`get_input_peer`, but for photos"""
try:
if photo.SUBCLASS_OF_ID == 0x846363e0: # crc32(b'InputPhoto'):
return photo
except AttributeError:
_raise_cast_fail(photo, 'InputPhoto')
if isinstance(photo, types.photos.Photo):
... |
Similar to: meth: get_input_peer but for chat photos | def get_input_chat_photo(photo):
"""Similar to :meth:`get_input_peer`, but for chat photos"""
try:
if photo.SUBCLASS_OF_ID == 0xd4eb2d74: # crc32(b'InputChatPhoto')
return photo
elif photo.SUBCLASS_OF_ID == 0xe7655f1f: # crc32(b'InputFile'):
return types.InputChatUpload... |
Similar to: meth: get_input_peer but for geo points | def get_input_geo(geo):
"""Similar to :meth:`get_input_peer`, but for geo points"""
try:
if geo.SUBCLASS_OF_ID == 0x430d225: # crc32(b'InputGeoPoint'):
return geo
except AttributeError:
_raise_cast_fail(geo, 'InputGeoPoint')
if isinstance(geo, types.GeoPoint):
retur... |
Similar to: meth: get_input_peer but for media. | def get_input_media(
media, *,
is_photo=False, attributes=None, force_document=False,
voice_note=False, video_note=False, supports_streaming=False
):
"""
Similar to :meth:`get_input_peer`, but for media.
If the media is :tl:`InputFile` and ``is_photo`` is known to be ``True``,
i... |
Similar to: meth: get_input_peer but for input messages. | def get_input_message(message):
"""Similar to :meth:`get_input_peer`, but for input messages."""
try:
if isinstance(message, int): # This case is really common too
return types.InputMessageID(message)
elif message.SUBCLASS_OF_ID == 0x54b6bcc5: # crc32(b'InputMessage'):
... |
Similar to: meth: get_input_peer but for message IDs. | def get_message_id(message):
"""Similar to :meth:`get_input_peer`, but for message IDs."""
if message is None:
return None
if isinstance(message, int):
return message
try:
if message.SUBCLASS_OF_ID == 0x790009e3:
# hex(crc32(b'Message')) = 0x790009e3
ret... |
Get a list of attributes for the given file and the mime type as a tuple ( [ attribute ] mime_type ). | def get_attributes(file, *, attributes=None, mime_type=None,
force_document=False, voice_note=False, video_note=False,
supports_streaming=False):
"""
Get a list of attributes for the given file and
the mime type as a tuple ([attribute], mime_type).
"""
# Note: `... |
Converts the given parse mode into an object with parse and unparse callable properties. | def sanitize_parse_mode(mode):
"""
Converts the given parse mode into an object with
``parse`` and ``unparse`` callable properties.
"""
if not mode:
return None
if callable(mode):
class CustomMode:
@staticmethod
def unparse(text, entities):
... |
Similar to: meth: get_input_peer but for input messages. | def get_input_location(location):
"""
Similar to :meth:`get_input_peer`, but for input messages.
Note that this returns a tuple ``(dc_id, location)``, the
``dc_id`` being present if known.
"""
try:
if location.SUBCLASS_OF_ID == 0x1523d462:
return None, location # crc32(b'In... |
Gets the extension for the given file which can be either a str or an open () ed file ( which has a. name attribute ). | def _get_extension(file):
"""
Gets the extension for the given file, which can be either a
str or an ``open()``'ed file (which has a ``.name`` attribute).
"""
if isinstance(file, str):
return os.path.splitext(file)[-1]
elif isinstance(file, bytes):
kind = imghdr.what(io.BytesIO(f... |
Returns True if the file extension looks like an image file to Telegram. | def is_image(file):
"""
Returns ``True`` if the file extension looks like an image file to Telegram.
"""
match = re.match(r'\.(png|jpe?g)', _get_extension(file), re.IGNORECASE)
if match:
return True
else:
return isinstance(resolve_bot_file_id(file), types.Photo) |
Parses the given phone or returns None if it s invalid. | def parse_phone(phone):
"""Parses the given phone, or returns ``None`` if it's invalid."""
if isinstance(phone, int):
return str(phone)
else:
phone = re.sub(r'[+()\s-]', '', str(phone))
if phone.isdigit():
return phone |
Parses the given username or channel access hash given a string username or URL. Returns a tuple consisting of both the stripped lowercase username and whether it is a joinchat/ hash ( in which case is not lowercase d ). | def parse_username(username):
"""
Parses the given username or channel access hash, given
a string, username or URL. Returns a tuple consisting of
both the stripped, lowercase username and whether it is
a joinchat/ hash (in which case is not lowercase'd).
Returns ``(None, False)`` if the ``user... |
Gets the inner text that s surrounded by the given entities. For instance: text = hey! entity = MessageEntityBold ( 2 2 ) - > y!. | def get_inner_text(text, entities):
"""
Gets the inner text that's surrounded by the given entities.
For instance: text = 'hey!', entity = MessageEntityBold(2, 2) -> 'y!'.
:param text: the original text.
:param entities: the entity or entities that must be matched.
:return: a single result ... |
Finds the ID of the given peer and converts it to the bot api format so it the peer can be identified back. User ID is left unmodified chat ID is negated and channel ID is prefixed with - 100. | def get_peer_id(peer, add_mark=True):
"""
Finds the ID of the given peer, and converts it to the "bot api" format
so it the peer can be identified back. User ID is left unmodified,
chat ID is negated, and channel ID is prefixed with -100.
The original ID and the peer type class can be returned with... |
Given a marked ID returns the original ID and its: tl: Peer type. | def resolve_id(marked_id):
"""Given a marked ID, returns the original ID and its :tl:`Peer` type."""
if marked_id >= 0:
return marked_id, types.PeerUser
# There have been report of chat IDs being 10000xyz, which means their
# marked version is -10000xyz, which in turn looks like a channel but
... |
Decodes run - length - encoded data. | def _rle_decode(data):
"""
Decodes run-length-encoded `data`.
"""
if not data:
return data
new = b''
last = b''
for cur in data:
if last == b'\0':
new += last * cur
last = b''
else:
new += last
last = bytes([cur])
... |
Decodes an url - safe base64 - encoded string into its bytes by first adding the stripped necessary padding characters. | def _decode_telegram_base64(string):
"""
Decodes an url-safe base64-encoded string into its bytes
by first adding the stripped necessary padding characters.
This is the way Telegram shares binary data as strings,
such as Bot API-style file IDs or invite links.
Returns ``None`` if the input str... |
Inverse for _decode_telegram_base64. | def _encode_telegram_base64(string):
"""
Inverse for `_decode_telegram_base64`.
"""
try:
return base64.urlsafe_b64encode(string).rstrip(b'=').decode('ascii')
except (binascii.Error, ValueError, TypeError):
return None |
Given a Bot API - style file_id returns the media it represents. If the file_id is not valid None is returned instead. | def resolve_bot_file_id(file_id):
"""
Given a Bot API-style `file_id`, returns the media it represents.
If the `file_id` is not valid, ``None`` is returned instead.
Note that the `file_id` does not have information such as image
dimensions or file size, so these will be zero if present.
For th... |
Inverse operation for resolve_bot_file_id. | def pack_bot_file_id(file):
"""
Inverse operation for `resolve_bot_file_id`.
The only parameters this method will accept are :tl:`Document` and
:tl:`Photo`, and it will return a variable-length ``file_id`` string.
If an invalid parameter is given, it will ``return None``.
"""
if isinstance... |
Resolves the given invite link. Returns a tuple of ( link creator user id global chat id random int ). | def resolve_invite_link(link):
"""
Resolves the given invite link. Returns a tuple of
``(link creator user id, global chat id, random int)``.
Note that for broadcast channels, the link creator
user ID will be zero to protect their identity.
Normal chats and megagroup channels will have such ID.... |
Resolves an inline message ID. Returns a tuple of ( message id peer dc id access hash ) | def resolve_inline_message_id(inline_msg_id):
"""
Resolves an inline message ID. Returns a tuple of
``(message id, peer, dc id, access hash)``
The ``peer`` may either be a :tl:`PeerUser` referencing
the user who sent the message via the bot in a private
conversation or small group chat, or a :t... |
Adds the JPG header and footer to a stripped image. | def stripped_photo_to_jpg(stripped):
"""
Adds the JPG header and footer to a stripped image.
Ported from https://github.com/telegramdesktop/tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225
"""
if len(stripped) < 3 or stripped[0] != 1:
retur... |
Sends and receives the result for the given request. | async def send(self, request):
"""
Sends and receives the result for the given request.
"""
body = bytes(request)
msg_id = self._state._get_new_msg_id()
await self._connection.send(
struct.pack('<qqi', 0, msg_id, len(body)) + body
)
body = awa... |
Get the relative path for the given path from the current file by working around https:// bugs. python. org/ issue20012. | def _rel(self, path):
"""
Get the relative path for the given path from the current
file by working around https://bugs.python.org/issue20012.
"""
return os.path.relpath(
str(path), self._parent).replace(os.path.sep, '/') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.