Move alltlobjects.py and fix imports

This commit is contained in:
Lonami Exo 2021-09-12 16:58:06 +02:00
parent 5fd2a017b2
commit 499fc9f603
32 changed files with 145 additions and 158 deletions

View File

@ -6,7 +6,6 @@ from ._misc import hints # depends on types/custom
from ._client.telegramclient import TelegramClient from ._client.telegramclient import TelegramClient
from ._network import connection from ._network import connection
from ._tl.custom import Button
from . import version, events, utils, errors from . import version, events, utils, errors
__version__ = version.__version__ __version__ = version.__version__

View File

@ -7,7 +7,7 @@ import warnings
from .._misc import utils, helpers, password as pwd_mod from .._misc import utils, helpers, password as pwd_mod
from .. import errors, _tl from .. import errors, _tl
from .._tl import custom from ..types import _custom
if typing.TYPE_CHECKING: if typing.TYPE_CHECKING:
from .telegramclient import TelegramClient from .telegramclient import TelegramClient
@ -343,8 +343,8 @@ async def send_code_request(
return result return result
async def qr_login(self: 'TelegramClient', ignored_ids: typing.List[int] = None) -> custom.QRLogin: async def qr_login(self: 'TelegramClient', ignored_ids: typing.List[int] = None) -> _custom.QRLogin:
qr_login = custom.QRLogin(self, ignored_ids or []) qr_login = _custom.QRLogin(self, ignored_ids or [])
await qr_login.recreate() await qr_login.recreate()
return qr_login return qr_login

View File

@ -1,7 +1,7 @@
import typing import typing
from .. import hints, _tl from .. import hints, _tl
from .._tl import custom from ..types import _custom
if typing.TYPE_CHECKING: if typing.TYPE_CHECKING:
from .telegramclient import TelegramClient from .telegramclient import TelegramClient
@ -14,7 +14,7 @@ async def inline_query(
*, *,
entity: 'hints.EntityLike' = None, entity: 'hints.EntityLike' = None,
offset: str = None, offset: str = None,
geo_point: '_tl.GeoPoint' = None) -> custom.InlineResults: geo_point: '_tl.GeoPoint' = None) -> _custom.InlineResults:
bot = await self.get_input_entity(bot) bot = await self.get_input_entity(bot)
if entity: if entity:
peer = await self.get_input_entity(entity) peer = await self.get_input_entity(entity)
@ -29,4 +29,4 @@ async def inline_query(
geo_point=geo_point geo_point=geo_point
)) ))
return custom.InlineResults(self, result, entity=peer if entity else None) return _custom.InlineResults(self, result, entity=peer if entity else None)

View File

@ -2,7 +2,7 @@ import typing
from .._misc import utils, hints from .._misc import utils, hints
from .. import _tl from .. import _tl
from .._tl import custom from ..types import _custom
def build_reply_markup( def build_reply_markup(
@ -32,7 +32,7 @@ def build_reply_markup(
for row in buttons: for row in buttons:
current = [] current = []
for button in row: for button in row:
if isinstance(button, custom.Button): if isinstance(button, _custom.Button):
if button.resize is not None: if button.resize is not None:
resize = button.resize resize = button.resize
if button.single_use is not None: if button.single_use is not None:
@ -41,10 +41,10 @@ def build_reply_markup(
selective = button.selective selective = button.selective
button = button.button button = button.button
elif isinstance(button, custom.MessageButton): elif isinstance(button, _custom.MessageButton):
button = button.button button = button.button
inline = custom.Button._is_inline(button) inline = _custom.Button._is_inline(button)
is_inline |= inline is_inline |= inline
is_normal |= not inline is_normal |= not inline

View File

@ -5,8 +5,8 @@ import string
import typing import typing
from .. import hints, errors, _tl from .. import hints, errors, _tl
from .._misc import helpers, utils, requestiter from .._misc import helpers, utils, requestiter, tlobject
from .._tl import custom from ..types import _custom
if typing.TYPE_CHECKING: if typing.TYPE_CHECKING:
from .telegramclient import TelegramClient from .telegramclient import TelegramClient
@ -302,7 +302,7 @@ class _AdminLogIter(requestiter.RequestIter):
ev.action.message._finish_init( ev.action.message._finish_init(
self.client, entities, self.entity) self.client, entities, self.entity)
self.buffer.append(custom.AdminLogEvent(ev, entities)) self.buffer.append(_custom.AdminLogEvent(ev, entities))
if len(r.events) < self.request.limit: if len(r.events) < self.request.limit:
return True return True
@ -516,7 +516,7 @@ def action(
except KeyError: except KeyError:
raise ValueError( raise ValueError(
'No such action "{}"'.format(action)) from None 'No such action "{}"'.format(action)) from None
elif not isinstance(action, _tl.TLObject) or action.SUBCLASS_OF_ID != 0x20b2cc21: elif not isinstance(action, tlobject.TLObject) or action.SUBCLASS_OF_ID != 0x20b2cc21:
# 0x20b2cc21 = crc32(b'SendMessageAction') # 0x20b2cc21 = crc32(b'SendMessageAction')
if isinstance(action, type): if isinstance(action, type):
raise ValueError('You must pass an instance, not the class') raise ValueError('You must pass an instance, not the class')
@ -716,7 +716,7 @@ async def get_permissions(
entity, entity,
user user
)) ))
return custom.ParticipantPermissions(participant.participant, False) return _custom.ParticipantPermissions(participant.participant, False)
elif helpers._entity_type(entity) == helpers._EntityType.CHAT: elif helpers._entity_type(entity) == helpers._EntityType.CHAT:
chat = await self(_tl.fn.messages.GetFullChat( chat = await self(_tl.fn.messages.GetFullChat(
entity entity
@ -725,7 +725,7 @@ async def get_permissions(
user = await self.get_me(input_peer=True) user = await self.get_me(input_peer=True)
for participant in chat.full_chat.participants.participants: for participant in chat.full_chat.participants.participants:
if participant.user_id == user.user_id: if participant.user_id == user.user_id:
return custom.ParticipantPermissions(participant, True) return _custom.ParticipantPermissions(participant, True)
raise errors.UserNotParticipantError(None) raise errors.UserNotParticipantError(None)
raise ValueError('You must pass either a channel or a chat') raise ValueError('You must pass either a channel or a chat')

View File

@ -5,7 +5,7 @@ import typing
from .. import hints, errors, _tl from .. import hints, errors, _tl
from .._misc import helpers, utils, requestiter from .._misc import helpers, utils, requestiter
from .._tl import custom from ..types import _custom
_MAX_CHUNK_SIZE = 100 _MAX_CHUNK_SIZE = 100
@ -80,7 +80,7 @@ class _DialogsIter(requestiter.RequestIter):
# Real world example: https://t.me/TelethonChat/271471 # Real world example: https://t.me/TelethonChat/271471
continue continue
cd = custom.Dialog(self.client, d, entities, message) cd = _custom.Dialog(self.client, d, entities, message)
if cd.dialog.pts: if cd.dialog.pts:
self.client._channel_pts[cd.id] = cd.dialog.pts self.client._channel_pts[cd.id] = cd.dialog.pts
@ -128,7 +128,7 @@ class _DraftsIter(requestiter.RequestIter):
for x in itertools.chain(r.users, r.chats)} for x in itertools.chain(r.users, r.chats)}
self.buffer.extend( self.buffer.extend(
custom.Draft(self.client, entities[utils.get_peer_id(d.peer)], d.draft) _custom.Draft(self.client, entities[utils.get_peer_id(d.peer)], d.draft)
for d in items for d in items
) )

View File

@ -7,7 +7,7 @@ import inspect
import asyncio import asyncio
from .._crypto import AES from .._crypto import AES
from .._misc import utils, helpers, requestiter from .._misc import utils, helpers, requestiter, tlobject
from .. import errors, hints, _tl from .. import errors, hints, _tl
try: try:
@ -198,7 +198,7 @@ async def download_profile_photo(
ENTITIES = (0x2da17977, 0xc5af5d94, 0x1f4661b9, 0xd49a2697) ENTITIES = (0x2da17977, 0xc5af5d94, 0x1f4661b9, 0xd49a2697)
# ('InputPeer', 'InputUser', 'InputChannel') # ('InputPeer', 'InputUser', 'InputChannel')
INPUTS = (0xc91c90b6, 0xe669bf46, 0x40f202fd) INPUTS = (0xc91c90b6, 0xe669bf46, 0x40f202fd)
if not isinstance(entity, _tl.TLObject) or entity.SUBCLASS_OF_ID in INPUTS: if not isinstance(entity, tlobject.TLObject) or entity.SUBCLASS_OF_ID in INPUTS:
entity = await self.get_entity(entity) entity = await self.get_entity(entity)
thumb = -1 if download_big else 0 thumb = -1 if download_big else 0

View File

@ -11,7 +11,6 @@ from .. import version, helpers, __name__ as __base_name__, _tl
from .._crypto import rsa from .._crypto import rsa
from .._misc import markdown, entitycache, statecache from .._misc import markdown, entitycache, statecache
from .._network import MTProtoSender, Connection, ConnectionTcpFull, TcpMTProxy from .._network import MTProtoSender, Connection, ConnectionTcpFull, TcpMTProxy
from .._tl.alltlobjects import LAYER
from ..sessions import Session, SQLiteSession, MemorySession from ..sessions import Session, SQLiteSession, MemorySession
DEFAULT_DC_ID = 2 DEFAULT_DC_ID = 2
@ -322,7 +321,7 @@ async def connect(self: 'TelegramClient') -> None:
self._init_request.query = _tl.fn.help.GetConfig() self._init_request.query = _tl.fn.help.GetConfig()
await self._sender.send(_tl.fn.InvokeWithLayer( await self._sender.send(_tl.fn.InvokeWithLayer(
LAYER, self._init_request _tl.LAYER, self._init_request
)) ))
self._updates_handle = self.loop.create_task(self._update_loop()) self._updates_handle = self.loop.create_task(self._update_loop())

View File

@ -9,7 +9,7 @@ from . import (
telegrambaseclient, updates, uploads, users telegrambaseclient, updates, uploads, users
) )
from .. import helpers, version, _tl from .. import helpers, version, _tl
from .._tl import custom from ..types import _custom
from .._network import ConnectionTcpFull from .._network import ConnectionTcpFull
from ..events.common import EventBuilder, EventCommon from ..events.common import EventBuilder, EventCommon
@ -500,7 +500,7 @@ class TelegramClient:
""" """
return await auth.send_code_request(**locals()) return await auth.send_code_request(**locals())
async def qr_login(self: 'TelegramClient', ignored_ids: typing.List[int] = None) -> custom.QRLogin: async def qr_login(self: 'TelegramClient', ignored_ids: typing.List[int] = None) -> _custom.QRLogin:
""" """
Initiates the QR login procedure. Initiates the QR login procedure.
@ -630,7 +630,7 @@ class TelegramClient:
*, *,
entity: 'hints.EntityLike' = None, entity: 'hints.EntityLike' = None,
offset: str = None, offset: str = None,
geo_point: '_tl.GeoPoint' = None) -> custom.InlineResults: geo_point: '_tl.GeoPoint' = None) -> _custom.InlineResults:
""" """
Makes an inline query to the specified bot (``@vote New Poll``). Makes an inline query to the specified bot (``@vote New Poll``).
@ -658,8 +658,8 @@ class TelegramClient:
for localised results. Available under some bots. for localised results. Available under some bots.
Returns Returns
A list of `custom.InlineResult A list of `_custom.InlineResult
<telethon.tl.custom.inlineresult.InlineResult>`. <telethon.tl._custom.inlineresult.InlineResult>`.
Example Example
.. code-block:: python .. code-block:: python
@ -923,7 +923,7 @@ class TelegramClient:
If `True`, events related to group calls will be returned. If `True`, events related to group calls will be returned.
Yields Yields
Instances of `AdminLogEvent <telethon.tl.custom.adminlogevent.AdminLogEvent>`. Instances of `AdminLogEvent <telethon.tl._custom.adminlogevent.AdminLogEvent>`.
Example Example
.. code-block:: python .. code-block:: python
@ -1161,8 +1161,8 @@ class TelegramClient:
.. note:: .. note::
Users may be able to identify the anonymous admin by its Users may be able to identify the anonymous admin by its
custom title, so additional care is needed when using both _custom title, so additional care is needed when using both
``anonymous`` and custom titles. For example, if multiple ``anonymous`` and _custom titles. For example, if multiple
anonymous admins share the same title, users won't be able anonymous admins share the same title, users won't be able
to distinguish them. to distinguish them.
@ -1178,7 +1178,7 @@ class TelegramClient:
permissions, but you can still disable those you need. permissions, but you can still disable those you need.
title (`str`, optional): title (`str`, optional):
The custom title (also known as "rank") to show for this admin. The _custom title (also known as "rank") to show for this admin.
This text will be shown instead of the "admin" badge. This text will be shown instead of the "admin" badge.
This will only work in channels and megagroups. This will only work in channels and megagroups.
@ -1340,7 +1340,7 @@ class TelegramClient:
The user to kick. The user to kick.
Returns Returns
Returns the service `Message <telethon.tl.custom.message.Message>` Returns the service `Message <telethon.tl._custom.message.Message>`
produced about a user being kicked, if any. produced about a user being kicked, if any.
Example Example
@ -1359,7 +1359,7 @@ class TelegramClient:
self: 'TelegramClient', self: 'TelegramClient',
entity: 'hints.EntityLike', entity: 'hints.EntityLike',
user: 'hints.EntityLike' = None user: 'hints.EntityLike' = None
) -> 'typing.Optional[custom.ParticipantPermissions]': ) -> 'typing.Optional[_custom.ParticipantPermissions]':
""" """
Fetches the permissions of a user in a specific chat or channel or Fetches the permissions of a user in a specific chat or channel or
get Default Restricted Rights of Chat or Channel. get Default Restricted Rights of Chat or Channel.
@ -1377,7 +1377,7 @@ class TelegramClient:
Target user. Target user.
Returns Returns
A `ParticipantPermissions <telethon.tl.custom.participantpermissions.ParticipantPermissions>` A `ParticipantPermissions <telethon.tl._custom.participantpermissions.ParticipantPermissions>`
instance. Refer to its documentation to see what properties are instance. Refer to its documentation to see what properties are
available. available.
@ -1509,7 +1509,7 @@ class TelegramClient:
Alias for `folder`. If unspecified, all will be returned, Alias for `folder`. If unspecified, all will be returned,
`False` implies ``folder=0`` and `True` implies ``folder=1``. `False` implies ``folder=0`` and `True` implies ``folder=1``.
Yields Yields
Instances of `Dialog <telethon.tl.custom.dialog.Dialog>`. Instances of `Dialog <telethon.tl._custom.dialog.Dialog>`.
Example Example
.. code-block:: python .. code-block:: python
@ -1563,7 +1563,7 @@ class TelegramClient:
If left unspecified, all draft messages will be returned. If left unspecified, all draft messages will be returned.
Yields Yields
Instances of `Draft <telethon.tl.custom.draft.Draft>`. Instances of `Draft <telethon.tl._custom.draft.Draft>`.
Example Example
.. code-block:: python .. code-block:: python
@ -1670,7 +1670,7 @@ class TelegramClient:
bots will only be able to use it to leave groups and channels bots will only be able to use it to leave groups and channels
(trying to delete a private conversation will do nothing). (trying to delete a private conversation will do nothing).
See also `Dialog.delete() <telethon.tl.custom.dialog.Dialog.delete>`. See also `Dialog.delete() <telethon.tl._custom.dialog.Dialog.delete>`.
Arguments Arguments
entity (entities): entity (entities):
@ -1765,10 +1765,10 @@ class TelegramClient:
``cryptg`` (through ``pip install cryptg``) so that decrypting the ``cryptg`` (through ``pip install cryptg``) so that decrypting the
received data is done in C instead of Python (much faster). received data is done in C instead of Python (much faster).
See also `Message.download_media() <telethon.tl.custom.message.Message.download_media>`. See also `Message.download_media() <telethon.tl._custom.message.Message.download_media>`.
Arguments Arguments
message (`Message <telethon.tl.custom.message.Message>` | :tl:`Media`): message (`Message <telethon.tl._custom.message.Message>` | :tl:`Media`):
The media or message containing the media that will be downloaded. The media or message containing the media that will be downloaded.
file (`str` | `file`, optional): file (`str` | `file`, optional):
@ -2186,7 +2186,7 @@ class TelegramClient:
All other parameter will be ignored for this, except `entity`. All other parameter will be ignored for this, except `entity`.
Yields Yields
Instances of `Message <telethon.tl.custom.message.Message>`. Instances of `Message <telethon.tl._custom.message.Message>`.
Example Example
.. code-block:: python .. code-block:: python
@ -2232,7 +2232,7 @@ class TelegramClient:
specified it makes sense that it should return the entirety of it. specified it makes sense that it should return the entirety of it.
If `ids` is present in the *named* arguments and is not a list, If `ids` is present in the *named* arguments and is not a list,
a single `Message <telethon.tl.custom.message.Message>` will be a single `Message <telethon.tl._custom.message.Message>` will be
returned for convenience instead of a list. returned for convenience instead of a list.
Example Example
@ -2278,7 +2278,7 @@ class TelegramClient:
Sends a message to the specified user, chat or channel. Sends a message to the specified user, chat or channel.
The default parse mode is the same as the official applications The default parse mode is the same as the official applications
(a custom flavour of markdown). ``**bold**, `code` or __italic__`` (a _custom flavour of markdown). ``**bold**, `code` or __italic__``
are available. In addition you can send ``[links](https://example.com)`` are available. In addition you can send ``[links](https://example.com)``
and ``[mentions](@username)`` (or using IDs like in the Bot API: and ``[mentions](@username)`` (or using IDs like in the Bot API:
``[mention](tg://user?id=123456789)``) and ``pre`` blocks with three ``[mention](tg://user?id=123456789)``) and ``pre`` blocks with three
@ -2288,14 +2288,14 @@ class TelegramClient:
is also done through this method. Simply send ``'/start data'`` to is also done through this method. Simply send ``'/start data'`` to
the bot. the bot.
See also `Message.respond() <telethon.tl.custom.message.Message.respond>` See also `Message.respond() <telethon.tl._custom.message.Message.respond>`
and `Message.reply() <telethon.tl.custom.message.Message.reply>`. and `Message.reply() <telethon.tl._custom.message.Message.reply>`.
Arguments Arguments
entity (`entity`): entity (`entity`):
To who will it be sent. To who will it be sent.
message (`str` | `Message <telethon.tl.custom.message.Message>`): message (`str` | `Message <telethon.tl._custom.message.Message>`):
The message to be sent, or another message object to resend. The message to be sent, or another message object to resend.
The maximum length for a message is 35,000 bytes or 4,096 The maximum length for a message is 35,000 bytes or 4,096
@ -2303,7 +2303,7 @@ class TelegramClient:
and you should slice them manually if the text to send is and you should slice them manually if the text to send is
longer than said length. longer than said length.
reply_to (`int` | `Message <telethon.tl.custom.message.Message>`, optional): reply_to (`int` | `Message <telethon.tl._custom.message.Message>`, optional):
Whether to reply to a message or not. If an integer is provided, Whether to reply to a message or not. If an integer is provided,
it should be the ID of the message that it should reply to. it should be the ID of the message that it should reply to.
@ -2344,7 +2344,7 @@ class TelegramClient:
clear_draft (`bool`, optional): clear_draft (`bool`, optional):
Whether the existing draft should be cleared or not. Whether the existing draft should be cleared or not.
buttons (`list`, `custom.Button <telethon.tl.custom.button.Button>`, :tl:`KeyboardButton`): buttons (`list`, `_custom.Button <telethon.tl._custom.button.Button>`, :tl:`KeyboardButton`):
The matrix (list of lists), row list or button to be shown The matrix (list of lists), row list or button to be shown
after sending the message. This parameter will only work if after sending the message. This parameter will only work if
you have signed in as a bot. You can also pass your own you have signed in as a bot. You can also pass your own
@ -2378,7 +2378,7 @@ class TelegramClient:
it will be scheduled to be automatically sent at a later it will be scheduled to be automatically sent at a later
time. time.
comment_to (`int` | `Message <telethon.tl.custom.message.Message>`, optional): comment_to (`int` | `Message <telethon.tl._custom.message.Message>`, optional):
Similar to ``reply_to``, but replies in the linked group of a Similar to ``reply_to``, but replies in the linked group of a
broadcast channel instead (effectively leaving a "comment to" broadcast channel instead (effectively leaving a "comment to"
the specified message). the specified message).
@ -2387,7 +2387,7 @@ class TelegramClient:
no linked chat, `telethon.errors.sgIdInvalidError` is raised. no linked chat, `telethon.errors.sgIdInvalidError` is raised.
Returns Returns
The sent `custom.Message <telethon.tl.custom.message.Message>`. The sent `_custom.Message <telethon.tl._custom.message.Message>`.
Example Example
.. code-block:: python .. code-block:: python
@ -2466,13 +2466,13 @@ class TelegramClient:
(the "forwarded from" text), you should use `send_message` with (the "forwarded from" text), you should use `send_message` with
the original message instead. This will send a copy of it. the original message instead. This will send a copy of it.
See also `Message.forward_to() <telethon.tl.custom.message.Message.forward_to>`. See also `Message.forward_to() <telethon.tl._custom.message.Message.forward_to>`.
Arguments Arguments
entity (`entity`): entity (`entity`):
To which entity the message(s) will be forwarded. To which entity the message(s) will be forwarded.
messages (`list` | `int` | `Message <telethon.tl.custom.message.Message>`): messages (`list` | `int` | `Message <telethon.tl._custom.message.Message>`):
The message(s) to forward, or their integer IDs. The message(s) to forward, or their integer IDs.
from_peer (`entity`): from_peer (`entity`):
@ -2502,7 +2502,7 @@ class TelegramClient:
at a later time. at a later time.
Returns Returns
The list of forwarded `Message <telethon.tl.custom.message.Message>`, The list of forwarded `Message <telethon.tl._custom.message.Message>`,
or a single one if a list wasn't provided as input. or a single one if a list wasn't provided as input.
Note that if all messages are invalid (i.e. deleted) the call Note that if all messages are invalid (i.e. deleted) the call
@ -2560,10 +2560,10 @@ class TelegramClient:
""" """
Edits the given message to change its text or media. Edits the given message to change its text or media.
See also `Message.edit() <telethon.tl.custom.message.Message.edit>`. See also `Message.edit() <telethon.tl._custom.message.Message.edit>`.
Arguments Arguments
entity (`entity` | `Message <telethon.tl.custom.message.Message>`): entity (`entity` | `Message <telethon.tl._custom.message.Message>`):
From which chat to edit the message. This can also be From which chat to edit the message. This can also be
the message to be edited, and the entity will be inferred the message to be edited, and the entity will be inferred
from it, so the next parameter will be assumed to be the from it, so the next parameter will be assumed to be the
@ -2573,16 +2573,16 @@ class TelegramClient:
which is the only way to edit messages that were sent which is the only way to edit messages that were sent
after the user selects an inline query result. after the user selects an inline query result.
message (`int` | `Message <telethon.tl.custom.message.Message>` | `str`): message (`int` | `Message <telethon.tl._custom.message.Message>` | `str`):
The ID of the message (or `Message The ID of the message (or `Message
<telethon.tl.custom.message.Message>` itself) to be edited. <telethon.tl._custom.message.Message>` itself) to be edited.
If the `entity` was a `Message If the `entity` was a `Message
<telethon.tl.custom.message.Message>`, then this message <telethon.tl._custom.message.Message>`, then this message
will be treated as the new text. will be treated as the new text.
text (`str`, optional): text (`str`, optional):
The new text of the message. Does nothing if the `entity` The new text of the message. Does nothing if the `entity`
was a `Message <telethon.tl.custom.message.Message>`. was a `Message <telethon.tl._custom.message.Message>`.
parse_mode (`object`, optional): parse_mode (`object`, optional):
See the `TelegramClient.parse_mode See the `TelegramClient.parse_mode
@ -2618,7 +2618,7 @@ class TelegramClient:
force_document (`bool`, optional): force_document (`bool`, optional):
Whether to send the given file as a document or not. Whether to send the given file as a document or not.
buttons (`list`, `custom.Button <telethon.tl.custom.button.Button>`, :tl:`KeyboardButton`): buttons (`list`, `_custom.Button <telethon.tl._custom.button.Button>`, :tl:`KeyboardButton`):
The matrix (list of lists), row list or button to be shown The matrix (list of lists), row list or button to be shown
after sending the message. This parameter will only work if after sending the message. This parameter will only work if
you have signed in as a bot. You can also pass your own you have signed in as a bot. You can also pass your own
@ -2640,7 +2640,7 @@ class TelegramClient:
trying to edit a message that was sent via inline bots. trying to edit a message that was sent via inline bots.
Returns Returns
The edited `Message <telethon.tl.custom.message.Message>`, The edited `Message <telethon.tl._custom.message.Message>`,
unless `entity` was a :tl:`InputBotInlineMessageID` in which unless `entity` was a :tl:`InputBotInlineMessageID` in which
case this method returns a boolean. case this method returns a boolean.
@ -2678,7 +2678,7 @@ class TelegramClient:
""" """
Deletes the given messages, optionally "for everyone". Deletes the given messages, optionally "for everyone".
See also `Message.delete() <telethon.tl.custom.message.Message.delete>`. See also `Message.delete() <telethon.tl._custom.message.Message.delete>`.
.. warning:: .. warning::
@ -2693,7 +2693,7 @@ class TelegramClient:
be `None` for normal chats, but **must** be present be `None` for normal chats, but **must** be present
for channels and megagroups. for channels and megagroups.
message_ids (`list` | `int` | `Message <telethon.tl.custom.message.Message>`): message_ids (`list` | `int` | `Message <telethon.tl._custom.message.Message>`):
The IDs (or ID) or messages to be deleted. The IDs (or ID) or messages to be deleted.
revoke (`bool`, optional): revoke (`bool`, optional):
@ -2741,13 +2741,13 @@ class TelegramClient:
including such ID will be marked as read (for all messages whose ID including such ID will be marked as read (for all messages whose ID
max_id). max_id).
See also `Message.mark_read() <telethon.tl.custom.message.Message.mark_read>`. See also `Message.mark_read() <telethon.tl._custom.message.Message.mark_read>`.
Arguments Arguments
entity (`entity`): entity (`entity`):
The chat where these messages are located. The chat where these messages are located.
message (`list` | `Message <telethon.tl.custom.message.Message>`): message (`list` | `Message <telethon.tl._custom.message.Message>`):
Either a list of messages or a single message. Either a list of messages or a single message.
max_id (`int`): max_id (`int`):
@ -2787,13 +2787,13 @@ class TelegramClient:
The default behaviour is to *not* notify members, unlike the The default behaviour is to *not* notify members, unlike the
official applications. official applications.
See also `Message.pin() <telethon.tl.custom.message.Message.pin>`. See also `Message.pin() <telethon.tl._custom.message.Message.pin>`.
Arguments Arguments
entity (`entity`): entity (`entity`):
The chat where the message should be pinned. The chat where the message should be pinned.
message (`int` | `Message <telethon.tl.custom.message.Message>`): message (`int` | `Message <telethon.tl._custom.message.Message>`):
The message or the message ID to pin. If it's The message or the message ID to pin. If it's
`None`, all messages will be unpinned instead. `None`, all messages will be unpinned instead.
@ -2826,13 +2826,13 @@ class TelegramClient:
If no message ID is specified, all pinned messages will be unpinned. If no message ID is specified, all pinned messages will be unpinned.
See also `Message.unpin() <telethon.tl.custom.message.Message.unpin>`. See also `Message.unpin() <telethon.tl._custom.message.Message.unpin>`.
Arguments Arguments
entity (`entity`): entity (`entity`):
The chat where the message should be pinned. The chat where the message should be pinned.
message (`int` | `Message <telethon.tl.custom.message.Message>`): message (`int` | `Message <telethon.tl._custom.message.Message>`):
The message or the message ID to unpin. If it's The message or the message ID to unpin. If it's
`None`, all messages will be unpinned instead. `None`, all messages will be unpinned instead.
@ -3277,7 +3277,7 @@ class TelegramClient:
A callback function accepting two parameters: A callback function accepting two parameters:
``(sent bytes, total)``. ``(sent bytes, total)``.
reply_to (`int` | `Message <telethon.tl.custom.message.Message>`): reply_to (`int` | `Message <telethon.tl._custom.message.Message>`):
Same as `reply_to` from `send_message`. Same as `reply_to` from `send_message`.
attributes (`list`, optional): attributes (`list`, optional):
@ -3318,7 +3318,7 @@ class TelegramClient:
If `True` the video will be sent as a video note, If `True` the video will be sent as a video note,
also known as a round video message. also known as a round video message.
buttons (`list`, `custom.Button <telethon.tl.custom.button.Button>`, :tl:`KeyboardButton`): buttons (`list`, `_custom.Button <telethon.tl._custom.button.Button>`, :tl:`KeyboardButton`):
The matrix (list of lists), row list or button to be shown The matrix (list of lists), row list or button to be shown
after sending the message. This parameter will only work if after sending the message. This parameter will only work if
you have signed in as a bot. You can also pass your own you have signed in as a bot. You can also pass your own
@ -3345,7 +3345,7 @@ class TelegramClient:
it will be scheduled to be automatically sent at a later it will be scheduled to be automatically sent at a later
time. time.
comment_to (`int` | `Message <telethon.tl.custom.message.Message>`, optional): comment_to (`int` | `Message <telethon.tl._custom.message.Message>`, optional):
Similar to ``reply_to``, but replies in the linked group of a Similar to ``reply_to``, but replies in the linked group of a
broadcast channel instead (effectively leaving a "comment to" broadcast channel instead (effectively leaving a "comment to"
the specified message). the specified message).
@ -3366,7 +3366,7 @@ class TelegramClient:
as text documents, which will fail with ``TtlMediaInvalidError``. as text documents, which will fail with ``TtlMediaInvalidError``.
Returns Returns
The `Message <telethon.tl.custom.message.Message>` (or messages) The `Message <telethon.tl._custom.message.Message>` (or messages)
containing the sent file, or messages if a list of them was passed. containing the sent file, or messages if a list of them was passed.
Example Example
@ -3381,7 +3381,7 @@ class TelegramClient:
await client.send_file(chat, '/my/songs/song.mp3', voice_note=True) await client.send_file(chat, '/my/songs/song.mp3', voice_note=True)
await client.send_file(chat, '/my/videos/video.mp4', video_note=True) await client.send_file(chat, '/my/videos/video.mp4', video_note=True)
# Custom thumbnails # _custom thumbnails
await client.send_file(chat, '/my/documents/doc.txt', thumb='photo.jpg') await client.send_file(chat, '/my/documents/doc.txt', thumb='photo.jpg')
# Only documents # Only documents
@ -3482,7 +3482,7 @@ class TelegramClient:
Returns Returns
:tl:`InputFileBig` if the file size is larger than 10MB, :tl:`InputFileBig` if the file size is larger than 10MB,
`InputSizedFile <telethon.tl.custom.inputsizedfile.InputSizedFile>` `InputSizedFile <telethon.tl._custom.inputsizedfile.InputSizedFile>`
(subclass of :tl:`InputFile`) otherwise. (subclass of :tl:`InputFile`) otherwise.
Example Example

View File

@ -11,7 +11,7 @@ from .._crypto import AES
from .._misc import utils, helpers from .._misc import utils, helpers
from .. import hints, _tl from .. import hints, _tl
from .._tl import custom from ..types import _custom
try: try:
import PIL import PIL
@ -363,7 +363,7 @@ async def upload_file(
if is_big: if is_big:
return _tl.InputFileBig(file_id, part_count, file_name) return _tl.InputFileBig(file_id, part_count, file_name)
else: else:
return custom.InputSizedFile( return _custom.InputSizedFile(
file_id, part_count, file_name, md5=hash_md5, size=file_size file_id, part_count, file_name, md5=hash_md5, size=file_size
) )

View File

@ -11,7 +11,7 @@ except ImportError:
rsa = None rsa = None
raise ImportError('Missing module "rsa", please install via pip.') raise ImportError('Missing module "rsa", please install via pip.')
from .. import _tl from .._misc import tlobject
# {fingerprint: (Crypto.PublicKey.RSA._RSAobj, old)} dictionary # {fingerprint: (Crypto.PublicKey.RSA._RSAobj, old)} dictionary
@ -41,8 +41,8 @@ def _compute_fingerprint(key):
:param key: the Crypto.RSA key. :param key: the Crypto.RSA key.
:return: its 8-bytes-long fingerprint. :return: its 8-bytes-long fingerprint.
""" """
n = _tl.TLObject.serialize_bytes(get_byte_array(key.n)) n = tlobject.TLObject.serialize_bytes(get_byte_array(key.n))
e = _tl.TLObject.serialize_bytes(get_byte_array(key.e)) e = tlobject.TLObject.serialize_bytes(get_byte_array(key.e))
# Telegram uses the last 8 bytes as the fingerprint # Telegram uses the last 8 bytes as the fingerprint
return struct.unpack('<q', sha1(n + e).digest()[-8:])[0] return struct.unpack('<q', sha1(n + e).digest()[-8:])[0]

View File

@ -9,8 +9,7 @@ from struct import unpack
from ..errors import TypeNotFoundError from ..errors import TypeNotFoundError
from .. import _tl from .. import _tl
from .._tl.alltlobjects import tlobjects from ..types import _core
from ..types import core
_EPOCH_NAIVE = datetime(*time.gmtime(0)[:6]) _EPOCH_NAIVE = datetime(*time.gmtime(0)[:6])
_EPOCH = _EPOCH_NAIVE.replace(tzinfo=timezone.utc) _EPOCH = _EPOCH_NAIVE.replace(tzinfo=timezone.utc)
@ -119,7 +118,7 @@ class BinaryReader:
def tgread_object(self): def tgread_object(self):
"""Reads a Telegram object.""" """Reads a Telegram object."""
constructor_id = self.read_int(signed=False) constructor_id = self.read_int(signed=False)
clazz = tlobjects.get(constructor_id, None) clazz = _tl.tlobjects.get(constructor_id, None)
if clazz is None: if clazz is None:
# The class was None, but there's still a # The class was None, but there's still a
# chance of it being a manually parsed value like bool! # chance of it being a manually parsed value like bool!
@ -131,7 +130,7 @@ class BinaryReader:
elif value == 0x1cb5c415: # Vector elif value == 0x1cb5c415: # Vector
return [self.tgread_object() for _ in range(self.read_int())] return [self.tgread_object() for _ in range(self.read_int())]
clazz = core.core_objects.get(constructor_id, None) clazz = _core.core_objects.get(constructor_id, None)
if clazz is None: if clazz is None:
# If there was still no luck, give up # If there was still no luck, give up
self.seek(-4) # Go back self.seek(-4) # Go back

View File

@ -8,6 +8,7 @@ import warnings
from .helpers import add_surrogate, del_surrogate, within_surrogate, strip_text from .helpers import add_surrogate, del_surrogate, within_surrogate, strip_text
from .. import _tl from .. import _tl
from .._misc import tlobject
DEFAULT_DELIMITERS = { DEFAULT_DELIMITERS = {
'**': _tl.MessageEntityBold, '**': _tl.MessageEntityBold,
@ -153,7 +154,7 @@ def unparse(text, entities, delimiters=None, url_fmt=None):
if url_fmt is not None: if url_fmt is not None:
warnings.warn('url_fmt is deprecated') # since it complicates everything *a lot* warnings.warn('url_fmt is deprecated') # since it complicates everything *a lot*
if isinstance(entities, _tl.TLObject): if isinstance(entities, tlobject.TLObject):
entities = (entities,) entities = (entities,)
text = add_surrogate(text) text = add_surrogate(text)

View File

@ -4,8 +4,7 @@ import io
import struct import struct
from .._tl import TLRequest from .._tl import TLRequest
from .._tl.core.messagecontainer import MessageContainer from ..types._core import MessageContainer, TLMessage
from .._tl.core.tlmessage import TLMessage
class MessagePacker: class MessagePacker:

View File

@ -9,7 +9,7 @@ from hashlib import sha1
from .. import helpers, _tl from .. import helpers, _tl
from .._crypto import AES, AuthKey, Factorization, rsa from .._crypto import AES, AuthKey, Factorization, rsa
from ..errors import SecurityError from ..errors import SecurityError
from .._misc import BinaryReader from .._misc.binaryreader import BinaryReader
async def do_authentication(sender): async def do_authentication(sender):

View File

@ -6,7 +6,7 @@ import struct
from .mtprotostate import MTProtoState from .mtprotostate import MTProtoState
from ..errors import InvalidBufferError from ..errors import InvalidBufferError
from .._misc import BinaryReader from .._misc.binaryreader import BinaryReader
class MTProtoPlainSender: class MTProtoPlainSender:

View File

@ -7,14 +7,14 @@ from .._misc.messagepacker import MessagePacker
from .mtprotoplainsender import MTProtoPlainSender from .mtprotoplainsender import MTProtoPlainSender
from .requeststate import RequestState from .requeststate import RequestState
from .mtprotostate import MTProtoState from .mtprotostate import MTProtoState
from .._tl.tlobject import TLRequest
from .. import helpers, utils, _tl from .. import helpers, utils, _tl
from ..errors import ( from ..errors import (
BadMessageError, InvalidBufferError, SecurityError, BadMessageError, InvalidBufferError, SecurityError,
TypeNotFoundError, rpc_message_to_error TypeNotFoundError, rpc_message_to_error
) )
from .._misc import BinaryReader from .._misc.binaryreader import BinaryReader
from .._tl.core import RpcResult, MessageContainer, GzipPacked from .._misc.tlobject import TLRequest
from ..types._core import RpcResult, MessageContainer, GzipPacked
from .._crypto import AuthKey from .._crypto import AuthKey
from .._misc.helpers import retry_range from .._misc.helpers import retry_range

View File

@ -5,11 +5,10 @@ from hashlib import sha256
from .._crypto import AES from .._crypto import AES
from ..errors import SecurityError, InvalidBufferError from ..errors import SecurityError, InvalidBufferError
from .._misc import BinaryReader from .._misc.binaryreader import BinaryReader
from .._tl.core import TLMessage from ..types._core import TLMessage, GzipPacked
from .._tl.tlobject import TLRequest from .._misc.tlobject import TLRequest
from .. import _tl from .. import _tl
from .._tl.core.gzippacked import GzipPacked
class _OpaqueRequest(TLRequest): class _OpaqueRequest(TLRequest):

View File

@ -5,7 +5,7 @@ import weakref
from .common import EventBuilder, EventCommon, name_inner_event from .common import EventBuilder, EventCommon, name_inner_event
from .._misc import utils from .._misc import utils
from .. import _tl from .. import _tl
from .._tl import custom from ..types import _custom
_IGNORE_MAX_SIZE = 100 # len() _IGNORE_MAX_SIZE = 100 # len()
_IGNORE_MAX_AGE = 5 # seconds _IGNORE_MAX_AGE = 5 # seconds
@ -140,12 +140,12 @@ class Album(EventBuilder):
if len(event.messages) > 1: if len(event.messages) > 1:
return super().filter(event) return super().filter(event)
class Event(EventCommon, custom.sendergetter.SenderGetter): class Event(EventCommon, _custom.sendergetter.SenderGetter):
""" """
Represents the event of a new album. Represents the event of a new album.
Members: Members:
messages (Sequence[`Message <telethon.tl.custom.message.Message>`]): messages (Sequence[`Message <telethon.tl._custom.message.Message>`]):
The list of messages belonging to the same album. The list of messages belonging to the same album.
""" """
def __init__(self, messages): def __init__(self, messages):
@ -160,7 +160,7 @@ class Album(EventBuilder):
super().__init__(chat_peer=chat_peer, super().__init__(chat_peer=chat_peer,
msg_id=message.id, broadcast=bool(message.post)) msg_id=message.id, broadcast=bool(message.post))
custom.sendergetter.SenderGetter.__init__(self, message.sender_id) _custom.sendergetter.SenderGetter.__init__(self, message.sender_id)
self.messages = messages self.messages = messages
def _set_client(self, client): def _set_client(self, client):
@ -217,7 +217,7 @@ class Album(EventBuilder):
@property @property
def forward(self): def forward(self):
""" """
The `Forward <telethon.tl.custom.forward.Forward>` The `Forward <telethon.tl._custom.forward.Forward>`
information for the first message in the album if it was forwarded. information for the first message in the album if it was forwarded.
""" """
# Each individual message in an album all reply to the same message # Each individual message in an album all reply to the same message
@ -229,7 +229,7 @@ class Album(EventBuilder):
async def get_reply_message(self): async def get_reply_message(self):
""" """
The `Message <telethon.tl.custom.message.Message>` The `Message <telethon.tl._custom.message.Message>`
that this album is replying to, or `None`. that this album is replying to, or `None`.
The result will be cached after its first use. The result will be cached after its first use.

View File

@ -4,7 +4,7 @@ import struct
from .common import EventBuilder, EventCommon, name_inner_event from .common import EventBuilder, EventCommon, name_inner_event
from .._misc import utils from .._misc import utils
from .. import _tl from .. import _tl
from .._tl import custom from ..types import _custom
@name_inner_event @name_inner_event
@ -123,7 +123,7 @@ class CallbackQuery(EventBuilder):
return self.func(event) return self.func(event)
return True return True
class Event(EventCommon, custom.sendergetter.SenderGetter): class Event(EventCommon, _custom.sendergetter.SenderGetter):
""" """
Represents the event of a new callback query. Represents the event of a new callback query.
@ -141,7 +141,7 @@ class CallbackQuery(EventBuilder):
""" """
def __init__(self, query, peer, msg_id): def __init__(self, query, peer, msg_id):
super().__init__(peer, msg_id=msg_id) super().__init__(peer, msg_id=msg_id)
custom.sendergetter.SenderGetter.__init__(self, query.user_id) _custom.sendergetter.SenderGetter.__init__(self, query.user_id)
self.query = query self.query = query
self.data_match = None self.data_match = None
self.pattern_match = None self.pattern_match = None
@ -308,7 +308,7 @@ class CallbackQuery(EventBuilder):
.. note:: .. note::
This method won't respect the previous message unlike This method won't respect the previous message unlike
`Message.edit <telethon.tl.custom.message.Message.edit>`, `Message.edit <telethon.tl._custom.message.Message.edit>`,
since the message object is normally not present. since the message object is normally not present.
""" """
self._client.loop.create_task(self.answer()) self._client.loop.create_task(self.answer())

View File

@ -2,8 +2,9 @@ import abc
import asyncio import asyncio
import warnings import warnings
from .._misc import utils from .. import _tl
from .._tl.custom.chatgetter import ChatGetter from .._misc import utils, tlobject
from ..types._custom.chatgetter import ChatGetter
async def _into_id_set(client, chats): async def _into_id_set(client, chats):
@ -25,7 +26,7 @@ async def _into_id_set(client, chats):
utils.get_peer_id(_tl.PeerChat(chat)), utils.get_peer_id(_tl.PeerChat(chat)),
utils.get_peer_id(_tl.PeerChannel(chat)), utils.get_peer_id(_tl.PeerChannel(chat)),
}) })
elif isinstance(chat, _tl.TLObject) and chat.SUBCLASS_OF_ID == 0x2d45687: elif isinstance(chat, tlobject.TLObject) and chat.SUBCLASS_OF_ID == 0x2d45687:
# 0x2d45687 == crc32(b'Peer') # 0x2d45687 == crc32(b'Peer')
result.add(utils.get_peer_id(chat)) result.add(utils.get_peer_id(chat))
else: else:

View File

@ -6,7 +6,7 @@ import asyncio
from .common import EventBuilder, EventCommon, name_inner_event from .common import EventBuilder, EventCommon, name_inner_event
from .._misc import utils from .._misc import utils
from .. import _tl from .. import _tl
from .._tl import custom from ..types import _custom
@name_inner_event @name_inner_event
@ -74,7 +74,7 @@ class InlineQuery(EventBuilder):
return super().filter(event) return super().filter(event)
class Event(EventCommon, custom.sendergetter.SenderGetter): class Event(EventCommon, _custom.sendergetter.SenderGetter):
""" """
Represents the event of a new callback query. Represents the event of a new callback query.
@ -91,7 +91,7 @@ class InlineQuery(EventBuilder):
""" """
def __init__(self, query): def __init__(self, query):
super().__init__(chat_peer=_tl.PeerUser(query.user_id)) super().__init__(chat_peer=_tl.PeerUser(query.user_id))
custom.sendergetter.SenderGetter.__init__(self, query.user_id) _custom.sendergetter.SenderGetter.__init__(self, query.user_id)
self.query = query self.query = query
self.pattern_match = None self.pattern_match = None
self._answered = False self._answered = False

View File

@ -4,7 +4,7 @@ import functools
from .common import EventBuilder, EventCommon, name_inner_event from .common import EventBuilder, EventCommon, name_inner_event
from .._misc import utils from .._misc import utils
from .. import _tl from .. import _tl
from .._tl import custom from ..types import _custom
# TODO Either the properties are poorly named or they should be # TODO Either the properties are poorly named or they should be
@ -65,7 +65,7 @@ class UserUpdate(EventBuilder):
return cls.Event(update.user_id, return cls.Event(update.user_id,
typing=update.action) typing=update.action)
class Event(EventCommon, custom.sendergetter.SenderGetter): class Event(EventCommon, _custom.sendergetter.SenderGetter):
""" """
Represents the event of a user update Represents the event of a user update
such as gone online, started typing, etc. such as gone online, started typing, etc.
@ -87,7 +87,7 @@ class UserUpdate(EventBuilder):
""" """
def __init__(self, peer, *, status=None, chat_peer=None, typing=None): def __init__(self, peer, *, status=None, chat_peer=None, typing=None):
super().__init__(chat_peer or peer) super().__init__(chat_peer or peer)
custom.sendergetter.SenderGetter.__init__(self, utils.get_peer_id(peer)) _custom.sendergetter.SenderGetter.__init__(self, utils.get_peer_id(peer))
self.status = status self.status = status
self.action = typing self.action = typing

View File

@ -1,7 +1,7 @@
from enum import Enum from enum import Enum
from .abstract import Session from .abstract import Session
from .._misc import utils from .._misc import utils, tlobject
from .. import _tl from .. import _tl
@ -89,7 +89,7 @@ class MemorySession(Session):
return id, hash, username, phone, name return id, hash, username, phone, name
def _entity_to_row(self, e): def _entity_to_row(self, e):
if not isinstance(e, _tl.TLObject): if not isinstance(e, tlobject.TLObject):
return return
try: try:
p = utils.get_input_peer(e, allow_self=False) p = utils.get_input_peer(e, allow_self=False)
@ -118,7 +118,7 @@ class MemorySession(Session):
) )
def _entities_to_rows(self, tlo): def _entities_to_rows(self, tlo):
if not isinstance(tlo, _tl.TLObject) and utils.is_list_like(tlo): if not isinstance(tlo, tlobject.TLObject) and utils.is_list_like(tlo):
# This may be a list of users already for instance # This may be a list of users already for instance
entities = tlo entities = tlo
else: else:
@ -189,7 +189,7 @@ class MemorySession(Session):
return utils.get_input_peer(key) return utils.get_input_peer(key)
except (AttributeError, TypeError): except (AttributeError, TypeError):
# Not a TLObject or can't be cast into InputPeer # Not a TLObject or can't be cast into InputPeer
if isinstance(key, _tl.TLObject): if isinstance(key, tlobject.TLObject):
key = utils.get_peer_id(key) key = utils.get_peer_id(key)
exact = True exact = True
else: else:

View File

@ -1,10 +1,10 @@
import gzip import gzip
import struct import struct
from .. import TLObject from ..._misc import tlobject
class GzipPacked(TLObject): class GzipPacked(tlobject.TLObject):
CONSTRUCTOR_ID = 0x3072cfa1 CONSTRUCTOR_ID = 0x3072cfa1
def __init__(self, data): def __init__(self, data):
@ -26,7 +26,7 @@ class GzipPacked(TLObject):
def __bytes__(self): def __bytes__(self):
return struct.pack('<I', GzipPacked.CONSTRUCTOR_ID) + \ return struct.pack('<I', GzipPacked.CONSTRUCTOR_ID) + \
TLObject.serialize_bytes(gzip.compress(self.data)) tlobject.TLObject.serialize_bytes(gzip.compress(self.data))
@staticmethod @staticmethod
def read(reader): def read(reader):

View File

@ -1,5 +1,5 @@
from .tlmessage import TLMessage from .tlmessage import TLMessage
from ..tlobject import TLObject from ..._misc.tlobject import TLObject
class MessageContainer(TLObject): class MessageContainer(TLObject):

View File

@ -1,5 +1,6 @@
from .gzippacked import GzipPacked from .gzippacked import GzipPacked
from .. import TLObject, RpcError from ..._misc.tlobject import TLObject
from ... import _tl
class RpcResult(TLObject): class RpcResult(TLObject):
@ -14,8 +15,8 @@ class RpcResult(TLObject):
def from_reader(cls, reader): def from_reader(cls, reader):
msg_id = reader.read_long() msg_id = reader.read_long()
inner_code = reader.read_int(signed=False) inner_code = reader.read_int(signed=False)
if inner_code == RpcError.CONSTRUCTOR_ID: if inner_code == _tl.RpcError.CONSTRUCTOR_ID:
return RpcResult(msg_id, None, RpcError.from_reader(reader)) return RpcResult(msg_id, None, _tl.RpcError.from_reader(reader))
if inner_code == GzipPacked.CONSTRUCTOR_ID: if inner_code == GzipPacked.CONSTRUCTOR_ID:
return RpcResult(msg_id, GzipPacked.from_reader(reader).data, None) return RpcResult(msg_id, GzipPacked.from_reader(reader).data, None)

View File

@ -1,7 +1,7 @@
from .. import TLObject from ..._misc import tlobject
class TLMessage(TLObject): class TLMessage(tlobject.TLObject):
""" """
https://core.telegram.org/mtproto/service_messages#simple-container. https://core.telegram.org/mtproto/service_messages#simple-container.

View File

@ -1,6 +1,6 @@
from . import Draft from . import Draft
from ... import _tl from ... import _tl
from ..._misc import utils from ..._misc import utils, tlobject
class Dialog: class Dialog:
@ -155,7 +155,7 @@ class Dialog:
} }
def __str__(self): def __str__(self):
return _tl.TLObject.pretty_format(self.to_dict()) return tlobject.TLObject.pretty_format(self.to_dict())
def stringify(self): def stringify(self):
return _tl.TLObject.pretty_format(self.to_dict(), indent=0) return tlobject.TLObject.pretty_format(self.to_dict(), indent=0)

View File

@ -2,7 +2,7 @@ import datetime
from ... import _tl from ... import _tl
from ...errors import RPCError from ...errors import RPCError
from ..._misc import markdown from ..._misc import markdown, tlobject
from ..._misc.utils import get_input_peer, get_peer from ..._misc.utils import get_input_peer, get_peer
@ -182,7 +182,7 @@ class Draft:
} }
def __str__(self): def __str__(self):
return _tl.TLObject.pretty_format(self.to_dict()) return tlobject.TLObject.pretty_format(self.to_dict())
def stringify(self): def stringify(self):
return _tl.TLObject.pretty_format(self.to_dict(), indent=0) return tlobject.TLObject.pretty_format(self.to_dict(), indent=0)

View File

@ -5,13 +5,13 @@ from .sendergetter import SenderGetter
from .messagebutton import MessageButton from .messagebutton import MessageButton
from .forward import Forward from .forward import Forward
from .file import File from .file import File
from ..._misc import utils from ..._misc import utils, tlobject
from ... import errors, _tl from ... import errors, _tl
# TODO Figure out a way to have the code generator error on missing fields # TODO Figure out a way to have the code generator error on missing fields
# Maybe parsing the init function alone if that's possible. # Maybe parsing the init function alone if that's possible.
class Message(ChatGetter, SenderGetter, _tl.TLObject): class Message(ChatGetter, SenderGetter, tlobject.TLObject):
""" """
This custom class aggregates both :tl:`Message` and This custom class aggregates both :tl:`Message` and
:tl:`MessageService` to ease accessing their members. :tl:`MessageService` to ease accessing their members.

View File

@ -52,7 +52,7 @@ BASE_TYPES = ('string', 'bytes', 'int', 'long', 'int128',
def _write_modules( def _write_modules(
out_dir, in_mod, kind, namespace_tlobjects, type_constructors): out_dir, in_mod, kind, namespace_tlobjects, type_constructors, layer):
# namespace_tlobjects: {'namespace', [TLObject]} # namespace_tlobjects: {'namespace', [TLObject]}
out_dir.mkdir(parents=True, exist_ok=True) out_dir.mkdir(parents=True, exist_ok=True)
for ns, tlobjects in namespace_tlobjects.items(): for ns, tlobjects in namespace_tlobjects.items():
@ -163,6 +163,9 @@ def _write_modules(
for line in type_defs: for line in type_defs:
builder.writeln(line) builder.writeln(line)
if not ns and kind == 'TLObject':
_write_all_tlobjects(tlobjects, layer, builder)
def _write_source_code(tlobject, kind, builder, type_constructors): def _write_source_code(tlobject, kind, builder, type_constructors):
""" """
@ -658,12 +661,6 @@ def _write_arg_read_code(builder, arg, tlobject, name):
def _write_all_tlobjects(tlobjects, layer, builder): def _write_all_tlobjects(tlobjects, layer, builder):
builder.writeln(AUTO_GEN_NOTICE)
builder.writeln()
builder.writeln('from . import types, functions')
builder.writeln()
# Create a constant variable to indicate which layer this is # Create a constant variable to indicate which layer this is
builder.writeln('LAYER = {}', layer) builder.writeln('LAYER = {}', layer)
builder.writeln() builder.writeln()
@ -675,12 +672,13 @@ def _write_all_tlobjects(tlobjects, layer, builder):
# Fill the dictionary (0x1a2b3c4f: tl.full.type.path.Class) # Fill the dictionary (0x1a2b3c4f: tl.full.type.path.Class)
for tlobject in tlobjects: for tlobject in tlobjects:
builder.write('{:#010x}: ', tlobject.id) builder.write('{:#010x}: ', tlobject.id)
builder.write('functions' if tlobject.is_function else 'types') if tlobject.is_function:
builder.write('fn.')
if tlobject.namespace: if tlobject.namespace:
builder.write('.{}', tlobject.namespace) builder.write('{}.', tlobject.namespace)
builder.writeln('.{},', tlobject.class_name) builder.writeln('{},', tlobject.class_name)
builder.current_indent -= 1 builder.current_indent -= 1
builder.writeln('}') builder.writeln('}')
@ -701,14 +699,9 @@ def generate_tlobjects(tlobjects, layer, input_mod, output_dir):
type_constructors[tlobject.result].append(tlobject) type_constructors[tlobject.result].append(tlobject)
_write_modules(output_dir, input_mod, 'TLObject', _write_modules(output_dir, input_mod, 'TLObject',
namespace_types, type_constructors) namespace_types, type_constructors, layer)
_write_modules(output_dir / 'fn', input_mod + '.fn', 'TLRequest', _write_modules(output_dir / 'fn', input_mod + '.fn', 'TLRequest',
namespace_functions, type_constructors) namespace_functions, type_constructors, layer)
filename = output_dir / 'alltlobjects.py'
with filename.open('w') as file:
with SourceBuilder(file) as builder:
_write_all_tlobjects(tlobjects, layer, builder)
def clean_tlobjects(output_dir): def clean_tlobjects(output_dir):
@ -716,7 +709,3 @@ def clean_tlobjects(output_dir):
d = output_dir / d d = output_dir / d
if d.is_dir(): if d.is_dir():
shutil.rmtree(str(d)) shutil.rmtree(str(d))
tl = output_dir / 'alltlobjects.py'
if tl.is_file():
tl.unlink()