1
0
mirror of https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git synced 2025-08-14 00:25:46 +02:00

Все подряд

This commit is contained in:
MoonTestUse1
2024-12-31 02:37:57 +06:00
parent 8e53bb6cb2
commit d5780b2eab
3258 changed files with 1087440 additions and 268 deletions

View File

@@ -0,0 +1 @@
from .tlobject import TLObject, TLRequest

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,26 @@
"""
This module holds core "special" types, which are more convenient ways
to do stuff in a `telethon.network.mtprotosender.MTProtoSender` instance.
Only special cases are gzip-packed data, the response message (not a
client message), the message container which references these messages
and would otherwise conflict with the rest, and finally the RpcResult:
rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult;
Three things to note with this definition:
1. The constructor ID is actually ``42d36c2c``.
2. Those bytes are not read like the rest of bytes (length + payload).
They are actually the raw bytes of another object, which can't be
read directly because it depends on per-request information (since
some can return ``Vector<int>`` and ``Vector<long>``).
3. Those bytes may be gzipped data, which needs to be treated early.
"""
from .tlmessage import TLMessage
from .gzippacked import GzipPacked
from .messagecontainer import MessageContainer
from .rpcresult import RpcResult
core_objects = {x.CONSTRUCTOR_ID: x for x in (
GzipPacked, MessageContainer, RpcResult
)}

View File

@@ -0,0 +1,45 @@
import gzip
import struct
from .. import TLObject
class GzipPacked(TLObject):
CONSTRUCTOR_ID = 0x3072cfa1
def __init__(self, data):
self.data = data
@staticmethod
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 requests.
"""
if content_related and len(data) > 512:
gzipped = bytes(GzipPacked(data))
return gzipped if len(gzipped) < len(data) else data
else:
return data
def __bytes__(self):
return struct.pack('<I', GzipPacked.CONSTRUCTOR_ID) + \
TLObject.serialize_bytes(gzip.compress(self.data))
@staticmethod
def read(reader):
constructor = reader.read_int(signed=False)
assert constructor == GzipPacked.CONSTRUCTOR_ID
return gzip.decompress(reader.tgread_bytes())
@classmethod
def from_reader(cls, reader):
return GzipPacked(gzip.decompress(reader.tgread_bytes()))
def to_dict(self):
return {
'_': 'GzipPacked',
'data': self.data
}

View File

@@ -0,0 +1,47 @@
from .tlmessage import TLMessage
from ..tlobject import TLObject
class MessageContainer(TLObject):
CONSTRUCTOR_ID = 0x73f1f8dc
# Maximum size in bytes for the inner payload of the container.
# Telegram will close the connection if the payload is bigger.
# The overhead of the container itself is subtracted.
MAXIMUM_SIZE = 1044456 - 8
# Maximum amount of messages that can't be sent inside a single
# container, inclusive. Beyond this limit Telegram will respond
# with BAD_MESSAGE 64 (invalid container).
#
# This limit is not 100% accurate and may in some cases be higher.
# However, sending up to 100 requests at once in a single container
# is a reasonable conservative value, since it could also depend on
# other factors like size per request, but we cannot know this.
MAXIMUM_LENGTH = 100
def __init__(self, messages):
self.messages = messages
def to_dict(self):
return {
'_': 'MessageContainer',
'messages':
[] if self.messages is None else [
None if x is None else x.to_dict() for x in self.messages
],
}
@classmethod
def from_reader(cls, reader):
# This assumes that .read_* calls are done in the order they appear
messages = []
for _ in range(reader.read_int()):
msg_id = reader.read_long()
seq_no = reader.read_int()
length = reader.read_int()
before = reader.tell_position()
obj = reader.tgread_object() # May over-read e.g. RpcResult
reader.set_position(before + length)
messages.append(TLMessage(msg_id, seq_no, obj))
return MessageContainer(messages)

View File

@@ -0,0 +1,35 @@
from .gzippacked import GzipPacked
from .. import TLObject
from ..types import RpcError
class RpcResult(TLObject):
CONSTRUCTOR_ID = 0xf35c6d01
def __init__(self, req_msg_id, body, error):
self.req_msg_id = req_msg_id
self.body = body
self.error = error
@classmethod
def from_reader(cls, reader):
msg_id = reader.read_long()
inner_code = reader.read_int(signed=False)
if inner_code == RpcError.CONSTRUCTOR_ID:
return RpcResult(msg_id, None, RpcError.from_reader(reader))
if inner_code == GzipPacked.CONSTRUCTOR_ID:
return RpcResult(msg_id, GzipPacked.from_reader(reader).data, None)
reader.seek(-4)
# This reader.read() will read more than necessary, but it's okay.
# We could make use of MessageContainer's length here, but since
# it's not necessary we don't need to care about it.
return RpcResult(msg_id, reader.read(), None)
def to_dict(self):
return {
'_': 'RpcResult',
'req_msg_id': self.req_msg_id,
'body': self.body,
'error': self.error
}

View File

@@ -0,0 +1,34 @@
from .. import TLObject
class TLMessage(TLObject):
"""
https://core.telegram.org/mtproto/service_messages#simple-container.
Messages are what's ultimately sent to Telegram:
message msg_id:long seqno:int bytes:int body:bytes = Message;
Each message has its own unique identifier, and the body is simply
the serialized request that should be executed on the server, or
the response object from Telegram. Since the body is always a valid
object, it makes sense to store the object and not the bytes to
ease working with them.
There is no need to add serializing logic here since that can be
inlined and is unlikely to change. Thus these are only needed to
encapsulate responses.
"""
SIZE_OVERHEAD = 12
def __init__(self, msg_id, seq_no, obj):
self.msg_id = msg_id
self.seq_no = seq_no
self.obj = obj
def to_dict(self):
return {
'_': 'TLMessage',
'msg_id': self.msg_id,
'seq_no': self.seq_no,
'obj': self.obj
}

View File

@@ -0,0 +1,14 @@
from .adminlogevent import AdminLogEvent
from .draft import Draft
from .dialog import Dialog
from .inputsizedfile import InputSizedFile
from .messagebutton import MessageButton
from .forward import Forward
from .message import Message
from .button import Button
from .inlinebuilder import InlineBuilder
from .inlineresult import InlineResult
from .inlineresults import InlineResults
from .conversation import Conversation
from .qrlogin import QRLogin
from .participantpermissions import ParticipantPermissions

View File

@@ -0,0 +1,475 @@
from ...tl import types
from ...utils import get_input_peer
class AdminLogEvent:
"""
Represents a more friendly interface for admin log events.
Members:
original (:tl:`ChannelAdminLogEvent`):
The original :tl:`ChannelAdminLogEvent`.
entities (`dict`):
A dictionary mapping user IDs to :tl:`User`.
When `old` and `new` are :tl:`ChannelParticipant`, you can
use this dictionary to map the ``user_id``, ``kicked_by``,
``inviter_id`` and ``promoted_by`` IDs to their :tl:`User`.
user (:tl:`User`):
The user that caused this action (``entities[original.user_id]``).
input_user (:tl:`InputPeerUser`):
Input variant of `user`.
"""
def __init__(self, original, entities):
self.original = original
self.entities = entities
self.user = entities[original.user_id]
self.input_user = get_input_peer(self.user)
@property
def id(self):
"""
The ID of this event.
"""
return self.original.id
@property
def date(self):
"""
The date when this event occurred.
"""
return self.original.date
@property
def user_id(self):
"""
The ID of the user that triggered this event.
"""
return self.original.user_id
@property
def action(self):
"""
The original :tl:`ChannelAdminLogEventAction`.
"""
return self.original.action
@property
def old(self):
"""
The old value from the event.
"""
ori = self.original.action
if isinstance(ori, (
types.ChannelAdminLogEventActionChangeAbout,
types.ChannelAdminLogEventActionChangeTitle,
types.ChannelAdminLogEventActionChangeUsername,
types.ChannelAdminLogEventActionChangeLocation,
types.ChannelAdminLogEventActionChangeHistoryTTL,
)):
return ori.prev_value
elif isinstance(ori, types.ChannelAdminLogEventActionChangePhoto):
return ori.prev_photo
elif isinstance(ori, types.ChannelAdminLogEventActionChangeStickerSet):
return ori.prev_stickerset
elif isinstance(ori, types.ChannelAdminLogEventActionEditMessage):
return ori.prev_message
elif isinstance(ori, (
types.ChannelAdminLogEventActionParticipantToggleAdmin,
types.ChannelAdminLogEventActionParticipantToggleBan
)):
return ori.prev_participant
elif isinstance(ori, (
types.ChannelAdminLogEventActionToggleInvites,
types.ChannelAdminLogEventActionTogglePreHistoryHidden,
types.ChannelAdminLogEventActionToggleSignatures
)):
return not ori.new_value
elif isinstance(ori, types.ChannelAdminLogEventActionDeleteMessage):
return ori.message
elif isinstance(ori, types.ChannelAdminLogEventActionDefaultBannedRights):
return ori.prev_banned_rights
elif isinstance(ori, types.ChannelAdminLogEventActionDiscardGroupCall):
return ori.call
elif isinstance(ori, (
types.ChannelAdminLogEventActionExportedInviteDelete,
types.ChannelAdminLogEventActionExportedInviteRevoke,
types.ChannelAdminLogEventActionParticipantJoinByInvite,
)):
return ori.invite
elif isinstance(ori, types.ChannelAdminLogEventActionExportedInviteEdit):
return ori.prev_invite
@property
def new(self):
"""
The new value present in the event.
"""
ori = self.original.action
if isinstance(ori, (
types.ChannelAdminLogEventActionChangeAbout,
types.ChannelAdminLogEventActionChangeTitle,
types.ChannelAdminLogEventActionChangeUsername,
types.ChannelAdminLogEventActionToggleInvites,
types.ChannelAdminLogEventActionTogglePreHistoryHidden,
types.ChannelAdminLogEventActionToggleSignatures,
types.ChannelAdminLogEventActionChangeLocation,
types.ChannelAdminLogEventActionChangeHistoryTTL,
)):
return ori.new_value
elif isinstance(ori, types.ChannelAdminLogEventActionChangePhoto):
return ori.new_photo
elif isinstance(ori, types.ChannelAdminLogEventActionChangeStickerSet):
return ori.new_stickerset
elif isinstance(ori, types.ChannelAdminLogEventActionEditMessage):
return ori.new_message
elif isinstance(ori, (
types.ChannelAdminLogEventActionParticipantToggleAdmin,
types.ChannelAdminLogEventActionParticipantToggleBan
)):
return ori.new_participant
elif isinstance(ori, (
types.ChannelAdminLogEventActionParticipantInvite,
types.ChannelAdminLogEventActionParticipantVolume,
)):
return ori.participant
elif isinstance(ori, types.ChannelAdminLogEventActionDefaultBannedRights):
return ori.new_banned_rights
elif isinstance(ori, types.ChannelAdminLogEventActionStopPoll):
return ori.message
elif isinstance(ori, types.ChannelAdminLogEventActionStartGroupCall):
return ori.call
elif isinstance(ori, (
types.ChannelAdminLogEventActionParticipantMute,
types.ChannelAdminLogEventActionParticipantUnmute,
)):
return ori.participant
elif isinstance(ori, types.ChannelAdminLogEventActionToggleGroupCallSetting):
return ori.join_muted
elif isinstance(ori, types.ChannelAdminLogEventActionExportedInviteEdit):
return ori.new_invite
@property
def changed_about(self):
"""
Whether the channel's about was changed or not.
If `True`, `old` and `new` will be present as `str`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionChangeAbout)
@property
def changed_title(self):
"""
Whether the channel's title was changed or not.
If `True`, `old` and `new` will be present as `str`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionChangeTitle)
@property
def changed_username(self):
"""
Whether the channel's username was changed or not.
If `True`, `old` and `new` will be present as `str`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionChangeUsername)
@property
def changed_photo(self):
"""
Whether the channel's photo was changed or not.
If `True`, `old` and `new` will be present as :tl:`Photo`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionChangePhoto)
@property
def changed_sticker_set(self):
"""
Whether the channel's sticker set was changed or not.
If `True`, `old` and `new` will be present as :tl:`InputStickerSet`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionChangeStickerSet)
@property
def changed_message(self):
"""
Whether a message in this channel was edited or not.
If `True`, `old` and `new` will be present as
`Message <telethon.tl.custom.message.Message>`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionEditMessage)
@property
def deleted_message(self):
"""
Whether a message in this channel was deleted or not.
If `True`, `old` will be present as
`Message <telethon.tl.custom.message.Message>`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionDeleteMessage)
@property
def changed_admin(self):
"""
Whether the permissions for an admin in this channel
changed or not.
If `True`, `old` and `new` will be present as
:tl:`ChannelParticipant`.
"""
return isinstance(
self.original.action,
types.ChannelAdminLogEventActionParticipantToggleAdmin)
@property
def changed_restrictions(self):
"""
Whether a message in this channel was edited or not.
If `True`, `old` and `new` will be present as
:tl:`ChannelParticipant`.
"""
return isinstance(
self.original.action,
types.ChannelAdminLogEventActionParticipantToggleBan)
@property
def changed_invites(self):
"""
Whether the invites in the channel were toggled or not.
If `True`, `old` and `new` will be present as `bool`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionToggleInvites)
@property
def changed_location(self):
"""
Whether the location setting of the channel has changed or not.
If `True`, `old` and `new` will be present as :tl:`ChannelLocation`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionChangeLocation)
@property
def joined(self):
"""
Whether `user` joined through the channel's
public username or not.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionParticipantJoin)
@property
def joined_invite(self):
"""
Whether a new user joined through an invite
link to the channel or not.
If `True`, `new` will be present as
:tl:`ChannelParticipant`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionParticipantInvite)
@property
def left(self):
"""
Whether `user` left the channel or not.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionParticipantLeave)
@property
def changed_hide_history(self):
"""
Whether hiding the previous message history for new members
in the channel was toggled or not.
If `True`, `old` and `new` will be present as `bool`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionTogglePreHistoryHidden)
@property
def changed_signatures(self):
"""
Whether the message signatures in the channel were toggled
or not.
If `True`, `old` and `new` will be present as `bool`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionToggleSignatures)
@property
def changed_pin(self):
"""
Whether a new message in this channel was pinned or not.
If `True`, `new` will be present as
`Message <telethon.tl.custom.message.Message>`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionUpdatePinned)
@property
def changed_default_banned_rights(self):
"""
Whether the default banned rights were changed or not.
If `True`, `old` and `new` will
be present as :tl:`ChatBannedRights`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionDefaultBannedRights)
@property
def stopped_poll(self):
"""
Whether a poll was stopped or not.
If `True`, `new` will be present as
`Message <telethon.tl.custom.message.Message>`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionStopPoll)
@property
def started_group_call(self):
"""
Whether a group call was started or not.
If `True`, `new` will be present as :tl:`InputGroupCall`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionStartGroupCall)
@property
def discarded_group_call(self):
"""
Whether a group call was started or not.
If `True`, `old` will be present as :tl:`InputGroupCall`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionDiscardGroupCall)
@property
def user_muted(self):
"""
Whether a participant was muted in the ongoing group call or not.
If `True`, `new` will be present as :tl:`GroupCallParticipant`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionParticipantMute)
@property
def user_unmutted(self):
"""
Whether a participant was unmuted from the ongoing group call or not.
If `True`, `new` will be present as :tl:`GroupCallParticipant`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionParticipantUnmute)
@property
def changed_call_settings(self):
"""
Whether the group call settings were changed or not.
If `True`, `new` will be `True` if new users are muted on join.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionToggleGroupCallSetting)
@property
def changed_history_ttl(self):
"""
Whether the Time To Live of the message history has changed.
Messages sent after this change will have a ``ttl_period`` in seconds
indicating how long they should live for before being auto-deleted.
If `True`, `old` will be the old TTL, and `new` the new TTL, in seconds.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionChangeHistoryTTL)
@property
def deleted_exported_invite(self):
"""
Whether the exported chat invite has been deleted.
If `True`, `old` will be the deleted :tl:`ExportedChatInvite`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionExportedInviteDelete)
@property
def edited_exported_invite(self):
"""
Whether the exported chat invite has been edited.
If `True`, `old` and `new` will be the old and new
:tl:`ExportedChatInvite`, respectively.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionExportedInviteEdit)
@property
def revoked_exported_invite(self):
"""
Whether the exported chat invite has been revoked.
If `True`, `old` will be the revoked :tl:`ExportedChatInvite`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionExportedInviteRevoke)
@property
def joined_by_invite(self):
"""
Whether a new participant has joined with the use of an invite link.
If `True`, `old` will be pre-existing (old) :tl:`ExportedChatInvite`
used to join.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionParticipantJoinByInvite)
@property
def changed_user_volume(self):
"""
Whether a participant's volume in a call has been changed.
If `True`, `new` will be the updated :tl:`GroupCallParticipant`.
"""
return isinstance(self.original.action,
types.ChannelAdminLogEventActionParticipantVolume)
def __str__(self):
return str(self.original)
def stringify(self):
return self.original.stringify()

View File

@@ -0,0 +1,309 @@
from .. import types
from ... import utils
class Button:
"""
.. note::
This class is used to **define** reply markups, e.g. when
sending a message or replying to events. When you access
`Message.buttons <telethon.tl.custom.message.Message.buttons>`
they are actually `MessageButton
<telethon.tl.custom.messagebutton.MessageButton>`,
so you might want to refer to that class instead.
Helper class to allow defining ``reply_markup`` when
sending a message with inline or keyboard buttons.
You should make use of the defined class methods to create button
instances instead making them yourself (i.e. don't do ``Button(...)``
but instead use methods line `Button.inline(...) <inline>` etc.
You can use `inline`, `switch_inline`, `url`, `auth`, `buy` and `game`
together to create inline buttons (under the message).
You can use `text`, `request_location`, `request_phone` and `request_poll`
together to create a reply markup (replaces the user keyboard).
You can also configure the aspect of the reply with these.
The latest message with a reply markup will be the one shown to the user
(messages contain the buttons, not the chat itself).
You **cannot** mix the two type of buttons together,
and it will error if you try to do so.
The text for all buttons may be at most 142 characters.
If more characters are given, Telegram will cut the text
to 128 characters and add the ellipsis (…) character as
the 129.
"""
def __init__(self, button, *, resize, single_use, selective):
self.button = button
self.resize = resize
self.single_use = single_use
self.selective = selective
@staticmethod
def _is_inline(button):
"""
Returns `True` if the button belongs to an inline keyboard.
"""
return isinstance(button, (
types.KeyboardButtonBuy,
types.KeyboardButtonCallback,
types.KeyboardButtonGame,
types.KeyboardButtonSwitchInline,
types.KeyboardButtonUrl,
types.InputKeyboardButtonUrlAuth,
types.KeyboardButtonWebView,
))
@staticmethod
def inline(text, data=None):
"""
Creates a new inline button with some payload data in it.
If `data` is omitted, the given `text` will be used as `data`.
In any case `data` should be either `bytes` or `str`.
Note that the given `data` must be less or equal to 64 bytes.
If more than 64 bytes are passed as data, ``ValueError`` is raised.
If you need to store more than 64 bytes, consider saving the real
data in a database and a reference to that data inside the button.
When the user clicks this button, `events.CallbackQuery
<telethon.events.callbackquery.CallbackQuery>` will trigger with the
same data that the button contained, so that you can determine which
button was pressed.
"""
if not data:
data = text.encode('utf-8')
elif not isinstance(data, (bytes, bytearray, memoryview)):
data = str(data).encode('utf-8')
if len(data) > 64:
raise ValueError('Too many bytes for the data')
return types.KeyboardButtonCallback(text, data)
@staticmethod
def switch_inline(text, query='', same_peer=False):
"""
Creates a new inline button to switch to inline query.
If `query` is given, it will be the default text to be used
when making the inline query.
If ``same_peer is True`` the inline query will directly be
set under the currently opened chat. Otherwise, the user will
have to select a different dialog to make the query.
When the user clicks this button, after a chat is selected, their
input field will be filled with the username of your bot followed
by the query text, ready to make inline queries.
"""
return types.KeyboardButtonSwitchInline(text, query, same_peer)
@staticmethod
def url(text, url=None):
"""
Creates a new inline button to open the desired URL on click.
If no `url` is given, the `text` will be used as said URL instead.
You cannot detect that the user clicked this button directly.
When the user clicks this button, a confirmation box will be shown
to the user asking whether they want to open the displayed URL unless
the domain is trusted, and once confirmed the URL will open in their
device.
"""
return types.KeyboardButtonUrl(text, url or text)
@staticmethod
def auth(text, url=None, *, bot=None, write_access=False, fwd_text=None):
"""
Creates a new inline button to authorize the user at the given URL.
You should set the `url` to be on the same domain as the one configured
for the desired `bot` via `@BotFather <https://t.me/BotFather>`_ using
the ``/setdomain`` command.
For more information about letting the user login via Telegram to
a certain domain, see https://core.telegram.org/widgets/login.
If no `url` is specified, it will default to `text`.
Args:
bot (`hints.EntityLike`):
The bot that requires this authorization. By default, this
is the bot that is currently logged in (itself), although
you may pass a different input peer.
.. note::
For now, you cannot use ID or username for this argument.
If you want to use a different bot than the one currently
logged in, you must manually use `client.get_input_entity()
<telethon.client.users.UserMethods.get_input_entity>`.
write_access (`bool`):
Whether write access is required or not.
This is `False` by default (read-only access).
fwd_text (`str`):
The new text to show in the button if the message is
forwarded. By default, the button text will be the same.
When the user clicks this button, a confirmation box will be shown
to the user asking whether they want to login to the specified domain.
"""
return types.InputKeyboardButtonUrlAuth(
text=text,
url=url or text,
bot=utils.get_input_user(bot or types.InputUserSelf()),
request_write_access=write_access,
fwd_text=fwd_text
)
@classmethod
def text(cls, text, *, resize=None, single_use=None, selective=None):
"""
Creates a new keyboard button with the given text.
Args:
resize (`bool`):
If present, the entire keyboard will be reconfigured to
be resized and be smaller if there are not many buttons.
single_use (`bool`):
If present, the entire keyboard will be reconfigured to
be usable only once before it hides itself.
selective (`bool`):
If present, the entire keyboard will be reconfigured to
be "selective". The keyboard will be shown only to specific
users. It will target users that are @mentioned in the text
of the message or to the sender of the message you reply to.
When the user clicks this button, a text message with the same text
as the button will be sent, and can be handled with `events.NewMessage
<telethon.events.newmessage.NewMessage>`. You cannot distinguish
between a button press and the user typing and sending exactly the
same text on their own.
"""
return cls(types.KeyboardButton(text),
resize=resize, single_use=single_use, selective=selective)
@classmethod
def request_location(cls, text, *,
resize=None, single_use=None, selective=None):
"""
Creates a new keyboard button to request the user's location on click.
``resize``, ``single_use`` and ``selective`` are documented in `text`.
When the user clicks this button, a confirmation box will be shown
to the user asking whether they want to share their location with the
bot, and if confirmed a message with geo media will be sent.
"""
return cls(types.KeyboardButtonRequestGeoLocation(text),
resize=resize, single_use=single_use, selective=selective)
@classmethod
def request_phone(cls, text, *,
resize=None, single_use=None, selective=None):
"""
Creates a new keyboard button to request the user's phone on click.
``resize``, ``single_use`` and ``selective`` are documented in `text`.
When the user clicks this button, a confirmation box will be shown
to the user asking whether they want to share their phone with the
bot, and if confirmed a message with contact media will be sent.
"""
return cls(types.KeyboardButtonRequestPhone(text),
resize=resize, single_use=single_use, selective=selective)
@classmethod
def request_poll(cls, text, *, force_quiz=False,
resize=None, single_use=None, selective=None):
"""
Creates a new keyboard button to request the user to create a poll.
If `force_quiz` is `False`, the user will be allowed to choose whether
they want their poll to be a quiz or not. Otherwise, the user will be
forced to create a quiz when creating the poll.
If a poll is a quiz, there will be only one answer that is valid, and
the votes cannot be retracted. Otherwise, users can vote and retract
the vote, and the pol might be multiple choice.
``resize``, ``single_use`` and ``selective`` are documented in `text`.
When the user clicks this button, a screen letting the user create a
poll will be shown, and if they do create one, the poll will be sent.
"""
return cls(types.KeyboardButtonRequestPoll(text, quiz=force_quiz),
resize=resize, single_use=single_use, selective=selective)
@staticmethod
def clear(selective=None):
"""
Clears all keyboard buttons after sending a message with this markup.
When used, no other button should be present or it will be ignored.
``selective`` is as documented in `text`.
"""
return types.ReplyKeyboardHide(selective=selective)
@staticmethod
def force_reply(single_use=None, selective=None, placeholder=None):
"""
Forces a reply to the message with this markup. If used,
no other button should be present or it will be ignored.
``single_use`` and ``selective`` are as documented in `text`.
Args:
placeholder (str):
text to show the user at typing place of message.
If the placeholder is too long, Telegram applications will
crop the text (for example, to 64 characters and adding an
ellipsis (…) character as the 65th).
"""
return types.ReplyKeyboardForceReply(
single_use=single_use,
selective=selective,
placeholder=placeholder)
@staticmethod
def buy(text):
"""
Creates a new inline button to buy a product.
This can only be used when sending files of type
:tl:`InputMediaInvoice`, and must be the first button.
If the button is not specified, Telegram will automatically
add the button to the message. See the
`Payments API <https://core.telegram.org/api/payments>`__
documentation for more information.
"""
return types.KeyboardButtonBuy(text)
@staticmethod
def game(text):
"""
Creates a new inline button to start playing a game.
This should be used when sending files of type
:tl:`InputMediaGame`, and must be the first button.
See the
`Games <https://core.telegram.org/api/bots/games>`__
documentation for more information on using games.
"""
return types.KeyboardButtonGame(text)

View File

@@ -0,0 +1,150 @@
import abc
from ... import errors, utils
from ...tl import types
class ChatGetter(abc.ABC):
"""
Helper base class that introduces the `chat`, `input_chat`
and `chat_id` properties and `get_chat` and `get_input_chat`
methods.
"""
def __init__(self, chat_peer=None, *, input_chat=None, chat=None, broadcast=None):
self._chat_peer = chat_peer
self._input_chat = input_chat
self._chat = chat
self._broadcast = broadcast
self._client = None
@property
def chat(self):
"""
Returns the :tl:`User`, :tl:`Chat` or :tl:`Channel` where this object
belongs to. It may be `None` if Telegram didn't send the chat.
If you only need the ID, use `chat_id` instead.
If you need to call a method which needs
this chat, use `input_chat` instead.
If you're using `telethon.events`, use `get_chat()` instead.
"""
return self._chat
async def get_chat(self):
"""
Returns `chat`, but will make an API call to find the
chat unless it's already cached.
If you only need the ID, use `chat_id` instead.
If you need to call a method which needs
this chat, use `get_input_chat()` instead.
"""
# See `get_sender` for information about 'min'.
if (self._chat is None or getattr(self._chat, 'min', None))\
and await self.get_input_chat():
try:
self._chat =\
await self._client.get_entity(self._input_chat)
except ValueError:
await self._refetch_chat()
return self._chat
@property
def input_chat(self):
"""
This :tl:`InputPeer` is the input version of the chat where the
message was sent. Similarly to `input_sender
<telethon.tl.custom.sendergetter.SenderGetter.input_sender>`, this
doesn't have things like username or similar, but still useful in
some cases.
Note that this might not be available if the library doesn't
have enough information available.
"""
if self._input_chat is None and self._chat_peer and self._client:
try:
self._input_chat = self._client._mb_entity_cache.get(
utils.get_peer_id(self._chat_peer, add_mark=False))._as_input_peer()
except AttributeError:
pass
return self._input_chat
async def get_input_chat(self):
"""
Returns `input_chat`, but will make an API call to find the
input chat unless it's already cached.
"""
if self.input_chat is None and self.chat_id and self._client:
try:
# The chat may be recent, look in dialogs
target = self.chat_id
async for d in self._client.iter_dialogs(100):
if d.id == target:
self._chat = d.entity
self._input_chat = d.input_entity
break
except errors.RPCError:
pass
return self._input_chat
@property
def chat_id(self):
"""
Returns the marked chat integer ID. Note that this value **will
be different** from ``peer_id`` for incoming private messages, since
the chat *to* which the messages go is to your own person, but
the *chat* itself is with the one who sent the message.
TL;DR; this gets the ID that you expect.
If there is a chat in the object, `chat_id` will *always* be set,
which is why you should use it instead of `chat.id <chat>`.
"""
return utils.get_peer_id(self._chat_peer) if self._chat_peer else None
@property
def is_private(self):
"""
`True` if the message was sent as a private message.
Returns `None` if there isn't enough information
(e.g. on `events.MessageDeleted <telethon.events.messagedeleted.MessageDeleted>`).
"""
return isinstance(self._chat_peer, types.PeerUser) if self._chat_peer else None
@property
def is_group(self):
"""
True if the message was sent on a group or megagroup.
Returns `None` if there isn't enough information
(e.g. on `events.MessageDeleted <telethon.events.messagedeleted.MessageDeleted>`).
"""
# TODO Cache could tell us more in the future
if self._broadcast is None and hasattr(self.chat, 'broadcast'):
self._broadcast = bool(self.chat.broadcast)
if isinstance(self._chat_peer, types.PeerChannel):
if self._broadcast is None:
return None
else:
return not self._broadcast
return isinstance(self._chat_peer, types.PeerChat)
@property
def is_channel(self):
"""`True` if the message was sent on a megagroup or channel."""
# The only case where chat peer could be none is in MessageDeleted,
# however those always have the peer in channels.
return isinstance(self._chat_peer, types.PeerChannel)
async def _refetch_chat(self):
"""
Re-fetches chat information through other means.
"""

View File

@@ -0,0 +1,529 @@
import asyncio
import functools
import inspect
import itertools
import time
from .chatgetter import ChatGetter
from ... import helpers, utils, errors
# Sometimes the edits arrive very fast (within the same second).
# In that case we add a small delta so that the age is older, for
# comparision purposes. This value is enough for up to 1000 messages.
_EDIT_COLLISION_DELTA = 0.001
def _checks_cancelled(f):
@functools.wraps(f)
def wrapper(self, *args, **kwargs):
if self._cancelled:
raise asyncio.CancelledError('The conversation was cancelled before')
return f(self, *args, **kwargs)
return wrapper
class Conversation(ChatGetter):
"""
Represents a conversation inside an specific chat.
A conversation keeps track of new messages since it was
created until its exit and easily lets you query the
current state.
If you need a conversation across two or more chats,
you should use two conversations and synchronize them
as you better see fit.
"""
_id_counter = 0
_custom_counter = 0
def __init__(self, client, input_chat,
*, timeout, total_timeout, max_messages,
exclusive, replies_are_responses):
# This call resets the client
ChatGetter.__init__(self, input_chat=input_chat)
self._id = Conversation._id_counter
Conversation._id_counter += 1
self._client = client
self._timeout = timeout
self._total_timeout = total_timeout
self._total_due = None
self._outgoing = set()
self._last_outgoing = 0
self._incoming = []
self._last_incoming = 0
self._max_incoming = max_messages
self._last_read = None
self._custom = {}
self._pending_responses = {}
self._pending_replies = {}
self._pending_edits = {}
self._pending_reads = {}
self._exclusive = exclusive
self._cancelled = False
# The user is able to expect two responses for the same message.
# {desired message ID: next incoming index}
self._response_indices = {}
if replies_are_responses:
self._reply_indices = self._response_indices
else:
self._reply_indices = {}
self._edit_dates = {}
@_checks_cancelled
async def send_message(self, *args, **kwargs):
"""
Sends a message in the context of this conversation. Shorthand
for `telethon.client.messages.MessageMethods.send_message` with
``entity`` already set.
"""
sent = await self._client.send_message(
self._input_chat, *args, **kwargs)
# Albums will be lists, so handle that
ms = sent if isinstance(sent, list) else (sent,)
self._outgoing.update(m.id for m in ms)
self._last_outgoing = ms[-1].id
return sent
@_checks_cancelled
async def send_file(self, *args, **kwargs):
"""
Sends a file in the context of this conversation. Shorthand
for `telethon.client.uploads.UploadMethods.send_file` with
``entity`` already set.
"""
sent = await self._client.send_file(
self._input_chat, *args, **kwargs)
# Albums will be lists, so handle that
ms = sent if isinstance(sent, list) else (sent,)
self._outgoing.update(m.id for m in ms)
self._last_outgoing = ms[-1].id
return sent
@_checks_cancelled
def mark_read(self, message=None):
"""
Marks as read the latest received message if ``message is None``.
Otherwise, marks as read until the given message (or message ID).
This is equivalent to calling `client.send_read_acknowledge
<telethon.client.messages.MessageMethods.send_read_acknowledge>`.
"""
if message is None:
if self._incoming:
message = self._incoming[-1].id
else:
message = 0
elif not isinstance(message, int):
message = message.id
return self._client.send_read_acknowledge(
self._input_chat, max_id=message)
def get_response(self, message=None, *, timeout=None):
"""
Gets the next message that responds to a previous one. This is
the method you need most of the time, along with `get_edit`.
Args:
message (`Message <telethon.tl.custom.message.Message>` | `int`, optional):
The message (or the message ID) for which a response
is expected. By default this is the last sent message.
timeout (`int` | `float`, optional):
If present, this `timeout` (in seconds) will override the
per-action timeout defined for the conversation.
.. code-block:: python
async with client.conversation(...) as conv:
await conv.send_message('Hey, what is your name?')
response = await conv.get_response()
name = response.text
await conv.send_message('Nice to meet you, {}!'.format(name))
"""
return self._get_message(
message, self._response_indices, self._pending_responses, timeout,
lambda x, y: True
)
def get_reply(self, message=None, *, timeout=None):
"""
Gets the next message that explicitly replies to a previous one.
"""
return self._get_message(
message, self._reply_indices, self._pending_replies, timeout,
lambda x, y: x.reply_to and x.reply_to.reply_to_msg_id == y
)
def _get_message(
self, target_message, indices, pending, timeout, condition):
"""
Gets the next desired message under the desired condition.
Args:
target_message (`object`):
The target message for which we want to find another
response that applies based on `condition`.
indices (`dict`):
This dictionary remembers the last ID chosen for the
input `target_message`.
pending (`dict`):
This dictionary remembers {msg_id: Future} to be set
once `condition` is met.
timeout (`int`):
The timeout (in seconds) override to use for this operation.
condition (`callable`):
The condition callable that checks if an incoming
message is a valid response.
"""
start_time = time.time()
target_id = self._get_message_id(target_message)
# If there is no last-chosen ID, make sure to pick one *after*
# the input message, since we don't want responses back in time
if target_id not in indices:
for i, incoming in enumerate(self._incoming):
if incoming.id > target_id:
indices[target_id] = i
break
else:
indices[target_id] = len(self._incoming)
# We will always return a future from here, even if the result
# can be set immediately. Otherwise, needing to await only
# sometimes is an annoying edge case (i.e. we would return
# a `Message` but `get_response()` always `await`'s).
future = self._client.loop.create_future()
# If there are enough responses saved return the next one
last_idx = indices[target_id]
if last_idx < len(self._incoming):
incoming = self._incoming[last_idx]
if condition(incoming, target_id):
indices[target_id] += 1
future.set_result(incoming)
return future
# Otherwise the next incoming response will be the one to use
#
# Note how we fill "pending" before giving control back to the
# event loop through "await". We want to register it as soon as
# possible, since any other task switch may arrive with the result.
pending[target_id] = future
return self._get_result(future, start_time, timeout, pending, target_id)
def get_edit(self, message=None, *, timeout=None):
"""
Awaits for an edit after the last message to arrive.
The arguments are the same as those for `get_response`.
"""
start_time = time.time()
target_id = self._get_message_id(message)
target_date = self._edit_dates.get(target_id, 0)
earliest_edit = min(
(x for x in self._incoming
if x.edit_date
and x.id > target_id
and x.edit_date.timestamp() > target_date
),
key=lambda x: x.edit_date.timestamp(),
default=None
)
future = self._client.loop.create_future()
if earliest_edit and earliest_edit.edit_date.timestamp() > target_date:
self._edit_dates[target_id] = earliest_edit.edit_date.timestamp()
future.set_result(earliest_edit)
return future # we should always return something we can await
# Otherwise the next incoming response will be the one to use
self._pending_edits[target_id] = future
return self._get_result(future, start_time, timeout, self._pending_edits, target_id)
def wait_read(self, message=None, *, timeout=None):
"""
Awaits for the sent message to be marked as read. Note that
receiving a response doesn't imply the message was read, and
this action will also trigger even without a response.
"""
start_time = time.time()
future = self._client.loop.create_future()
target_id = self._get_message_id(message)
if self._last_read is None:
self._last_read = target_id - 1
if self._last_read >= target_id:
return
self._pending_reads[target_id] = future
return self._get_result(future, start_time, timeout, self._pending_reads, target_id)
async def wait_event(self, event, *, timeout=None):
"""
Waits for a custom event to occur. Timeouts still apply.
.. note::
**Only use this if there isn't another method available!**
For example, don't use `wait_event` for new messages,
since `get_response` already exists, etc.
Unless you're certain that your code will run fast enough,
generally you should get a "handle" of this special coroutine
before acting. In this example you will see how to wait for a user
to join a group with proper use of `wait_event`:
.. code-block:: python
from telethon import TelegramClient, events
client = TelegramClient(...)
group_id = ...
async def main():
# Could also get the user id from an event; this is just an example
user_id = ...
async with client.conversation(user_id) as conv:
# Get a handle to the future event we'll wait for
handle = conv.wait_event(events.ChatAction(
group_id,
func=lambda e: e.user_joined and e.user_id == user_id
))
# Perform whatever action in between
await conv.send_message('Please join this group before speaking to me!')
# Wait for the event we registered above to fire
event = await handle
# Continue with the conversation
await conv.send_message('Thanks!')
This way your event can be registered before acting,
since the response may arrive before your event was
registered. It depends on your use case since this
also means the event can arrive before you send
a previous action.
"""
start_time = time.time()
if isinstance(event, type):
event = event()
await event.resolve(self._client)
counter = Conversation._custom_counter
Conversation._custom_counter += 1
future = self._client.loop.create_future()
self._custom[counter] = (event, future)
try:
return await self._get_result(future, start_time, timeout, self._custom, counter)
finally:
# Need to remove it from the dict if it times out, else we may
# try and fail to set the result later (#1618).
self._custom.pop(counter, None)
async def _check_custom(self, built):
for key, (ev, fut) in list(self._custom.items()):
ev_type = type(ev)
inst = built[ev_type]
if inst:
filter = ev.filter(inst)
if inspect.isawaitable(filter):
filter = await filter
if filter:
fut.set_result(inst)
del self._custom[key]
def _on_new_message(self, response):
response = response.message
if response.chat_id != self.chat_id or response.out:
return
if len(self._incoming) == self._max_incoming:
self._cancel_all(ValueError('Too many incoming messages'))
return
self._incoming.append(response)
# Most of the time, these dictionaries will contain just one item
# TODO In fact, why not make it be that way? Force one item only.
# How often will people want to wait for two responses at
# the same time? It's impossible, first one will arrive
# and then another, so they can do that.
for msg_id, future in list(self._pending_responses.items()):
self._response_indices[msg_id] = len(self._incoming)
future.set_result(response)
del self._pending_responses[msg_id]
for msg_id, future in list(self._pending_replies.items()):
if response.reply_to and msg_id == response.reply_to.reply_to_msg_id:
self._reply_indices[msg_id] = len(self._incoming)
future.set_result(response)
del self._pending_replies[msg_id]
def _on_edit(self, message):
message = message.message
if message.chat_id != self.chat_id or message.out:
return
# We have to update our incoming messages with the new edit date
for i, m in enumerate(self._incoming):
if m.id == message.id:
self._incoming[i] = message
break
for msg_id, future in list(self._pending_edits.items()):
if msg_id < message.id:
edit_ts = message.edit_date.timestamp()
# We compare <= because edit_ts resolution is always to
# seconds, but we may have increased _edit_dates before.
# Since the dates are ever growing this is not a problem.
if edit_ts <= self._edit_dates.get(msg_id, 0):
self._edit_dates[msg_id] += _EDIT_COLLISION_DELTA
else:
self._edit_dates[msg_id] = message.edit_date.timestamp()
future.set_result(message)
del self._pending_edits[msg_id]
def _on_read(self, event):
if event.chat_id != self.chat_id or event.inbox:
return
self._last_read = event.max_id
for msg_id, pending in list(self._pending_reads.items()):
if msg_id >= self._last_read:
pending.set_result(True)
del self._pending_reads[msg_id]
def _get_message_id(self, message):
if message is not None: # 0 is valid but false-y, check for None
return message if isinstance(message, int) else message.id
elif self._last_outgoing:
return self._last_outgoing
else:
raise ValueError('No message was sent previously')
@_checks_cancelled
def _get_result(self, future, start_time, timeout, pending, target_id):
due = self._total_due
if timeout is None:
timeout = self._timeout
if timeout is not None:
due = min(due, start_time + timeout)
# NOTE: We can't try/finally to pop from pending here because
# the event loop needs to get back to us, but it might
# dispatch another update before, and in that case a
# response could be set twice. So responses must be
# cleared when their futures are set to a result.
return asyncio.wait_for(
future,
timeout=None if due == float('inf') else due - time.time()
)
def _cancel_all(self, exception=None):
self._cancelled = True
for pending in itertools.chain(
self._pending_responses.values(),
self._pending_replies.values(),
self._pending_edits.values()):
if exception:
pending.set_exception(exception)
else:
pending.cancel()
for _, fut in self._custom.values():
if exception:
fut.set_exception(exception)
else:
fut.cancel()
async def __aenter__(self):
self._input_chat = \
await self._client.get_input_entity(self._input_chat)
self._chat_peer = utils.get_peer(self._input_chat)
# Make sure we're the only conversation in this chat if it's exclusive
chat_id = utils.get_peer_id(self._chat_peer)
conv_set = self._client._conversations[chat_id]
if self._exclusive and conv_set:
raise errors.AlreadyInConversationError()
conv_set.add(self)
self._cancelled = False
self._last_outgoing = 0
self._last_incoming = 0
for d in (
self._outgoing, self._incoming,
self._pending_responses, self._pending_replies,
self._pending_edits, self._response_indices,
self._reply_indices, self._edit_dates, self._custom):
d.clear()
if self._total_timeout:
self._total_due = time.time() + self._total_timeout
else:
self._total_due = float('inf')
return self
def cancel(self):
"""
Cancels the current conversation. Pending responses and subsequent
calls to get a response will raise ``asyncio.CancelledError``.
This method is synchronous and should not be awaited.
"""
self._cancel_all()
async def cancel_all(self):
"""
Calls `cancel` on *all* conversations in this chat.
Note that you should ``await`` this method, since it's meant to be
used outside of a context manager, and it needs to resolve the chat.
"""
chat_id = await self._client.get_peer_id(self._input_chat)
for conv in self._client._conversations[chat_id]:
conv.cancel()
async def __aexit__(self, exc_type, exc_val, exc_tb):
chat_id = utils.get_peer_id(self._chat_peer)
conv_set = self._client._conversations[chat_id]
conv_set.discard(self)
if not conv_set:
del self._client._conversations[chat_id]
self._cancel_all()
__enter__ = helpers._sync_enter
__exit__ = helpers._sync_exit

View File

@@ -0,0 +1,161 @@
from . import Draft
from .. import TLObject, types, functions
from ... import utils
class Dialog:
"""
Custom class that encapsulates a dialog (an open "conversation" with
someone, a group or a channel) providing an abstraction to easily
access the input version/normal entity/message etc. The library will
return instances of this class when calling :meth:`.get_dialogs()`.
Args:
dialog (:tl:`Dialog`):
The original ``Dialog`` instance.
pinned (`bool`):
Whether this dialog is pinned to the top or not.
folder_id (`folder_id`):
The folder ID that this dialog belongs to.
archived (`bool`):
Whether this dialog is archived or not (``folder_id is None``).
message (`Message <telethon.tl.custom.message.Message>`):
The last message sent on this dialog. Note that this member
will not be updated when new messages arrive, it's only set
on creation of the instance.
date (`datetime`):
The date of the last message sent on this dialog.
entity (`entity`):
The entity that belongs to this dialog (user, chat or channel).
input_entity (:tl:`InputPeer`):
Input version of the entity.
id (`int`):
The marked ID of the entity, which is guaranteed to be unique.
name (`str`):
Display name for this dialog. For chats and channels this is
their title, and for users it's "First-Name Last-Name".
title (`str`):
Alias for `name`.
unread_count (`int`):
How many messages are currently unread in this dialog. Note that
this value won't update when new messages arrive.
unread_mentions_count (`int`):
How many mentions are currently unread in this dialog. Note that
this value won't update when new messages arrive.
draft (`Draft <telethon.tl.custom.draft.Draft>`):
The draft object in this dialog. It will not be `None`,
so you can call ``draft.set_message(...)``.
is_user (`bool`):
`True` if the `entity` is a :tl:`User`.
is_group (`bool`):
`True` if the `entity` is a :tl:`Chat`
or a :tl:`Channel` megagroup.
is_channel (`bool`):
`True` if the `entity` is a :tl:`Channel`.
"""
def __init__(self, client, dialog, entities, message):
# Both entities and messages being dicts {ID: item}
self._client = client
self.dialog = dialog
self.pinned = bool(dialog.pinned)
self.folder_id = dialog.folder_id
self.archived = dialog.folder_id is not None
self.message = message
self.date = getattr(self.message, 'date', None)
self.entity = entities[utils.get_peer_id(dialog.peer)]
self.input_entity = utils.get_input_peer(self.entity)
self.id = utils.get_peer_id(self.entity) # ^ May be InputPeerSelf()
self.name = self.title = utils.get_display_name(self.entity)
self.unread_count = dialog.unread_count
self.unread_mentions_count = dialog.unread_mentions_count
self.draft = Draft(client, self.entity, self.dialog.draft)
self.is_user = isinstance(self.entity, types.User)
self.is_group = (
isinstance(self.entity, (types.Chat, types.ChatForbidden)) or
(isinstance(self.entity, types.Channel) and self.entity.megagroup)
)
self.is_channel = isinstance(self.entity, types.Channel)
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)
async def delete(self, revoke=False):
"""
Deletes the dialog from your dialog list. If you own the
channel this won't destroy it, only delete it from the list.
Shorthand for `telethon.client.dialogs.DialogMethods.delete_dialog`
with ``entity`` already set.
"""
# Pass the entire entity so the method can determine whether
# the `Chat` is deactivated (in which case we don't kick ourselves,
# or it would raise `PEER_ID_INVALID`).
await self._client.delete_dialog(self.entity, revoke=revoke)
async def archive(self, folder=1):
"""
Archives (or un-archives) this dialog.
Args:
folder (`int`, optional):
The folder to which the dialog should be archived to.
If you want to "un-archive" it, use ``folder=0``.
Returns:
The :tl:`Updates` object that the request produces.
Example:
.. code-block:: python
# Archiving
dialog.archive()
# Un-archiving
dialog.archive(0)
"""
return await self._client(functions.folders.EditPeerFoldersRequest([
types.InputFolderPeer(self.input_entity, folder_id=folder)
]))
def to_dict(self):
return {
'_': 'Dialog',
'name': self.name,
'date': self.date,
'draft': self.draft,
'message': self.message,
'entity': self.entity,
}
def __str__(self):
return TLObject.pretty_format(self.to_dict())
def stringify(self):
return TLObject.pretty_format(self.to_dict(), indent=0)

View File

@@ -0,0 +1,191 @@
import datetime
from .. import TLObject, types
from ..functions.messages import SaveDraftRequest
from ..types import DraftMessage
from ...errors import RPCError
from ...extensions import markdown
from ...utils import get_input_peer, get_peer, get_peer_id
class Draft:
"""
Custom class that encapsulates a draft on the Telegram servers, providing
an abstraction to change the message conveniently. The library will return
instances of this class when calling :meth:`get_drafts()`.
Args:
date (`datetime`):
The date of the draft.
link_preview (`bool`):
Whether the link preview is enabled or not.
reply_to_msg_id (`int`):
The message ID that the draft will reply to.
"""
def __init__(self, client, entity, draft):
self._client = client
self._peer = get_peer(entity)
self._entity = entity
self._input_entity = get_input_peer(entity) if entity else None
if not draft or not isinstance(draft, DraftMessage):
draft = DraftMessage('', None, None, None, None)
self._text = markdown.unparse(draft.message, draft.entities)
self._raw_text = draft.message
self.date = draft.date
self.link_preview = not draft.no_webpage
self.reply_to_msg_id = draft.reply_to.reply_to_msg_id if isinstance(draft.reply_to, types.InputReplyToMessage) else None
@property
def entity(self):
"""
The entity that belongs to this dialog (user, chat or channel).
"""
return self._entity
@property
def input_entity(self):
"""
Input version of the entity.
"""
if not self._input_entity:
try:
self._input_entity = self._client._mb_entity_cache.get(
get_peer_id(self._peer, add_mark=False))._as_input_peer()
except AttributeError:
pass
return self._input_entity
async def get_entity(self):
"""
Returns `entity` but will make an API call if necessary.
"""
if not self.entity and await self.get_input_entity():
try:
self._entity =\
await self._client.get_entity(self._input_entity)
except ValueError:
pass
return self._entity
async def get_input_entity(self):
"""
Returns `input_entity` but will make an API call if necessary.
"""
# We don't actually have an API call we can make yet
# to get more info, but keep this method for consistency.
return self.input_entity
@property
def text(self):
"""
The markdown text contained in the draft. It will be
empty if there is no text (and hence no draft is set).
"""
return self._text
@property
def raw_text(self):
"""
The raw (text without formatting) contained in the draft.
It will be empty if there is no text (thus draft not set).
"""
return self._raw_text
@property
def is_empty(self):
"""
Convenience bool to determine if the draft is empty or not.
"""
return not self._text
async def set_message(
self, text=None, reply_to=0, parse_mode=(),
link_preview=None):
"""
Changes the draft message on the Telegram servers. The changes are
reflected in this object.
:param str text: New text of the draft.
Preserved if left as None.
:param int reply_to: Message ID to reply to.
Preserved if left as 0, erased if set to None.
:param bool link_preview: Whether to attach a web page preview.
Preserved if left as None.
:param str parse_mode: The parse mode to be used for the text.
:return bool: `True` on success.
"""
if text is None:
text = self._text
if reply_to == 0:
reply_to = self.reply_to_msg_id
if link_preview is None:
link_preview = self.link_preview
raw_text, entities =\
await self._client._parse_message_text(text, parse_mode)
result = await self._client(SaveDraftRequest(
peer=self._peer,
message=raw_text,
no_webpage=not link_preview,
reply_to=None if reply_to is None else types.InputReplyToMessage(reply_to),
entities=entities
))
if result:
self._text = text
self._raw_text = raw_text
self.link_preview = link_preview
self.reply_to_msg_id = reply_to
self.date = datetime.datetime.now(tz=datetime.timezone.utc)
return result
async def send(self, clear=True, parse_mode=()):
"""
Sends the contents of this draft to the dialog. This is just a
wrapper around ``send_message(dialog.input_entity, *args, **kwargs)``.
"""
await self._client.send_message(
self._peer, self.text, reply_to=self.reply_to_msg_id,
link_preview=self.link_preview, parse_mode=parse_mode,
clear_draft=clear
)
async def delete(self):
"""
Deletes this draft, and returns `True` on success.
"""
return await self.set_message(text='')
def to_dict(self):
try:
entity = self.entity
except RPCError as e:
entity = e
return {
'_': 'Draft',
'text': self.text,
'entity': entity,
'date': self.date,
'link_preview': self.link_preview,
'reply_to_msg_id': self.reply_to_msg_id
}
def __str__(self):
return TLObject.pretty_format(self.to_dict())
def stringify(self):
return TLObject.pretty_format(self.to_dict(), indent=0)

View File

@@ -0,0 +1,146 @@
import mimetypes
import os
from ... import utils
from ...tl import types
class File:
"""
Convenience class over media like photos or documents, which
supports accessing the attributes in a more convenient way.
If any of the attributes are not present in the current media,
the properties will be `None`.
The original media is available through the ``media`` attribute.
"""
def __init__(self, media):
self.media = media
@property
def id(self):
"""
The old bot-API style ``file_id`` representing this file.
.. warning::
This feature has not been maintained for a long time and
may not work. It will be removed in future versions.
.. note::
This file ID may not work under user accounts,
but should still be usable by bot accounts.
You can, however, still use it to identify
a file in for example a database.
"""
return utils.pack_bot_file_id(self.media)
@property
def name(self):
"""
The file name of this document.
"""
return self._from_attr(types.DocumentAttributeFilename, 'file_name')
@property
def ext(self):
"""
The extension from the mime type of this file.
If the mime type is unknown, the extension
from the file name (if any) will be used.
"""
return (
mimetypes.guess_extension(self.mime_type)
or os.path.splitext(self.name or '')[-1]
or None
)
@property
def mime_type(self):
"""
The mime-type of this file.
"""
if isinstance(self.media, types.Photo):
return 'image/jpeg'
elif isinstance(self.media, types.Document):
return self.media.mime_type
@property
def width(self):
"""
The width in pixels of this media if it's a photo or a video.
"""
if isinstance(self.media, types.Photo):
return max(getattr(s, 'w', 0) for s in self.media.sizes)
return self._from_attr((
types.DocumentAttributeImageSize, types.DocumentAttributeVideo), 'w')
@property
def height(self):
"""
The height in pixels of this media if it's a photo or a video.
"""
if isinstance(self.media, types.Photo):
return max(getattr(s, 'h', 0) for s in self.media.sizes)
return self._from_attr((
types.DocumentAttributeImageSize, types.DocumentAttributeVideo), 'h')
@property
def duration(self):
"""
The duration in seconds of the audio or video.
"""
return self._from_attr((
types.DocumentAttributeAudio, types.DocumentAttributeVideo), 'duration')
@property
def title(self):
"""
The title of the song.
"""
return self._from_attr(types.DocumentAttributeAudio, 'title')
@property
def performer(self):
"""
The performer of the song.
"""
return self._from_attr(types.DocumentAttributeAudio, 'performer')
@property
def emoji(self):
"""
A string with all emoji that represent the current sticker.
"""
return self._from_attr(types.DocumentAttributeSticker, 'alt')
@property
def sticker_set(self):
"""
The :tl:`InputStickerSet` to which the sticker file belongs.
"""
return self._from_attr(types.DocumentAttributeSticker, 'stickerset')
@property
def size(self):
"""
The size in bytes of this file.
For photos, this is the heaviest thumbnail, as it often repressents the largest dimensions.
"""
if isinstance(self.media, types.Photo):
return max(filter(None, map(utils._photo_size_byte_count, self.media.sizes)), default=None)
elif isinstance(self.media, types.Document):
return self.media.size
def _from_attr(self, cls, field):
if isinstance(self.media, types.Document):
for attr in self.media.attributes:
if isinstance(attr, cls):
return getattr(attr, field, None)

View File

@@ -0,0 +1,51 @@
from .chatgetter import ChatGetter
from .sendergetter import SenderGetter
from ... import utils, helpers
from ...tl import types
class Forward(ChatGetter, SenderGetter):
"""
Custom class that encapsulates a :tl:`MessageFwdHeader` providing an
abstraction to easily access information like the original sender.
Remember that this class implements `ChatGetter
<telethon.tl.custom.chatgetter.ChatGetter>` and `SenderGetter
<telethon.tl.custom.sendergetter.SenderGetter>` which means you
have access to all their sender and chat properties and methods.
Attributes:
original_fwd (:tl:`MessageFwdHeader`):
The original :tl:`MessageFwdHeader` instance.
Any other attribute:
Attributes not described here are the same as those available
in the original :tl:`MessageFwdHeader`.
"""
def __init__(self, client, original, entities):
# Copy all the fields, not reference! It would cause memory cycles:
# self.original_fwd.original_fwd.original_fwd.original_fwd
# ...would be valid if we referenced.
self.__dict__.update(original.__dict__)
self.original_fwd = original
sender_id = sender = input_sender = peer = chat = input_chat = None
if original.from_id:
ty = helpers._entity_type(original.from_id)
if ty == helpers._EntityType.USER:
sender_id = utils.get_peer_id(original.from_id)
sender, input_sender = utils._get_entity_pair(
sender_id, entities, client._mb_entity_cache)
elif ty in (helpers._EntityType.CHAT, helpers._EntityType.CHANNEL):
peer = original.from_id
chat, input_chat = utils._get_entity_pair(
utils.get_peer_id(peer), entities, client._mb_entity_cache)
# This call resets the client
ChatGetter.__init__(self, peer, chat=chat, input_chat=input_chat)
SenderGetter.__init__(self, sender_id, sender=sender, input_sender=input_sender)
self._client = client
# TODO We could reload the message

View File

@@ -0,0 +1,450 @@
import hashlib
from .. import functions, types
from ... import utils
_TYPE_TO_MIMES = {
'gif': ['image/gif'], # 'video/mp4' too, but that's used for video
'article': ['text/html'],
'audio': ['audio/mpeg'],
'contact': [],
'file': ['application/pdf', 'application/zip'], # actually any
'geo': [],
'photo': ['image/jpeg'],
'sticker': ['image/webp', 'application/x-tgsticker'],
'venue': [],
'video': ['video/mp4'], # tdlib includes text/html for some reason
'voice': ['audio/ogg'],
}
class InlineBuilder:
"""
Helper class to allow defining `InlineQuery
<telethon.events.inlinequery.InlineQuery>` ``results``.
Common arguments to all methods are
explained here to avoid repetition:
text (`str`, optional):
If present, the user will send a text
message with this text upon being clicked.
link_preview (`bool`, optional):
Whether to show a link preview in the sent
text message or not.
geo (:tl:`InputGeoPoint`, :tl:`GeoPoint`, :tl:`InputMediaVenue`, :tl:`MessageMediaVenue`, optional):
If present, it may either be a geo point or a venue.
period (int, optional):
The period in seconds to be used for geo points.
contact (:tl:`InputMediaContact`, :tl:`MessageMediaContact`, optional):
If present, it must be the contact information to send.
game (`bool`, optional):
May be `True` to indicate that the game will be sent.
buttons (`list`, `custom.Button <telethon.tl.custom.button.Button>`, :tl:`KeyboardButton`, optional):
Same as ``buttons`` for `client.send_message()
<telethon.client.messages.MessageMethods.send_message>`.
parse_mode (`str`, optional):
Same as ``parse_mode`` for `client.send_message()
<telethon.client.messageparse.MessageParseMethods.parse_mode>`.
id (`str`, optional):
The string ID to use for this result. If not present, it
will be the SHA256 hexadecimal digest of converting the
created :tl:`InputBotInlineResult` with empty ID to ``bytes()``,
so that the ID will be deterministic for the same input.
.. note::
If two inputs are exactly the same, their IDs will be the same
too. If you send two articles with the same ID, it will raise
``ResultIdDuplicateError``. Consider giving them an explicit
ID if you need to send two results that are the same.
"""
def __init__(self, client):
self._client = client
# noinspection PyIncorrectDocstring
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.
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 for this result.
thumb (:tl:`InputWebDocument`, optional):
The thumbnail to be shown for this result.
For now it has to be a :tl:`InputWebDocument` if present.
content (:tl:`InputWebDocument`, optional):
The content to be shown for this result.
For now it has to be a :tl:`InputWebDocument` if present.
Example:
.. code-block:: python
results = [
# Option with title and description sending a message.
builder.article(
title='First option',
description='This is the first option',
text='Text sent after clicking this option',
),
# Option with title URL to be opened when clicked.
builder.article(
title='Second option',
url='https://example.com',
text='Text sent if the user clicks the option and not the URL',
),
# Sending a message with buttons.
# You can use a list or a list of lists to include more buttons.
builder.article(
title='Third option',
text='Text sent with buttons below',
buttons=Button.url('https://example.com'),
),
]
"""
# TODO Does 'article' work always?
# article, photo, gif, mpeg4_gif, video, audio,
# voice, document, location, venue, contact, game
result = types.InputBotInlineResult(
id=id or '',
type='article',
send_message=await self._message(
text=text, parse_mode=parse_mode, link_preview=link_preview,
geo=geo, period=period,
contact=contact,
game=game,
buttons=buttons
),
title=title,
description=description,
url=url,
thumb=thumb,
content=content
)
if id is None:
result.id = hashlib.sha256(bytes(result)).hexdigest()
return result
# noinspection PyIncorrectDocstring
async def photo(
self, file, *, id=None, include_media=True,
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:
include_media (`bool`, optional):
Whether the photo file used to display the result should be
included in the message itself or not. By default, the photo
is included, and the text parameter alters the caption.
file (`obj`, optional):
Same as ``file`` for `client.send_file()
<telethon.client.uploads.UploadMethods.send_file>`.
Example:
.. code-block:: python
results = [
# Sending just the photo when the user selects it.
builder.photo('/path/to/photo.jpg'),
# Including a caption with some in-memory photo.
photo_bytesio = ...
builder.photo(
photo_bytesio,
text='This will be the caption of the sent photo',
),
# Sending just the message without including the photo.
builder.photo(
photo,
text='This will be a normal text message',
include_media=False,
),
]
"""
try:
fh = utils.get_input_photo(file)
except TypeError:
_, media, _ = await self._client._file_to_media(
file, allow_cache=True, as_image=True
)
if isinstance(media, types.InputPhoto):
fh = media
else:
r = await self._client(functions.messages.UploadMediaRequest(
types.InputPeerSelf(), media=media
))
fh = utils.get_input_photo(r.photo)
result = types.InputBotInlineResultPhoto(
id=id or '',
type='photo',
photo=fh,
send_message=await self._message(
text=text or '',
parse_mode=parse_mode,
link_preview=link_preview,
media=include_media,
geo=geo,
period=period,
contact=contact,
game=game,
buttons=buttons
)
)
if id is None:
result.id = hashlib.sha256(bytes(result)).hexdigest()
return result
# noinspection PyIncorrectDocstring
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, contact=None, game=False, buttons=None,
include_media=True
):
"""
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`` for `client.send_file()
<telethon.client.uploads.UploadMethods.send_file>`.
title (`str`, optional):
The title to be shown for this result.
description (`str`, optional):
Further explanation of what this result means.
type (`str`, optional):
The type of the document. May be one of: article, audio,
contact, file, geo, gif, photo, sticker, venue, video, voice.
It will be automatically set if ``mime_type`` is specified,
and default to ``'file'`` if no matching mime type is found.
you may need to pass ``attributes`` in order to use ``type``
effectively.
attributes (`list`, optional):
Optional attributes that override the inferred ones, like
:tl:`DocumentAttributeFilename` and so on.
include_media (`bool`, optional):
Whether the document file used to display the result should be
included in the message itself or not. By default, the document
is included, and the text parameter alters the caption.
Example:
.. code-block:: python
results = [
# Sending just the file when the user selects it.
builder.document('/path/to/file.pdf'),
# Including a caption with some in-memory file.
file_bytesio = ...
builder.document(
file_bytesio,
text='This will be the caption of the sent file',
),
# Sending just the message without including the file.
builder.document(
photo,
text='This will be a normal text message',
include_media=False,
),
]
"""
if type is None:
if voice_note:
type = 'voice'
elif mime_type:
for ty, mimes in _TYPE_TO_MIMES.items():
for mime in mimes:
if mime_type == mime:
type = ty
break
if type is None:
type = 'file'
try:
fh = utils.get_input_document(file)
except TypeError:
_, media, _ = await self._client._file_to_media(
file,
mime_type=mime_type,
attributes=attributes,
force_document=force_document,
voice_note=voice_note,
video_note=video_note,
allow_cache=use_cache
)
if isinstance(media, types.InputDocument):
fh = media
else:
r = await self._client(functions.messages.UploadMediaRequest(
types.InputPeerSelf(), media=media
))
fh = utils.get_input_document(r.document)
result = types.InputBotInlineResultDocument(
id=id or '',
type=type,
document=fh,
send_message=await self._message(
# Empty string for text if there's media but text is None.
# We may want to display a document but send text; however
# default to sending the media (without text, i.e. stickers).
text=text or '',
parse_mode=parse_mode,
link_preview=link_preview,
media=include_media,
geo=geo,
period=period,
contact=contact,
game=game,
buttons=buttons
),
title=title,
description=description
)
if id is None:
result.id = hashlib.sha256(bytes(result)).hexdigest()
return result
# noinspection PyIncorrectDocstring
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`):
The short name of the game to use.
"""
result = types.InputBotInlineResultGame(
id=id or '',
short_name=short_name,
send_message=await self._message(
text=text, parse_mode=parse_mode, link_preview=link_preview,
geo=geo, period=period,
contact=contact,
game=game,
buttons=buttons
)
)
if id is None:
result.id = hashlib.sha256(bytes(result)).hexdigest()
return result
async def _message(
self, *,
text=None, parse_mode=(), link_preview=True, media=False,
geo=None, period=60, contact=None, game=False, buttons=None
):
# Empty strings are valid but false-y; if they're empty use dummy '\0'
args = ('\0' if text == '' else text, geo, contact, game)
if sum(1 for x in args if x is not None and x is not False) != 1:
raise ValueError(
'Must set exactly one of text, geo, contact or game (set {})'
.format(', '.join(x[0] for x in zip(
'text geo contact game'.split(), args) if x[1]) or 'none')
)
markup = self._client.build_reply_markup(buttons, inline_only=True)
if text is not None:
text, msg_entities = await self._client._parse_message_text(
text, parse_mode
)
if media:
# "MediaAuto" means it will use whatever media the inline
# result itself has (stickers, photos, or documents), while
# respecting the user's text (caption) and formatting.
return types.InputBotInlineMessageMediaAuto(
message=text,
entities=msg_entities,
reply_markup=markup
)
else:
return types.InputBotInlineMessageText(
message=text,
no_webpage=not link_preview,
entities=msg_entities,
reply_markup=markup
)
elif isinstance(geo, (types.InputGeoPoint, types.GeoPoint)):
return types.InputBotInlineMessageMediaGeo(
geo_point=utils.get_input_geo(geo),
period=period,
reply_markup=markup
)
elif isinstance(geo, (types.InputMediaVenue, types.MessageMediaVenue)):
if isinstance(geo, types.InputMediaVenue):
geo_point = geo.geo_point
else:
geo_point = geo.geo
return types.InputBotInlineMessageMediaVenue(
geo_point=geo_point,
title=geo.title,
address=geo.address,
provider=geo.provider,
venue_id=geo.venue_id,
venue_type=geo.venue_type,
reply_markup=markup
)
elif isinstance(contact, (
types.InputMediaContact, types.MessageMediaContact)):
return types.InputBotInlineMessageMediaContact(
phone_number=contact.phone_number,
first_name=contact.first_name,
last_name=contact.last_name,
vcard=contact.vcard,
reply_markup=markup
)
elif game:
return types.InputBotInlineMessageGame(
reply_markup=markup
)
else:
raise ValueError('No text, game or valid geo or contact given')

View File

@@ -0,0 +1,176 @@
from .. import types, functions
from ... import utils
class InlineResult:
"""
Custom class that encapsulates a bot inline result providing
an abstraction to easily access some commonly needed features
(such as clicking a result to select it).
Attributes:
result (:tl:`BotInlineResult`):
The original :tl:`BotInlineResult` object.
"""
# tdlib types are the following (InlineQueriesManager::answer_inline_query @ 1a4a834):
# gif, article, audio, contact, file, geo, photo, sticker, venue, video, voice
#
# However, those documented in https://core.telegram.org/bots/api#inline-mode are different.
ARTICLE = 'article'
PHOTO = 'photo'
GIF = 'gif'
VIDEO = 'video'
VIDEO_GIF = 'mpeg4_gif'
AUDIO = 'audio'
DOCUMENT = 'document'
LOCATION = 'location'
VENUE = 'venue'
CONTACT = 'contact'
GAME = 'game'
def __init__(self, client, original, query_id=None, *, entity=None):
self._client = client
self.result = original
self._query_id = query_id
self._entity = entity
@property
def type(self):
"""
The always-present type of this result. It will be one of:
``'article'``, ``'photo'``, ``'gif'``, ``'mpeg4_gif'``, ``'video'``,
``'audio'``, ``'voice'``, ``'document'``, ``'location'``, ``'venue'``,
``'contact'``, ``'game'``.
You can access all of these constants through `InlineResult`,
such as `InlineResult.ARTICLE`, `InlineResult.VIDEO_GIF`, etc.
"""
return self.result.type
@property
def message(self):
"""
The always-present :tl:`BotInlineMessage` that
will be sent if `click` is called on this result.
"""
return self.result.send_message
@property
def title(self):
"""
The title for this inline result. It may be `None`.
"""
return self.result.title
@property
def description(self):
"""
The description for this inline result. It may be `None`.
"""
return self.result.description
@property
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
@property
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):
return self.result.photo
@property
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.BotInlineMediaResult):
return self.result.document
async def click(self, entity=None, reply_to=None, comment_to=None,
silent=False, clear_draft=False, hide_via=False,
background=None):
"""
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 reply to this ID or message.
comment_to (`int` | `Message <telethon.tl.custom.message.Message>`, optional):
Similar to ``reply_to``, but replies in the linked group of a
broadcast channel instead (effectively leaving a "comment to"
the specified message).
silent (`bool`, optional):
Whether the message should notify people with sound or not.
Defaults to `False` (send with a notification sound unless
the person has the chat muted). Set it to `True` to alter
this behaviour.
clear_draft (`bool`, optional):
Whether the draft should be removed after sending the
message from this result or not. Defaults to `False`.
hide_via (`bool`, optional):
Whether the "via @bot" should be hidden or not.
Only works with certain bots (like @bing or @gif).
background (`bool`, optional):
Whether the message should be send in background.
"""
if entity:
entity = await self._client.get_input_entity(entity)
elif self._entity:
entity = self._entity
else:
raise ValueError('You must provide the entity where the result should be sent to')
if comment_to:
entity, reply_id = await self._client._get_comment_data(entity, comment_to)
else:
reply_id = None if reply_to is None else utils.get_message_id(reply_to)
req = functions.messages.SendInlineBotResultRequest(
peer=entity,
query_id=self._query_id,
id=self.result.id,
silent=silent,
background=background,
clear_draft=clear_draft,
hide_via=hide_via,
reply_to=None if reply_id is None else types.InputReplyToMessage(reply_id)
)
return self._client._get_response_message(
req, await self._client(req), entity)
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.download_media>`.
"""
if self.document or self.photo:
return await self._client.download_media(
self.document or self.photo, *args, **kwargs)

View File

@@ -0,0 +1,83 @@
import time
from .inlineresult import InlineResult
class InlineResults(list):
"""
Custom class that encapsulates :tl:`BotResults` providing
an abstraction to easily access some commonly needed features
(such as clicking one of the results to select it)
Note that this is a list of `InlineResult
<telethon.tl.custom.inlineresult.InlineResult>`
so you can iterate over it or use indices to
access its elements. In addition, it has some
attributes.
Attributes:
result (:tl:`BotResults`):
The original :tl:`BotResults` object.
query_id (`int`):
The random ID that identifies this query.
cache_time (`int`):
For how long the results should be considered
valid. You can call `results_valid` at any
moment to determine if the results are still
valid or not.
users (:tl:`User`):
The users present in this inline query.
gallery (`bool`):
Whether these results should be presented
in a grid (as a gallery of images) or not.
next_offset (`str`, optional):
The string to be used as an offset to get
the next chunk of results, if any.
switch_pm (:tl:`InlineBotSwitchPM`, optional):
If presents, the results should show a button to
switch to a private conversation with the bot using
the text in this object.
"""
def __init__(self, client, original, *, entity=None):
super().__init__(InlineResult(client, x, original.query_id, entity=entity)
for x in original.results)
self.result = original
self.query_id = original.query_id
self.cache_time = original.cache_time
self._valid_until = time.time() + self.cache_time
self.users = original.users
self.gallery = bool(original.gallery)
self.next_offset = original.next_offset
self.switch_pm = original.switch_pm
def results_valid(self):
"""
Returns `True` if the cache time has not expired
yet and the results can still be considered valid.
"""
return time.time() < self._valid_until
def _to_str(self, item_function):
return ('[{}, query_id={}, cache_time={}, users={}, gallery={}, '
'next_offset={}, switch_pm={}]'.format(
', '.join(item_function(x) for x in self),
self.query_id,
self.cache_time,
self.users,
self.gallery,
self.next_offset,
self.switch_pm
))
def __str__(self):
return self._to_str(str)
def __repr__(self):
return self._to_str(repr)

View File

@@ -0,0 +1,9 @@
from ..types import InputFile
class InputSizedFile(InputFile):
"""InputFile class with two extra parameters: md5 (digest) and size"""
def __init__(self, id_, parts, name, md5, size):
super().__init__(id_, parts, name, md5.hexdigest())
self.md5 = md5.digest()
self.size = size

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,151 @@
from .. import types, functions
from ... import password as pwd_mod
from ...errors import BotResponseTimeoutError
try:
import webbrowser
except ModuleNotFoundError:
pass
import sys
import os
class MessageButton:
"""
.. note::
`Message.buttons <telethon.tl.custom.message.Message.buttons>`
are instances of this type. If you want to **define** a reply
markup for e.g. sending messages, refer to `Button
<telethon.tl.custom.button.Button>` instead.
Custom class that encapsulates a message button providing
an abstraction to easily access some commonly needed features
(such as clicking the button itself).
Attributes:
button (:tl:`KeyboardButton`):
The original :tl:`KeyboardButton` object.
"""
def __init__(self, client, original, chat, bot, msg_id):
self.button = original
self._bot = bot
self._chat = chat
self._msg_id = msg_id
self._client = client
@property
def client(self):
"""
Returns the `telethon.client.telegramclient.TelegramClient`
instance that created this instance.
"""
return self._client
@property
def text(self):
"""The text string of the button."""
return self.button.text
@property
def data(self):
"""The `bytes` data for :tl:`KeyboardButtonCallback` objects."""
if isinstance(self.button, types.KeyboardButtonCallback):
return self.button.data
@property
def inline_query(self):
"""The query `str` for :tl:`KeyboardButtonSwitchInline` objects."""
if isinstance(self.button, types.KeyboardButtonSwitchInline):
return self.button.query
@property
def url(self):
"""The url `str` for :tl:`KeyboardButtonUrl` objects."""
if isinstance(self.button, types.KeyboardButtonUrl):
return self.button.url
async def click(self, share_phone=None, share_geo=None, *, password=None):
"""
Emulates the behaviour of clicking this button.
If it's a normal :tl:`KeyboardButton` with text, a message will be
sent, and the sent `Message <telethon.tl.custom.message.Message>` returned.
If it's an inline :tl:`KeyboardButtonCallback` with text and data,
it will be "clicked" and the :tl:`BotCallbackAnswer` returned.
If it's an inline :tl:`KeyboardButtonSwitchInline` button, the
:tl:`StartBotRequest` will be invoked and the resulting updates
returned.
If it's a :tl:`KeyboardButtonUrl`, the URL of the button will
be passed to ``webbrowser.open`` and return `True` on success.
If it's a :tl:`KeyboardButtonRequestPhone`, you must indicate that you
want to ``share_phone=True`` in order to share it. Sharing it is not a
default because it is a privacy concern and could happen accidentally.
You may also use ``share_phone=phone`` to share a specific number, in
which case either `str` or :tl:`InputMediaContact` should be used.
If it's a :tl:`KeyboardButtonRequestGeoLocation`, you must pass a
tuple in ``share_geo=(longitude, latitude)``. Note that Telegram seems
to have some heuristics to determine impossible locations, so changing
this value a lot quickly may not work as expected. You may also pass a
:tl:`InputGeoPoint` if you find the order confusing.
"""
if isinstance(self.button, types.KeyboardButton):
return await self._client.send_message(
self._chat, self.button.text, parse_mode=None)
elif isinstance(self.button, types.KeyboardButtonCallback):
if password is not None:
pwd = await self._client(functions.account.GetPasswordRequest())
password = pwd_mod.compute_check(pwd, password)
req = functions.messages.GetBotCallbackAnswerRequest(
peer=self._chat, msg_id=self._msg_id, data=self.button.data,
password=password
)
try:
return await self._client(req)
except BotResponseTimeoutError:
return None
elif isinstance(self.button, types.KeyboardButtonSwitchInline):
return await self._client(functions.messages.StartBotRequest(
bot=self._bot, peer=self._chat, start_param=self.button.query
))
elif isinstance(self.button, types.KeyboardButtonUrl):
if "webbrowser" in sys.modules:
return webbrowser.open(self.button.url)
elif isinstance(self.button, types.KeyboardButtonGame):
req = functions.messages.GetBotCallbackAnswerRequest(
peer=self._chat, msg_id=self._msg_id, game=True
)
try:
return await self._client(req)
except BotResponseTimeoutError:
return None
elif isinstance(self.button, types.KeyboardButtonRequestPhone):
if not share_phone:
raise ValueError('cannot click on phone buttons unless share_phone=True')
if share_phone == True or isinstance(share_phone, str):
me = await self._client.get_me()
share_phone = types.InputMediaContact(
phone_number=me.phone if share_phone == True else share_phone,
first_name=me.first_name or '',
last_name=me.last_name or '',
vcard=''
)
return await self._client.send_file(self._chat, share_phone)
elif isinstance(self.button, types.KeyboardButtonRequestGeoLocation):
if not share_geo:
raise ValueError('cannot click on geo buttons unless share_geo=(longitude, latitude)')
if isinstance(share_geo, (tuple, list)):
long, lat = share_geo
share_geo = types.InputMediaGeoPoint(types.InputGeoPoint(lat=lat, long=long))
return await self._client.send_file(self._chat, share_geo)

View File

@@ -0,0 +1,138 @@
from .. import types
def _admin_prop(field_name, doc):
"""
Helper method to build properties that return `True` if the user is an
administrator of a normal chat, or otherwise return `True` if the user
has a specific permission being an admin of a channel.
"""
def fget(self):
if not self.is_admin:
return False
if self.is_chat:
return True
return getattr(self.participant.admin_rights, field_name)
return {'fget': fget, 'doc': doc}
class ParticipantPermissions:
"""
Participant permissions information.
The properties in this objects are boolean values indicating whether the
user has the permission or not.
Example
.. code-block:: python
permissions = ...
if permissions.is_banned:
"this user is banned"
elif permissions.is_admin:
"this user is an administrator"
"""
def __init__(self, participant, chat: bool):
self.participant = participant
self.is_chat = chat
@property
def is_admin(self):
"""
Whether the user is an administrator of the chat or not. The creator
also counts as begin an administrator, since they have all permissions.
"""
return self.is_creator or isinstance(self.participant, (
types.ChannelParticipantAdmin,
types.ChatParticipantAdmin
))
@property
def is_creator(self):
"""
Whether the user is the creator of the chat or not.
"""
return isinstance(self.participant, (
types.ChannelParticipantCreator,
types.ChatParticipantCreator
))
@property
def has_default_permissions(self):
"""
Whether the user is a normal user of the chat (not administrator, but
not banned either, and has no restrictions applied).
"""
return isinstance(self.participant, (
types.ChannelParticipant,
types.ChatParticipant,
types.ChannelParticipantSelf
))
@property
def is_banned(self):
"""
Whether the user is banned in the chat.
"""
return isinstance(self.participant, types.ChannelParticipantBanned)
@property
def has_left(self):
"""
Whether the user left the chat.
"""
return isinstance(self.participant, types.ChannelParticipantLeft)
@property
def add_admins(self):
"""
Whether the administrator can add new administrators with the same or
less permissions than them.
"""
if not self.is_admin:
return False
if self.is_chat:
return self.is_creator
return self.participant.admin_rights.add_admins
ban_users = property(**_admin_prop('ban_users', """
Whether the administrator can ban other users or not.
"""))
pin_messages = property(**_admin_prop('pin_messages', """
Whether the administrator can pin messages or not.
"""))
invite_users = property(**_admin_prop('invite_users', """
Whether the administrator can add new users to the chat.
"""))
delete_messages = property(**_admin_prop('delete_messages', """
Whether the administrator can delete messages from other participants.
"""))
edit_messages = property(**_admin_prop('edit_messages', """
Whether the administrator can edit messages.
"""))
post_messages = property(**_admin_prop('post_messages', """
Whether the administrator can post messages in the broadcast channel.
"""))
change_info = property(**_admin_prop('change_info', """
Whether the administrator can change the information about the chat,
such as title or description.
"""))
anonymous = property(**_admin_prop('anonymous', """
Whether the administrator will remain anonymous when sending messages.
"""))
manage_call = property(**_admin_prop('manage_call', """
Whether the user will be able to manage group calls.
"""))

View File

@@ -0,0 +1,119 @@
import asyncio
import base64
import datetime
from .. import types, functions
from ... import events
class QRLogin:
"""
QR login information.
Most of the time, you will present the `url` as a QR code to the user,
and while it's being shown, call `wait`.
"""
def __init__(self, client, ignored_ids):
self._client = client
self._request = functions.auth.ExportLoginTokenRequest(
self._client.api_id, self._client.api_hash, ignored_ids)
self._resp = None
async def recreate(self):
"""
Generates a new token and URL for a new QR code, useful if the code
has expired before it was imported.
"""
self._resp = await self._client(self._request)
@property
def token(self) -> bytes:
"""
The binary data representing the token.
It can be used by a previously-authorized client in a call to
:tl:`auth.importLoginToken` to log the client that originally
requested the QR login.
"""
return self._resp.token
@property
def url(self) -> str:
"""
The ``tg://login`` URI with the token. When opened by a Telegram
application where the user is logged in, it will import the login
token.
If you want to display a QR code to the user, this is the URL that
should be launched when the QR code is scanned (the URL that should
be contained in the QR code image you generate).
Whether you generate the QR code image or not is up to you, and the
library can't do this for you due to the vast ways of generating and
displaying the QR code that exist.
The URL simply consists of `token` base64-encoded.
"""
return 'tg://login?token={}'.format(base64.urlsafe_b64encode(self._resp.token).decode('utf-8').rstrip('='))
@property
def expires(self) -> datetime.datetime:
"""
The `datetime` at which the QR code will expire.
If you want to try again, you will need to call `recreate`.
"""
return self._resp.expires
async def wait(self, timeout: float = None):
"""
Waits for the token to be imported by a previously-authorized client,
either by scanning the QR, launching the URL directly, or calling the
import method.
This method **must** be called before the QR code is scanned, and
must be executing while the QR code is being scanned. Otherwise, the
login will not complete.
Will raise `asyncio.TimeoutError` if the login doesn't complete on
time.
Arguments
timeout (float):
The timeout, in seconds, to wait before giving up. By default
the library will wait until the token expires, which is often
what you want.
Returns
On success, an instance of :tl:`User`. On failure it will raise.
"""
if timeout is None:
timeout = (self._resp.expires - datetime.datetime.now(tz=datetime.timezone.utc)).total_seconds()
event = asyncio.Event()
async def handler(_update):
event.set()
self._client.add_event_handler(handler, events.Raw(types.UpdateLoginToken))
try:
# Will raise timeout error if it doesn't complete quick enough,
# which we want to let propagate
await asyncio.wait_for(event.wait(), timeout=timeout)
finally:
self._client.remove_event_handler(handler)
# We got here without it raising timeout error, so we can proceed
resp = await self._client(self._request)
if isinstance(resp, types.auth.LoginTokenMigrateTo):
await self._client._switch_dc(resp.dc_id)
resp = await self._client(functions.auth.ImportLoginTokenRequest(resp.token))
# resp should now be auth.loginTokenSuccess
if isinstance(resp, types.auth.LoginTokenSuccess):
user = resp.authorization.user
await self._client._on_login(user)
return user
raise TypeError('Login token response was unexpected: {}'.format(resp))

View File

@@ -0,0 +1,102 @@
import abc
from ... import utils
class SenderGetter(abc.ABC):
"""
Helper base class that introduces the `sender`, `input_sender`
and `sender_id` properties and `get_sender` and `get_input_sender`
methods.
"""
def __init__(self, sender_id=None, *, sender=None, input_sender=None):
self._sender_id = sender_id
self._sender = sender
self._input_sender = input_sender
self._client = None
@property
def sender(self):
"""
Returns the :tl:`User` or :tl:`Channel` that sent this object.
It may be `None` if Telegram didn't send the sender.
If you only need the ID, use `sender_id` instead.
If you need to call a method which needs
this chat, use `input_sender` instead.
If you're using `telethon.events`, use `get_sender()` instead.
"""
return self._sender
async def get_sender(self):
"""
Returns `sender`, but will make an API call to find the
sender unless it's already cached.
If you only need the ID, use `sender_id` instead.
If you need to call a method which needs
this sender, use `get_input_sender()` instead.
"""
# ``sender.min`` is present both in :tl:`User` and :tl:`Channel`.
# It's a flag that will be set if only minimal information is
# available (such as display name, but username may be missing),
# in which case we want to force fetch the entire thing because
# the user explicitly called a method. If the user is okay with
# cached information, they may use the property instead.
if (self._sender is None or getattr(self._sender, 'min', None)) \
and await self.get_input_sender():
# self.get_input_sender may refresh in which case the sender may no longer be min
# However it could still incur a cost so the cheap check is done twice instead.
if self._sender is None or getattr(self._sender, 'min', None):
try:
self._sender =\
await self._client.get_entity(self._input_sender)
except ValueError:
await self._refetch_sender()
return self._sender
@property
def input_sender(self):
"""
This :tl:`InputPeer` is the input version of the user/channel who
sent the message. Similarly to `input_chat
<telethon.tl.custom.chatgetter.ChatGetter.input_chat>`, this doesn't
have things like username or similar, but still useful in some cases.
Note that this might not be available if the library can't
find the input chat, or if the message a broadcast on a channel.
"""
if self._input_sender is None and self._sender_id and self._client:
try:
self._input_sender = self._client._mb_entity_cache.get(
utils.resolve_id(self._sender_id)[0])._as_input_peer()
except AttributeError:
pass
return self._input_sender
async def get_input_sender(self):
"""
Returns `input_sender`, but will make an API call to find the
input sender unless it's already cached.
"""
if self.input_sender is None and self._sender_id and self._client:
await self._refetch_sender()
return self._input_sender
@property
def sender_id(self):
"""
Returns the marked sender integer ID, if present.
If there is a sender in the object, `sender_id` will *always* be set,
which is why you should use it instead of `sender.id <sender>`.
"""
return self._sender_id
async def _refetch_sender(self):
"""
Re-fetches sender information through other means.
"""

View File

@@ -0,0 +1,581 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
from . import account, auth, bots, channels, chatlists, contacts, folders, help, langpack, messages, payments, phone, photos, premium, stats, stickers, stories, updates, upload, users
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeInputClientProxy, TypeJSONValue, TypeMessageRange, TypeType, TypeX
class DestroyAuthKeyRequest(TLRequest):
CONSTRUCTOR_ID = 0xd1435160
SUBCLASS_OF_ID = 0x8291e68e
def to_dict(self):
return {
'_': 'DestroyAuthKeyRequest'
}
def _bytes(self):
return b''.join((
b'`QC\xd1',
))
@classmethod
def from_reader(cls, reader):
return cls()
class DestroySessionRequest(TLRequest):
CONSTRUCTOR_ID = 0xe7512126
SUBCLASS_OF_ID = 0xaf0ce7bd
def __init__(self, session_id: int):
"""
:returns DestroySessionRes: Instance of either DestroySessionOk, DestroySessionNone.
"""
self.session_id = session_id
def to_dict(self):
return {
'_': 'DestroySessionRequest',
'session_id': self.session_id
}
def _bytes(self):
return b''.join((
b'&!Q\xe7',
struct.pack('<q', self.session_id),
))
@classmethod
def from_reader(cls, reader):
_session_id = reader.read_long()
return cls(session_id=_session_id)
class GetFutureSaltsRequest(TLRequest):
CONSTRUCTOR_ID = 0xb921bd04
SUBCLASS_OF_ID = 0x1090f517
def __init__(self, num: int):
"""
:returns FutureSalts: Instance of FutureSalts.
"""
self.num = num
def to_dict(self):
return {
'_': 'GetFutureSaltsRequest',
'num': self.num
}
def _bytes(self):
return b''.join((
b'\x04\xbd!\xb9',
struct.pack('<i', self.num),
))
@classmethod
def from_reader(cls, reader):
_num = reader.read_int()
return cls(num=_num)
class InitConnectionRequest(TLRequest):
CONSTRUCTOR_ID = 0xc1cd5ea9
SUBCLASS_OF_ID = 0xb7b2364b
def __init__(self, api_id: int, device_model: str, system_version: str, app_version: str, system_lang_code: str, lang_pack: str, lang_code: str, query: 'TypeX', proxy: Optional['TypeInputClientProxy']=None, params: Optional['TypeJSONValue']=None):
"""
:returns X: This type has no constructors.
"""
self.api_id = api_id
self.device_model = device_model
self.system_version = system_version
self.app_version = app_version
self.system_lang_code = system_lang_code
self.lang_pack = lang_pack
self.lang_code = lang_code
self.query = query
self.proxy = proxy
self.params = params
def to_dict(self):
return {
'_': 'InitConnectionRequest',
'api_id': self.api_id,
'device_model': self.device_model,
'system_version': self.system_version,
'app_version': self.app_version,
'system_lang_code': self.system_lang_code,
'lang_pack': self.lang_pack,
'lang_code': self.lang_code,
'query': self.query.to_dict() if isinstance(self.query, TLObject) else self.query,
'proxy': self.proxy.to_dict() if isinstance(self.proxy, TLObject) else self.proxy,
'params': self.params.to_dict() if isinstance(self.params, TLObject) else self.params
}
def _bytes(self):
return b''.join((
b'\xa9^\xcd\xc1',
struct.pack('<I', (0 if self.proxy is None or self.proxy is False else 1) | (0 if self.params is None or self.params is False else 2)),
struct.pack('<i', self.api_id),
self.serialize_bytes(self.device_model),
self.serialize_bytes(self.system_version),
self.serialize_bytes(self.app_version),
self.serialize_bytes(self.system_lang_code),
self.serialize_bytes(self.lang_pack),
self.serialize_bytes(self.lang_code),
b'' if self.proxy is None or self.proxy is False else (self.proxy._bytes()),
b'' if self.params is None or self.params is False else (self.params._bytes()),
self.query._bytes(),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_api_id = reader.read_int()
_device_model = reader.tgread_string()
_system_version = reader.tgread_string()
_app_version = reader.tgread_string()
_system_lang_code = reader.tgread_string()
_lang_pack = reader.tgread_string()
_lang_code = reader.tgread_string()
if flags & 1:
_proxy = reader.tgread_object()
else:
_proxy = None
if flags & 2:
_params = reader.tgread_object()
else:
_params = None
_query = reader.tgread_object()
return cls(api_id=_api_id, device_model=_device_model, system_version=_system_version, app_version=_app_version, system_lang_code=_system_lang_code, lang_pack=_lang_pack, lang_code=_lang_code, query=_query, proxy=_proxy, params=_params)
class InvokeAfterMsgRequest(TLRequest):
CONSTRUCTOR_ID = 0xcb9f372d
SUBCLASS_OF_ID = 0xb7b2364b
def __init__(self, msg_id: int, query: 'TypeX'):
"""
:returns X: This type has no constructors.
"""
self.msg_id = msg_id
self.query = query
def to_dict(self):
return {
'_': 'InvokeAfterMsgRequest',
'msg_id': self.msg_id,
'query': self.query.to_dict() if isinstance(self.query, TLObject) else self.query
}
def _bytes(self):
return b''.join((
b'-7\x9f\xcb',
struct.pack('<q', self.msg_id),
self.query._bytes(),
))
@classmethod
def from_reader(cls, reader):
_msg_id = reader.read_long()
_query = reader.tgread_object()
return cls(msg_id=_msg_id, query=_query)
class InvokeAfterMsgsRequest(TLRequest):
CONSTRUCTOR_ID = 0x3dc4b4f0
SUBCLASS_OF_ID = 0xb7b2364b
def __init__(self, msg_ids: List[int], query: 'TypeX'):
"""
:returns X: This type has no constructors.
"""
self.msg_ids = msg_ids
self.query = query
def to_dict(self):
return {
'_': 'InvokeAfterMsgsRequest',
'msg_ids': [] if self.msg_ids is None else self.msg_ids[:],
'query': self.query.to_dict() if isinstance(self.query, TLObject) else self.query
}
def _bytes(self):
return b''.join((
b'\xf0\xb4\xc4=',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.msg_ids)),b''.join(struct.pack('<q', x) for x in self.msg_ids),
self.query._bytes(),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_msg_ids = []
for _ in range(reader.read_int()):
_x = reader.read_long()
_msg_ids.append(_x)
_query = reader.tgread_object()
return cls(msg_ids=_msg_ids, query=_query)
class InvokeWithLayerRequest(TLRequest):
CONSTRUCTOR_ID = 0xda9b0d0d
SUBCLASS_OF_ID = 0xb7b2364b
def __init__(self, layer: int, query: 'TypeX'):
"""
:returns X: This type has no constructors.
"""
self.layer = layer
self.query = query
def to_dict(self):
return {
'_': 'InvokeWithLayerRequest',
'layer': self.layer,
'query': self.query.to_dict() if isinstance(self.query, TLObject) else self.query
}
def _bytes(self):
return b''.join((
b'\r\r\x9b\xda',
struct.pack('<i', self.layer),
self.query._bytes(),
))
@classmethod
def from_reader(cls, reader):
_layer = reader.read_int()
_query = reader.tgread_object()
return cls(layer=_layer, query=_query)
class InvokeWithMessagesRangeRequest(TLRequest):
CONSTRUCTOR_ID = 0x365275f2
SUBCLASS_OF_ID = 0xb7b2364b
def __init__(self, range: 'TypeMessageRange', query: 'TypeX'):
"""
:returns X: This type has no constructors.
"""
self.range = range
self.query = query
def to_dict(self):
return {
'_': 'InvokeWithMessagesRangeRequest',
'range': self.range.to_dict() if isinstance(self.range, TLObject) else self.range,
'query': self.query.to_dict() if isinstance(self.query, TLObject) else self.query
}
def _bytes(self):
return b''.join((
b'\xf2uR6',
self.range._bytes(),
self.query._bytes(),
))
@classmethod
def from_reader(cls, reader):
_range = reader.tgread_object()
_query = reader.tgread_object()
return cls(range=_range, query=_query)
class InvokeWithTakeoutRequest(TLRequest):
CONSTRUCTOR_ID = 0xaca9fd2e
SUBCLASS_OF_ID = 0xb7b2364b
def __init__(self, takeout_id: int, query: 'TypeX'):
"""
:returns X: This type has no constructors.
"""
self.takeout_id = takeout_id
self.query = query
def to_dict(self):
return {
'_': 'InvokeWithTakeoutRequest',
'takeout_id': self.takeout_id,
'query': self.query.to_dict() if isinstance(self.query, TLObject) else self.query
}
def _bytes(self):
return b''.join((
b'.\xfd\xa9\xac',
struct.pack('<q', self.takeout_id),
self.query._bytes(),
))
@classmethod
def from_reader(cls, reader):
_takeout_id = reader.read_long()
_query = reader.tgread_object()
return cls(takeout_id=_takeout_id, query=_query)
class InvokeWithoutUpdatesRequest(TLRequest):
CONSTRUCTOR_ID = 0xbf9459b7
SUBCLASS_OF_ID = 0xb7b2364b
def __init__(self, query: 'TypeX'):
"""
:returns X: This type has no constructors.
"""
self.query = query
def to_dict(self):
return {
'_': 'InvokeWithoutUpdatesRequest',
'query': self.query.to_dict() if isinstance(self.query, TLObject) else self.query
}
def _bytes(self):
return b''.join((
b'\xb7Y\x94\xbf',
self.query._bytes(),
))
@classmethod
def from_reader(cls, reader):
_query = reader.tgread_object()
return cls(query=_query)
class PingRequest(TLRequest):
CONSTRUCTOR_ID = 0x7abe77ec
SUBCLASS_OF_ID = 0x816aee71
def __init__(self, ping_id: int):
"""
:returns Pong: Instance of Pong.
"""
self.ping_id = ping_id
def to_dict(self):
return {
'_': 'PingRequest',
'ping_id': self.ping_id
}
def _bytes(self):
return b''.join((
b'\xecw\xbez',
struct.pack('<q', self.ping_id),
))
@classmethod
def from_reader(cls, reader):
_ping_id = reader.read_long()
return cls(ping_id=_ping_id)
class PingDelayDisconnectRequest(TLRequest):
CONSTRUCTOR_ID = 0xf3427b8c
SUBCLASS_OF_ID = 0x816aee71
def __init__(self, ping_id: int, disconnect_delay: int):
"""
:returns Pong: Instance of Pong.
"""
self.ping_id = ping_id
self.disconnect_delay = disconnect_delay
def to_dict(self):
return {
'_': 'PingDelayDisconnectRequest',
'ping_id': self.ping_id,
'disconnect_delay': self.disconnect_delay
}
def _bytes(self):
return b''.join((
b'\x8c{B\xf3',
struct.pack('<q', self.ping_id),
struct.pack('<i', self.disconnect_delay),
))
@classmethod
def from_reader(cls, reader):
_ping_id = reader.read_long()
_disconnect_delay = reader.read_int()
return cls(ping_id=_ping_id, disconnect_delay=_disconnect_delay)
class ReqDHParamsRequest(TLRequest):
CONSTRUCTOR_ID = 0xd712e4be
SUBCLASS_OF_ID = 0xa6188d9e
def __init__(self, nonce: int, server_nonce: int, p: bytes, q: bytes, public_key_fingerprint: int, encrypted_data: bytes):
"""
:returns Server_DH_Params: Instance of either ServerDHParamsFail, ServerDHParamsOk.
"""
self.nonce = nonce
self.server_nonce = server_nonce
self.p = p
self.q = q
self.public_key_fingerprint = public_key_fingerprint
self.encrypted_data = encrypted_data
def to_dict(self):
return {
'_': 'ReqDHParamsRequest',
'nonce': self.nonce,
'server_nonce': self.server_nonce,
'p': self.p,
'q': self.q,
'public_key_fingerprint': self.public_key_fingerprint,
'encrypted_data': self.encrypted_data
}
def _bytes(self):
return b''.join((
b'\xbe\xe4\x12\xd7',
self.nonce.to_bytes(16, 'little', signed=True),
self.server_nonce.to_bytes(16, 'little', signed=True),
self.serialize_bytes(self.p),
self.serialize_bytes(self.q),
struct.pack('<q', self.public_key_fingerprint),
self.serialize_bytes(self.encrypted_data),
))
@classmethod
def from_reader(cls, reader):
_nonce = reader.read_large_int(bits=128)
_server_nonce = reader.read_large_int(bits=128)
_p = reader.tgread_bytes()
_q = reader.tgread_bytes()
_public_key_fingerprint = reader.read_long()
_encrypted_data = reader.tgread_bytes()
return cls(nonce=_nonce, server_nonce=_server_nonce, p=_p, q=_q, public_key_fingerprint=_public_key_fingerprint, encrypted_data=_encrypted_data)
class ReqPqRequest(TLRequest):
CONSTRUCTOR_ID = 0x60469778
SUBCLASS_OF_ID = 0x786986b8
def __init__(self, nonce: int):
"""
:returns ResPQ: Instance of ResPQ.
"""
self.nonce = nonce
def to_dict(self):
return {
'_': 'ReqPqRequest',
'nonce': self.nonce
}
def _bytes(self):
return b''.join((
b'x\x97F`',
self.nonce.to_bytes(16, 'little', signed=True),
))
@classmethod
def from_reader(cls, reader):
_nonce = reader.read_large_int(bits=128)
return cls(nonce=_nonce)
class ReqPqMultiRequest(TLRequest):
CONSTRUCTOR_ID = 0xbe7e8ef1
SUBCLASS_OF_ID = 0x786986b8
def __init__(self, nonce: int):
"""
:returns ResPQ: Instance of ResPQ.
"""
self.nonce = nonce
def to_dict(self):
return {
'_': 'ReqPqMultiRequest',
'nonce': self.nonce
}
def _bytes(self):
return b''.join((
b'\xf1\x8e~\xbe',
self.nonce.to_bytes(16, 'little', signed=True),
))
@classmethod
def from_reader(cls, reader):
_nonce = reader.read_large_int(bits=128)
return cls(nonce=_nonce)
class RpcDropAnswerRequest(TLRequest):
CONSTRUCTOR_ID = 0x58e4a740
SUBCLASS_OF_ID = 0x4bca7570
def __init__(self, req_msg_id: int):
"""
:returns RpcDropAnswer: Instance of either RpcAnswerUnknown, RpcAnswerDroppedRunning, RpcAnswerDropped.
"""
self.req_msg_id = req_msg_id
def to_dict(self):
return {
'_': 'RpcDropAnswerRequest',
'req_msg_id': self.req_msg_id
}
def _bytes(self):
return b''.join((
b'@\xa7\xe4X',
struct.pack('<q', self.req_msg_id),
))
@classmethod
def from_reader(cls, reader):
_req_msg_id = reader.read_long()
return cls(req_msg_id=_req_msg_id)
class SetClientDHParamsRequest(TLRequest):
CONSTRUCTOR_ID = 0xf5045f1f
SUBCLASS_OF_ID = 0x55dd6cdb
def __init__(self, nonce: int, server_nonce: int, encrypted_data: bytes):
"""
:returns Set_client_DH_params_answer: Instance of either DhGenOk, DhGenRetry, DhGenFail.
"""
self.nonce = nonce
self.server_nonce = server_nonce
self.encrypted_data = encrypted_data
def to_dict(self):
return {
'_': 'SetClientDHParamsRequest',
'nonce': self.nonce,
'server_nonce': self.server_nonce,
'encrypted_data': self.encrypted_data
}
def _bytes(self):
return b''.join((
b'\x1f_\x04\xf5',
self.nonce.to_bytes(16, 'little', signed=True),
self.server_nonce.to_bytes(16, 'little', signed=True),
self.serialize_bytes(self.encrypted_data),
))
@classmethod
def from_reader(cls, reader):
_nonce = reader.read_large_int(bits=128)
_server_nonce = reader.read_large_int(bits=128)
_encrypted_data = reader.tgread_bytes()
return cls(nonce=_nonce, server_nonce=_server_nonce, encrypted_data=_encrypted_data)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,749 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeCodeSettings, TypeEmailVerification, TypeInputCheckPasswordSRP
from ...tl.types.account import TypePasswordInputSettings
class AcceptLoginTokenRequest(TLRequest):
CONSTRUCTOR_ID = 0xe894ad4d
SUBCLASS_OF_ID = 0xc913c01a
def __init__(self, token: bytes):
"""
:returns Authorization: Instance of Authorization.
"""
self.token = token
def to_dict(self):
return {
'_': 'AcceptLoginTokenRequest',
'token': self.token
}
def _bytes(self):
return b''.join((
b'M\xad\x94\xe8',
self.serialize_bytes(self.token),
))
@classmethod
def from_reader(cls, reader):
_token = reader.tgread_bytes()
return cls(token=_token)
class BindTempAuthKeyRequest(TLRequest):
CONSTRUCTOR_ID = 0xcdd42a05
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, perm_auth_key_id: int, nonce: int, expires_at: Optional[datetime], encrypted_message: bytes):
"""
:returns Bool: This type has no constructors.
"""
self.perm_auth_key_id = perm_auth_key_id
self.nonce = nonce
self.expires_at = expires_at
self.encrypted_message = encrypted_message
def to_dict(self):
return {
'_': 'BindTempAuthKeyRequest',
'perm_auth_key_id': self.perm_auth_key_id,
'nonce': self.nonce,
'expires_at': self.expires_at,
'encrypted_message': self.encrypted_message
}
def _bytes(self):
return b''.join((
b'\x05*\xd4\xcd',
struct.pack('<q', self.perm_auth_key_id),
struct.pack('<q', self.nonce),
self.serialize_datetime(self.expires_at),
self.serialize_bytes(self.encrypted_message),
))
@classmethod
def from_reader(cls, reader):
_perm_auth_key_id = reader.read_long()
_nonce = reader.read_long()
_expires_at = reader.tgread_date()
_encrypted_message = reader.tgread_bytes()
return cls(perm_auth_key_id=_perm_auth_key_id, nonce=_nonce, expires_at=_expires_at, encrypted_message=_encrypted_message)
class CancelCodeRequest(TLRequest):
CONSTRUCTOR_ID = 0x1f040578
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, phone_number: str, phone_code_hash: str):
"""
:returns Bool: This type has no constructors.
"""
self.phone_number = phone_number
self.phone_code_hash = phone_code_hash
def to_dict(self):
return {
'_': 'CancelCodeRequest',
'phone_number': self.phone_number,
'phone_code_hash': self.phone_code_hash
}
def _bytes(self):
return b''.join((
b'x\x05\x04\x1f',
self.serialize_bytes(self.phone_number),
self.serialize_bytes(self.phone_code_hash),
))
@classmethod
def from_reader(cls, reader):
_phone_number = reader.tgread_string()
_phone_code_hash = reader.tgread_string()
return cls(phone_number=_phone_number, phone_code_hash=_phone_code_hash)
class CheckPasswordRequest(TLRequest):
CONSTRUCTOR_ID = 0xd18b4d16
SUBCLASS_OF_ID = 0xb9e04e39
def __init__(self, password: 'TypeInputCheckPasswordSRP'):
"""
:returns auth.Authorization: Instance of either Authorization, AuthorizationSignUpRequired.
"""
self.password = password
def to_dict(self):
return {
'_': 'CheckPasswordRequest',
'password': self.password.to_dict() if isinstance(self.password, TLObject) else self.password
}
def _bytes(self):
return b''.join((
b'\x16M\x8b\xd1',
self.password._bytes(),
))
@classmethod
def from_reader(cls, reader):
_password = reader.tgread_object()
return cls(password=_password)
class CheckRecoveryPasswordRequest(TLRequest):
CONSTRUCTOR_ID = 0xd36bf79
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, code: str):
"""
:returns Bool: This type has no constructors.
"""
self.code = code
def to_dict(self):
return {
'_': 'CheckRecoveryPasswordRequest',
'code': self.code
}
def _bytes(self):
return b''.join((
b'y\xbf6\r',
self.serialize_bytes(self.code),
))
@classmethod
def from_reader(cls, reader):
_code = reader.tgread_string()
return cls(code=_code)
class DropTempAuthKeysRequest(TLRequest):
CONSTRUCTOR_ID = 0x8e48a188
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, except_auth_keys: List[int]):
"""
:returns Bool: This type has no constructors.
"""
self.except_auth_keys = except_auth_keys
def to_dict(self):
return {
'_': 'DropTempAuthKeysRequest',
'except_auth_keys': [] if self.except_auth_keys is None else self.except_auth_keys[:]
}
def _bytes(self):
return b''.join((
b'\x88\xa1H\x8e',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.except_auth_keys)),b''.join(struct.pack('<q', x) for x in self.except_auth_keys),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_except_auth_keys = []
for _ in range(reader.read_int()):
_x = reader.read_long()
_except_auth_keys.append(_x)
return cls(except_auth_keys=_except_auth_keys)
class ExportAuthorizationRequest(TLRequest):
CONSTRUCTOR_ID = 0xe5bfffcd
SUBCLASS_OF_ID = 0x5fd1ec51
def __init__(self, dc_id: int):
"""
:returns auth.ExportedAuthorization: Instance of ExportedAuthorization.
"""
self.dc_id = dc_id
def to_dict(self):
return {
'_': 'ExportAuthorizationRequest',
'dc_id': self.dc_id
}
def _bytes(self):
return b''.join((
b'\xcd\xff\xbf\xe5',
struct.pack('<i', self.dc_id),
))
@classmethod
def from_reader(cls, reader):
_dc_id = reader.read_int()
return cls(dc_id=_dc_id)
class ExportLoginTokenRequest(TLRequest):
CONSTRUCTOR_ID = 0xb7e085fe
SUBCLASS_OF_ID = 0x6b55f636
def __init__(self, api_id: int, api_hash: str, except_ids: List[int]):
"""
:returns auth.LoginToken: Instance of either LoginToken, LoginTokenMigrateTo, LoginTokenSuccess.
"""
self.api_id = api_id
self.api_hash = api_hash
self.except_ids = except_ids
def to_dict(self):
return {
'_': 'ExportLoginTokenRequest',
'api_id': self.api_id,
'api_hash': self.api_hash,
'except_ids': [] if self.except_ids is None else self.except_ids[:]
}
def _bytes(self):
return b''.join((
b'\xfe\x85\xe0\xb7',
struct.pack('<i', self.api_id),
self.serialize_bytes(self.api_hash),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.except_ids)),b''.join(struct.pack('<q', x) for x in self.except_ids),
))
@classmethod
def from_reader(cls, reader):
_api_id = reader.read_int()
_api_hash = reader.tgread_string()
reader.read_int()
_except_ids = []
for _ in range(reader.read_int()):
_x = reader.read_long()
_except_ids.append(_x)
return cls(api_id=_api_id, api_hash=_api_hash, except_ids=_except_ids)
class ImportAuthorizationRequest(TLRequest):
CONSTRUCTOR_ID = 0xa57a7dad
SUBCLASS_OF_ID = 0xb9e04e39
def __init__(self, id: int, bytes: bytes):
"""
:returns auth.Authorization: Instance of either Authorization, AuthorizationSignUpRequired.
"""
self.id = id
self.bytes = bytes
def to_dict(self):
return {
'_': 'ImportAuthorizationRequest',
'id': self.id,
'bytes': self.bytes
}
def _bytes(self):
return b''.join((
b'\xad}z\xa5',
struct.pack('<q', self.id),
self.serialize_bytes(self.bytes),
))
@classmethod
def from_reader(cls, reader):
_id = reader.read_long()
_bytes = reader.tgread_bytes()
return cls(id=_id, bytes=_bytes)
class ImportBotAuthorizationRequest(TLRequest):
CONSTRUCTOR_ID = 0x67a3ff2c
SUBCLASS_OF_ID = 0xb9e04e39
def __init__(self, flags: int, api_id: int, api_hash: str, bot_auth_token: str):
"""
:returns auth.Authorization: Instance of either Authorization, AuthorizationSignUpRequired.
"""
self.flags = flags
self.api_id = api_id
self.api_hash = api_hash
self.bot_auth_token = bot_auth_token
def to_dict(self):
return {
'_': 'ImportBotAuthorizationRequest',
'flags': self.flags,
'api_id': self.api_id,
'api_hash': self.api_hash,
'bot_auth_token': self.bot_auth_token
}
def _bytes(self):
return b''.join((
b',\xff\xa3g',
struct.pack('<i', self.flags),
struct.pack('<i', self.api_id),
self.serialize_bytes(self.api_hash),
self.serialize_bytes(self.bot_auth_token),
))
@classmethod
def from_reader(cls, reader):
_flags = reader.read_int()
_api_id = reader.read_int()
_api_hash = reader.tgread_string()
_bot_auth_token = reader.tgread_string()
return cls(flags=_flags, api_id=_api_id, api_hash=_api_hash, bot_auth_token=_bot_auth_token)
class ImportLoginTokenRequest(TLRequest):
CONSTRUCTOR_ID = 0x95ac5ce4
SUBCLASS_OF_ID = 0x6b55f636
def __init__(self, token: bytes):
"""
:returns auth.LoginToken: Instance of either LoginToken, LoginTokenMigrateTo, LoginTokenSuccess.
"""
self.token = token
def to_dict(self):
return {
'_': 'ImportLoginTokenRequest',
'token': self.token
}
def _bytes(self):
return b''.join((
b'\xe4\\\xac\x95',
self.serialize_bytes(self.token),
))
@classmethod
def from_reader(cls, reader):
_token = reader.tgread_bytes()
return cls(token=_token)
class ImportWebTokenAuthorizationRequest(TLRequest):
CONSTRUCTOR_ID = 0x2db873a9
SUBCLASS_OF_ID = 0xb9e04e39
def __init__(self, api_id: int, api_hash: str, web_auth_token: str):
"""
:returns auth.Authorization: Instance of either Authorization, AuthorizationSignUpRequired.
"""
self.api_id = api_id
self.api_hash = api_hash
self.web_auth_token = web_auth_token
def to_dict(self):
return {
'_': 'ImportWebTokenAuthorizationRequest',
'api_id': self.api_id,
'api_hash': self.api_hash,
'web_auth_token': self.web_auth_token
}
def _bytes(self):
return b''.join((
b'\xa9s\xb8-',
struct.pack('<i', self.api_id),
self.serialize_bytes(self.api_hash),
self.serialize_bytes(self.web_auth_token),
))
@classmethod
def from_reader(cls, reader):
_api_id = reader.read_int()
_api_hash = reader.tgread_string()
_web_auth_token = reader.tgread_string()
return cls(api_id=_api_id, api_hash=_api_hash, web_auth_token=_web_auth_token)
class LogOutRequest(TLRequest):
CONSTRUCTOR_ID = 0x3e72ba19
SUBCLASS_OF_ID = 0xa804315
def to_dict(self):
return {
'_': 'LogOutRequest'
}
def _bytes(self):
return b''.join((
b'\x19\xbar>',
))
@classmethod
def from_reader(cls, reader):
return cls()
class RecoverPasswordRequest(TLRequest):
CONSTRUCTOR_ID = 0x37096c70
SUBCLASS_OF_ID = 0xb9e04e39
def __init__(self, code: str, new_settings: Optional['TypePasswordInputSettings']=None):
"""
:returns auth.Authorization: Instance of either Authorization, AuthorizationSignUpRequired.
"""
self.code = code
self.new_settings = new_settings
def to_dict(self):
return {
'_': 'RecoverPasswordRequest',
'code': self.code,
'new_settings': self.new_settings.to_dict() if isinstance(self.new_settings, TLObject) else self.new_settings
}
def _bytes(self):
return b''.join((
b'pl\t7',
struct.pack('<I', (0 if self.new_settings is None or self.new_settings is False else 1)),
self.serialize_bytes(self.code),
b'' if self.new_settings is None or self.new_settings is False else (self.new_settings._bytes()),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_code = reader.tgread_string()
if flags & 1:
_new_settings = reader.tgread_object()
else:
_new_settings = None
return cls(code=_code, new_settings=_new_settings)
class RequestFirebaseSmsRequest(TLRequest):
CONSTRUCTOR_ID = 0x89464b50
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, phone_number: str, phone_code_hash: str, safety_net_token: Optional[str]=None, ios_push_secret: Optional[str]=None):
"""
:returns Bool: This type has no constructors.
"""
self.phone_number = phone_number
self.phone_code_hash = phone_code_hash
self.safety_net_token = safety_net_token
self.ios_push_secret = ios_push_secret
def to_dict(self):
return {
'_': 'RequestFirebaseSmsRequest',
'phone_number': self.phone_number,
'phone_code_hash': self.phone_code_hash,
'safety_net_token': self.safety_net_token,
'ios_push_secret': self.ios_push_secret
}
def _bytes(self):
return b''.join((
b'PKF\x89',
struct.pack('<I', (0 if self.safety_net_token is None or self.safety_net_token is False else 1) | (0 if self.ios_push_secret is None or self.ios_push_secret is False else 2)),
self.serialize_bytes(self.phone_number),
self.serialize_bytes(self.phone_code_hash),
b'' if self.safety_net_token is None or self.safety_net_token is False else (self.serialize_bytes(self.safety_net_token)),
b'' if self.ios_push_secret is None or self.ios_push_secret is False else (self.serialize_bytes(self.ios_push_secret)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_phone_number = reader.tgread_string()
_phone_code_hash = reader.tgread_string()
if flags & 1:
_safety_net_token = reader.tgread_string()
else:
_safety_net_token = None
if flags & 2:
_ios_push_secret = reader.tgread_string()
else:
_ios_push_secret = None
return cls(phone_number=_phone_number, phone_code_hash=_phone_code_hash, safety_net_token=_safety_net_token, ios_push_secret=_ios_push_secret)
class RequestPasswordRecoveryRequest(TLRequest):
CONSTRUCTOR_ID = 0xd897bc66
SUBCLASS_OF_ID = 0xfa72d43a
def to_dict(self):
return {
'_': 'RequestPasswordRecoveryRequest'
}
def _bytes(self):
return b''.join((
b'f\xbc\x97\xd8',
))
@classmethod
def from_reader(cls, reader):
return cls()
class ResendCodeRequest(TLRequest):
CONSTRUCTOR_ID = 0x3ef1a9bf
SUBCLASS_OF_ID = 0x6ce87081
def __init__(self, phone_number: str, phone_code_hash: str):
"""
:returns auth.SentCode: Instance of either SentCode, SentCodeSuccess.
"""
self.phone_number = phone_number
self.phone_code_hash = phone_code_hash
def to_dict(self):
return {
'_': 'ResendCodeRequest',
'phone_number': self.phone_number,
'phone_code_hash': self.phone_code_hash
}
def _bytes(self):
return b''.join((
b'\xbf\xa9\xf1>',
self.serialize_bytes(self.phone_number),
self.serialize_bytes(self.phone_code_hash),
))
@classmethod
def from_reader(cls, reader):
_phone_number = reader.tgread_string()
_phone_code_hash = reader.tgread_string()
return cls(phone_number=_phone_number, phone_code_hash=_phone_code_hash)
class ResetAuthorizationsRequest(TLRequest):
CONSTRUCTOR_ID = 0x9fab0d1a
SUBCLASS_OF_ID = 0xf5b399ac
def to_dict(self):
return {
'_': 'ResetAuthorizationsRequest'
}
def _bytes(self):
return b''.join((
b'\x1a\r\xab\x9f',
))
@classmethod
def from_reader(cls, reader):
return cls()
class ResetLoginEmailRequest(TLRequest):
CONSTRUCTOR_ID = 0x7e960193
SUBCLASS_OF_ID = 0x6ce87081
def __init__(self, phone_number: str, phone_code_hash: str):
"""
:returns auth.SentCode: Instance of either SentCode, SentCodeSuccess.
"""
self.phone_number = phone_number
self.phone_code_hash = phone_code_hash
def to_dict(self):
return {
'_': 'ResetLoginEmailRequest',
'phone_number': self.phone_number,
'phone_code_hash': self.phone_code_hash
}
def _bytes(self):
return b''.join((
b'\x93\x01\x96~',
self.serialize_bytes(self.phone_number),
self.serialize_bytes(self.phone_code_hash),
))
@classmethod
def from_reader(cls, reader):
_phone_number = reader.tgread_string()
_phone_code_hash = reader.tgread_string()
return cls(phone_number=_phone_number, phone_code_hash=_phone_code_hash)
class SendCodeRequest(TLRequest):
CONSTRUCTOR_ID = 0xa677244f
SUBCLASS_OF_ID = 0x6ce87081
def __init__(self, phone_number: str, api_id: int, api_hash: str, settings: 'TypeCodeSettings'):
"""
:returns auth.SentCode: Instance of either SentCode, SentCodeSuccess.
"""
self.phone_number = phone_number
self.api_id = api_id
self.api_hash = api_hash
self.settings = settings
def to_dict(self):
return {
'_': 'SendCodeRequest',
'phone_number': self.phone_number,
'api_id': self.api_id,
'api_hash': self.api_hash,
'settings': self.settings.to_dict() if isinstance(self.settings, TLObject) else self.settings
}
def _bytes(self):
return b''.join((
b'O$w\xa6',
self.serialize_bytes(self.phone_number),
struct.pack('<i', self.api_id),
self.serialize_bytes(self.api_hash),
self.settings._bytes(),
))
@classmethod
def from_reader(cls, reader):
_phone_number = reader.tgread_string()
_api_id = reader.read_int()
_api_hash = reader.tgread_string()
_settings = reader.tgread_object()
return cls(phone_number=_phone_number, api_id=_api_id, api_hash=_api_hash, settings=_settings)
class SignInRequest(TLRequest):
CONSTRUCTOR_ID = 0x8d52a951
SUBCLASS_OF_ID = 0xb9e04e39
def __init__(self, phone_number: str, phone_code_hash: str, phone_code: Optional[str]=None, email_verification: Optional['TypeEmailVerification']=None):
"""
:returns auth.Authorization: Instance of either Authorization, AuthorizationSignUpRequired.
"""
self.phone_number = phone_number
self.phone_code_hash = phone_code_hash
self.phone_code = phone_code
self.email_verification = email_verification
def to_dict(self):
return {
'_': 'SignInRequest',
'phone_number': self.phone_number,
'phone_code_hash': self.phone_code_hash,
'phone_code': self.phone_code,
'email_verification': self.email_verification.to_dict() if isinstance(self.email_verification, TLObject) else self.email_verification
}
def _bytes(self):
return b''.join((
b'Q\xa9R\x8d',
struct.pack('<I', (0 if self.phone_code is None or self.phone_code is False else 1) | (0 if self.email_verification is None or self.email_verification is False else 2)),
self.serialize_bytes(self.phone_number),
self.serialize_bytes(self.phone_code_hash),
b'' if self.phone_code is None or self.phone_code is False else (self.serialize_bytes(self.phone_code)),
b'' if self.email_verification is None or self.email_verification is False else (self.email_verification._bytes()),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_phone_number = reader.tgread_string()
_phone_code_hash = reader.tgread_string()
if flags & 1:
_phone_code = reader.tgread_string()
else:
_phone_code = None
if flags & 2:
_email_verification = reader.tgread_object()
else:
_email_verification = None
return cls(phone_number=_phone_number, phone_code_hash=_phone_code_hash, phone_code=_phone_code, email_verification=_email_verification)
class SignUpRequest(TLRequest):
CONSTRUCTOR_ID = 0xaac7b717
SUBCLASS_OF_ID = 0xb9e04e39
def __init__(self, phone_number: str, phone_code_hash: str, first_name: str, last_name: str, no_joined_notifications: Optional[bool]=None):
"""
:returns auth.Authorization: Instance of either Authorization, AuthorizationSignUpRequired.
"""
self.phone_number = phone_number
self.phone_code_hash = phone_code_hash
self.first_name = first_name
self.last_name = last_name
self.no_joined_notifications = no_joined_notifications
def to_dict(self):
return {
'_': 'SignUpRequest',
'phone_number': self.phone_number,
'phone_code_hash': self.phone_code_hash,
'first_name': self.first_name,
'last_name': self.last_name,
'no_joined_notifications': self.no_joined_notifications
}
def _bytes(self):
return b''.join((
b'\x17\xb7\xc7\xaa',
struct.pack('<I', (0 if self.no_joined_notifications is None or self.no_joined_notifications is False else 1)),
self.serialize_bytes(self.phone_number),
self.serialize_bytes(self.phone_code_hash),
self.serialize_bytes(self.first_name),
self.serialize_bytes(self.last_name),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_no_joined_notifications = bool(flags & 1)
_phone_number = reader.tgread_string()
_phone_code_hash = reader.tgread_string()
_first_name = reader.tgread_string()
_last_name = reader.tgread_string()
return cls(phone_number=_phone_number, phone_code_hash=_phone_code_hash, first_name=_first_name, last_name=_last_name, no_joined_notifications=_no_joined_notifications)

View File

@@ -0,0 +1,587 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeBotCommand, TypeBotCommandScope, TypeBotMenuButton, TypeChatAdminRights, TypeDataJSON, TypeInputUser
class AllowSendMessageRequest(TLRequest):
CONSTRUCTOR_ID = 0xf132e3ef
SUBCLASS_OF_ID = 0x8af52aac
def __init__(self, bot: 'TypeInputUser'):
"""
:returns Updates: Instance of either UpdatesTooLong, UpdateShortMessage, UpdateShortChatMessage, UpdateShort, UpdatesCombined, Updates, UpdateShortSentMessage.
"""
self.bot = bot
async def resolve(self, client, utils):
self.bot = utils.get_input_user(await client.get_input_entity(self.bot))
def to_dict(self):
return {
'_': 'AllowSendMessageRequest',
'bot': self.bot.to_dict() if isinstance(self.bot, TLObject) else self.bot
}
def _bytes(self):
return b''.join((
b'\xef\xe32\xf1',
self.bot._bytes(),
))
@classmethod
def from_reader(cls, reader):
_bot = reader.tgread_object()
return cls(bot=_bot)
class AnswerWebhookJSONQueryRequest(TLRequest):
CONSTRUCTOR_ID = 0xe6213f4d
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, query_id: int, data: 'TypeDataJSON'):
"""
:returns Bool: This type has no constructors.
"""
self.query_id = query_id
self.data = data
def to_dict(self):
return {
'_': 'AnswerWebhookJSONQueryRequest',
'query_id': self.query_id,
'data': self.data.to_dict() if isinstance(self.data, TLObject) else self.data
}
def _bytes(self):
return b''.join((
b'M?!\xe6',
struct.pack('<q', self.query_id),
self.data._bytes(),
))
@classmethod
def from_reader(cls, reader):
_query_id = reader.read_long()
_data = reader.tgread_object()
return cls(query_id=_query_id, data=_data)
class CanSendMessageRequest(TLRequest):
CONSTRUCTOR_ID = 0x1359f4e6
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, bot: 'TypeInputUser'):
"""
:returns Bool: This type has no constructors.
"""
self.bot = bot
async def resolve(self, client, utils):
self.bot = utils.get_input_user(await client.get_input_entity(self.bot))
def to_dict(self):
return {
'_': 'CanSendMessageRequest',
'bot': self.bot.to_dict() if isinstance(self.bot, TLObject) else self.bot
}
def _bytes(self):
return b''.join((
b'\xe6\xf4Y\x13',
self.bot._bytes(),
))
@classmethod
def from_reader(cls, reader):
_bot = reader.tgread_object()
return cls(bot=_bot)
class GetBotCommandsRequest(TLRequest):
CONSTRUCTOR_ID = 0xe34c0dd6
SUBCLASS_OF_ID = 0xfae91529
def __init__(self, scope: 'TypeBotCommandScope', lang_code: str):
"""
:returns Vector<BotCommand>: This type has no constructors.
"""
self.scope = scope
self.lang_code = lang_code
def to_dict(self):
return {
'_': 'GetBotCommandsRequest',
'scope': self.scope.to_dict() if isinstance(self.scope, TLObject) else self.scope,
'lang_code': self.lang_code
}
def _bytes(self):
return b''.join((
b'\xd6\rL\xe3',
self.scope._bytes(),
self.serialize_bytes(self.lang_code),
))
@classmethod
def from_reader(cls, reader):
_scope = reader.tgread_object()
_lang_code = reader.tgread_string()
return cls(scope=_scope, lang_code=_lang_code)
class GetBotInfoRequest(TLRequest):
CONSTRUCTOR_ID = 0xdcd914fd
SUBCLASS_OF_ID = 0xca7b2235
def __init__(self, lang_code: str, bot: Optional['TypeInputUser']=None):
"""
:returns bots.BotInfo: Instance of BotInfo.
"""
self.lang_code = lang_code
self.bot = bot
async def resolve(self, client, utils):
if self.bot:
self.bot = utils.get_input_user(await client.get_input_entity(self.bot))
def to_dict(self):
return {
'_': 'GetBotInfoRequest',
'lang_code': self.lang_code,
'bot': self.bot.to_dict() if isinstance(self.bot, TLObject) else self.bot
}
def _bytes(self):
return b''.join((
b'\xfd\x14\xd9\xdc',
struct.pack('<I', (0 if self.bot is None or self.bot is False else 1)),
b'' if self.bot is None or self.bot is False else (self.bot._bytes()),
self.serialize_bytes(self.lang_code),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
if flags & 1:
_bot = reader.tgread_object()
else:
_bot = None
_lang_code = reader.tgread_string()
return cls(lang_code=_lang_code, bot=_bot)
class GetBotMenuButtonRequest(TLRequest):
CONSTRUCTOR_ID = 0x9c60eb28
SUBCLASS_OF_ID = 0x4c71bd3c
def __init__(self, user_id: 'TypeInputUser'):
"""
:returns BotMenuButton: Instance of either BotMenuButtonDefault, BotMenuButtonCommands, BotMenuButton.
"""
self.user_id = user_id
async def resolve(self, client, utils):
self.user_id = utils.get_input_user(await client.get_input_entity(self.user_id))
def to_dict(self):
return {
'_': 'GetBotMenuButtonRequest',
'user_id': self.user_id.to_dict() if isinstance(self.user_id, TLObject) else self.user_id
}
def _bytes(self):
return b''.join((
b'(\xeb`\x9c',
self.user_id._bytes(),
))
@classmethod
def from_reader(cls, reader):
_user_id = reader.tgread_object()
return cls(user_id=_user_id)
class InvokeWebViewCustomMethodRequest(TLRequest):
CONSTRUCTOR_ID = 0x87fc5e7
SUBCLASS_OF_ID = 0xad0352e8
def __init__(self, bot: 'TypeInputUser', custom_method: str, params: 'TypeDataJSON'):
"""
:returns DataJSON: Instance of DataJSON.
"""
self.bot = bot
self.custom_method = custom_method
self.params = params
async def resolve(self, client, utils):
self.bot = utils.get_input_user(await client.get_input_entity(self.bot))
def to_dict(self):
return {
'_': 'InvokeWebViewCustomMethodRequest',
'bot': self.bot.to_dict() if isinstance(self.bot, TLObject) else self.bot,
'custom_method': self.custom_method,
'params': self.params.to_dict() if isinstance(self.params, TLObject) else self.params
}
def _bytes(self):
return b''.join((
b'\xe7\xc5\x7f\x08',
self.bot._bytes(),
self.serialize_bytes(self.custom_method),
self.params._bytes(),
))
@classmethod
def from_reader(cls, reader):
_bot = reader.tgread_object()
_custom_method = reader.tgread_string()
_params = reader.tgread_object()
return cls(bot=_bot, custom_method=_custom_method, params=_params)
class ReorderUsernamesRequest(TLRequest):
CONSTRUCTOR_ID = 0x9709b1c2
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, bot: 'TypeInputUser', order: List[str]):
"""
:returns Bool: This type has no constructors.
"""
self.bot = bot
self.order = order
async def resolve(self, client, utils):
self.bot = utils.get_input_user(await client.get_input_entity(self.bot))
def to_dict(self):
return {
'_': 'ReorderUsernamesRequest',
'bot': self.bot.to_dict() if isinstance(self.bot, TLObject) else self.bot,
'order': [] if self.order is None else self.order[:]
}
def _bytes(self):
return b''.join((
b'\xc2\xb1\t\x97',
self.bot._bytes(),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.order)),b''.join(self.serialize_bytes(x) for x in self.order),
))
@classmethod
def from_reader(cls, reader):
_bot = reader.tgread_object()
reader.read_int()
_order = []
for _ in range(reader.read_int()):
_x = reader.tgread_string()
_order.append(_x)
return cls(bot=_bot, order=_order)
class ResetBotCommandsRequest(TLRequest):
CONSTRUCTOR_ID = 0x3d8de0f9
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, scope: 'TypeBotCommandScope', lang_code: str):
"""
:returns Bool: This type has no constructors.
"""
self.scope = scope
self.lang_code = lang_code
def to_dict(self):
return {
'_': 'ResetBotCommandsRequest',
'scope': self.scope.to_dict() if isinstance(self.scope, TLObject) else self.scope,
'lang_code': self.lang_code
}
def _bytes(self):
return b''.join((
b'\xf9\xe0\x8d=',
self.scope._bytes(),
self.serialize_bytes(self.lang_code),
))
@classmethod
def from_reader(cls, reader):
_scope = reader.tgread_object()
_lang_code = reader.tgread_string()
return cls(scope=_scope, lang_code=_lang_code)
class SendCustomRequestRequest(TLRequest):
CONSTRUCTOR_ID = 0xaa2769ed
SUBCLASS_OF_ID = 0xad0352e8
def __init__(self, custom_method: str, params: 'TypeDataJSON'):
"""
:returns DataJSON: Instance of DataJSON.
"""
self.custom_method = custom_method
self.params = params
def to_dict(self):
return {
'_': 'SendCustomRequestRequest',
'custom_method': self.custom_method,
'params': self.params.to_dict() if isinstance(self.params, TLObject) else self.params
}
def _bytes(self):
return b''.join((
b"\xedi'\xaa",
self.serialize_bytes(self.custom_method),
self.params._bytes(),
))
@classmethod
def from_reader(cls, reader):
_custom_method = reader.tgread_string()
_params = reader.tgread_object()
return cls(custom_method=_custom_method, params=_params)
class SetBotBroadcastDefaultAdminRightsRequest(TLRequest):
CONSTRUCTOR_ID = 0x788464e1
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, admin_rights: 'TypeChatAdminRights'):
"""
:returns Bool: This type has no constructors.
"""
self.admin_rights = admin_rights
def to_dict(self):
return {
'_': 'SetBotBroadcastDefaultAdminRightsRequest',
'admin_rights': self.admin_rights.to_dict() if isinstance(self.admin_rights, TLObject) else self.admin_rights
}
def _bytes(self):
return b''.join((
b'\xe1d\x84x',
self.admin_rights._bytes(),
))
@classmethod
def from_reader(cls, reader):
_admin_rights = reader.tgread_object()
return cls(admin_rights=_admin_rights)
class SetBotCommandsRequest(TLRequest):
CONSTRUCTOR_ID = 0x517165a
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, scope: 'TypeBotCommandScope', lang_code: str, commands: List['TypeBotCommand']):
"""
:returns Bool: This type has no constructors.
"""
self.scope = scope
self.lang_code = lang_code
self.commands = commands
def to_dict(self):
return {
'_': 'SetBotCommandsRequest',
'scope': self.scope.to_dict() if isinstance(self.scope, TLObject) else self.scope,
'lang_code': self.lang_code,
'commands': [] if self.commands is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.commands]
}
def _bytes(self):
return b''.join((
b'Z\x16\x17\x05',
self.scope._bytes(),
self.serialize_bytes(self.lang_code),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.commands)),b''.join(x._bytes() for x in self.commands),
))
@classmethod
def from_reader(cls, reader):
_scope = reader.tgread_object()
_lang_code = reader.tgread_string()
reader.read_int()
_commands = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_commands.append(_x)
return cls(scope=_scope, lang_code=_lang_code, commands=_commands)
class SetBotGroupDefaultAdminRightsRequest(TLRequest):
CONSTRUCTOR_ID = 0x925ec9ea
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, admin_rights: 'TypeChatAdminRights'):
"""
:returns Bool: This type has no constructors.
"""
self.admin_rights = admin_rights
def to_dict(self):
return {
'_': 'SetBotGroupDefaultAdminRightsRequest',
'admin_rights': self.admin_rights.to_dict() if isinstance(self.admin_rights, TLObject) else self.admin_rights
}
def _bytes(self):
return b''.join((
b'\xea\xc9^\x92',
self.admin_rights._bytes(),
))
@classmethod
def from_reader(cls, reader):
_admin_rights = reader.tgread_object()
return cls(admin_rights=_admin_rights)
class SetBotInfoRequest(TLRequest):
CONSTRUCTOR_ID = 0x10cf3123
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, lang_code: str, bot: Optional['TypeInputUser']=None, name: Optional[str]=None, about: Optional[str]=None, description: Optional[str]=None):
"""
:returns Bool: This type has no constructors.
"""
self.lang_code = lang_code
self.bot = bot
self.name = name
self.about = about
self.description = description
async def resolve(self, client, utils):
if self.bot:
self.bot = utils.get_input_user(await client.get_input_entity(self.bot))
def to_dict(self):
return {
'_': 'SetBotInfoRequest',
'lang_code': self.lang_code,
'bot': self.bot.to_dict() if isinstance(self.bot, TLObject) else self.bot,
'name': self.name,
'about': self.about,
'description': self.description
}
def _bytes(self):
return b''.join((
b'#1\xcf\x10',
struct.pack('<I', (0 if self.bot is None or self.bot is False else 4) | (0 if self.name is None or self.name is False else 8) | (0 if self.about is None or self.about is False else 1) | (0 if self.description is None or self.description is False else 2)),
b'' if self.bot is None or self.bot is False else (self.bot._bytes()),
self.serialize_bytes(self.lang_code),
b'' if self.name is None or self.name is False else (self.serialize_bytes(self.name)),
b'' if self.about is None or self.about is False else (self.serialize_bytes(self.about)),
b'' if self.description is None or self.description is False else (self.serialize_bytes(self.description)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
if flags & 4:
_bot = reader.tgread_object()
else:
_bot = None
_lang_code = reader.tgread_string()
if flags & 8:
_name = reader.tgread_string()
else:
_name = None
if flags & 1:
_about = reader.tgread_string()
else:
_about = None
if flags & 2:
_description = reader.tgread_string()
else:
_description = None
return cls(lang_code=_lang_code, bot=_bot, name=_name, about=_about, description=_description)
class SetBotMenuButtonRequest(TLRequest):
CONSTRUCTOR_ID = 0x4504d54f
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, user_id: 'TypeInputUser', button: 'TypeBotMenuButton'):
"""
:returns Bool: This type has no constructors.
"""
self.user_id = user_id
self.button = button
async def resolve(self, client, utils):
self.user_id = utils.get_input_user(await client.get_input_entity(self.user_id))
def to_dict(self):
return {
'_': 'SetBotMenuButtonRequest',
'user_id': self.user_id.to_dict() if isinstance(self.user_id, TLObject) else self.user_id,
'button': self.button.to_dict() if isinstance(self.button, TLObject) else self.button
}
def _bytes(self):
return b''.join((
b'O\xd5\x04E',
self.user_id._bytes(),
self.button._bytes(),
))
@classmethod
def from_reader(cls, reader):
_user_id = reader.tgread_object()
_button = reader.tgread_object()
return cls(user_id=_user_id, button=_button)
class ToggleUsernameRequest(TLRequest):
CONSTRUCTOR_ID = 0x53ca973
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, bot: 'TypeInputUser', username: str, active: bool):
"""
:returns Bool: This type has no constructors.
"""
self.bot = bot
self.username = username
self.active = active
async def resolve(self, client, utils):
self.bot = utils.get_input_user(await client.get_input_entity(self.bot))
def to_dict(self):
return {
'_': 'ToggleUsernameRequest',
'bot': self.bot.to_dict() if isinstance(self.bot, TLObject) else self.bot,
'username': self.username,
'active': self.active
}
def _bytes(self):
return b''.join((
b's\xa9<\x05',
self.bot._bytes(),
self.serialize_bytes(self.username),
b'\xb5ur\x99' if self.active else b'7\x97y\xbc',
))
@classmethod
def from_reader(cls, reader):
_bot = reader.tgread_object()
_username = reader.tgread_string()
_active = reader.tgread_bool()
return cls(bot=_bot, username=_username, active=_active)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,425 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeInputChatlist, TypeInputPeer
class CheckChatlistInviteRequest(TLRequest):
CONSTRUCTOR_ID = 0x41c10fff
SUBCLASS_OF_ID = 0x41720e75
def __init__(self, slug: str):
"""
:returns chatlists.ChatlistInvite: Instance of either ChatlistInviteAlready, ChatlistInvite.
"""
self.slug = slug
def to_dict(self):
return {
'_': 'CheckChatlistInviteRequest',
'slug': self.slug
}
def _bytes(self):
return b''.join((
b'\xff\x0f\xc1A',
self.serialize_bytes(self.slug),
))
@classmethod
def from_reader(cls, reader):
_slug = reader.tgread_string()
return cls(slug=_slug)
class DeleteExportedInviteRequest(TLRequest):
CONSTRUCTOR_ID = 0x719c5c5e
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, chatlist: 'TypeInputChatlist', slug: str):
"""
:returns Bool: This type has no constructors.
"""
self.chatlist = chatlist
self.slug = slug
def to_dict(self):
return {
'_': 'DeleteExportedInviteRequest',
'chatlist': self.chatlist.to_dict() if isinstance(self.chatlist, TLObject) else self.chatlist,
'slug': self.slug
}
def _bytes(self):
return b''.join((
b'^\\\x9cq',
self.chatlist._bytes(),
self.serialize_bytes(self.slug),
))
@classmethod
def from_reader(cls, reader):
_chatlist = reader.tgread_object()
_slug = reader.tgread_string()
return cls(chatlist=_chatlist, slug=_slug)
class EditExportedInviteRequest(TLRequest):
CONSTRUCTOR_ID = 0x653db63d
SUBCLASS_OF_ID = 0x7711f8ff
def __init__(self, chatlist: 'TypeInputChatlist', slug: str, title: Optional[str]=None, peers: Optional[List['TypeInputPeer']]=None):
"""
:returns ExportedChatlistInvite: Instance of ExportedChatlistInvite.
"""
self.chatlist = chatlist
self.slug = slug
self.title = title
self.peers = peers
async def resolve(self, client, utils):
if self.peers:
_tmp = []
for _x in self.peers:
_tmp.append(utils.get_input_peer(await client.get_input_entity(_x)))
self.peers = _tmp
def to_dict(self):
return {
'_': 'EditExportedInviteRequest',
'chatlist': self.chatlist.to_dict() if isinstance(self.chatlist, TLObject) else self.chatlist,
'slug': self.slug,
'title': self.title,
'peers': [] if self.peers is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.peers]
}
def _bytes(self):
return b''.join((
b'=\xb6=e',
struct.pack('<I', (0 if self.title is None or self.title is False else 2) | (0 if self.peers is None or self.peers is False else 4)),
self.chatlist._bytes(),
self.serialize_bytes(self.slug),
b'' if self.title is None or self.title is False else (self.serialize_bytes(self.title)),
b'' if self.peers is None or self.peers is False else b''.join((b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.peers)),b''.join(x._bytes() for x in self.peers))),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_chatlist = reader.tgread_object()
_slug = reader.tgread_string()
if flags & 2:
_title = reader.tgread_string()
else:
_title = None
if flags & 4:
reader.read_int()
_peers = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_peers.append(_x)
else:
_peers = None
return cls(chatlist=_chatlist, slug=_slug, title=_title, peers=_peers)
class ExportChatlistInviteRequest(TLRequest):
CONSTRUCTOR_ID = 0x8472478e
SUBCLASS_OF_ID = 0xc2694ee9
def __init__(self, chatlist: 'TypeInputChatlist', title: str, peers: List['TypeInputPeer']):
"""
:returns chatlists.ExportedChatlistInvite: Instance of ExportedChatlistInvite.
"""
self.chatlist = chatlist
self.title = title
self.peers = peers
async def resolve(self, client, utils):
_tmp = []
for _x in self.peers:
_tmp.append(utils.get_input_peer(await client.get_input_entity(_x)))
self.peers = _tmp
def to_dict(self):
return {
'_': 'ExportChatlistInviteRequest',
'chatlist': self.chatlist.to_dict() if isinstance(self.chatlist, TLObject) else self.chatlist,
'title': self.title,
'peers': [] if self.peers is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.peers]
}
def _bytes(self):
return b''.join((
b'\x8eGr\x84',
self.chatlist._bytes(),
self.serialize_bytes(self.title),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.peers)),b''.join(x._bytes() for x in self.peers),
))
@classmethod
def from_reader(cls, reader):
_chatlist = reader.tgread_object()
_title = reader.tgread_string()
reader.read_int()
_peers = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_peers.append(_x)
return cls(chatlist=_chatlist, title=_title, peers=_peers)
class GetChatlistUpdatesRequest(TLRequest):
CONSTRUCTOR_ID = 0x89419521
SUBCLASS_OF_ID = 0x7d1641ea
def __init__(self, chatlist: 'TypeInputChatlist'):
"""
:returns chatlists.ChatlistUpdates: Instance of ChatlistUpdates.
"""
self.chatlist = chatlist
def to_dict(self):
return {
'_': 'GetChatlistUpdatesRequest',
'chatlist': self.chatlist.to_dict() if isinstance(self.chatlist, TLObject) else self.chatlist
}
def _bytes(self):
return b''.join((
b'!\x95A\x89',
self.chatlist._bytes(),
))
@classmethod
def from_reader(cls, reader):
_chatlist = reader.tgread_object()
return cls(chatlist=_chatlist)
class GetExportedInvitesRequest(TLRequest):
CONSTRUCTOR_ID = 0xce03da83
SUBCLASS_OF_ID = 0xe6c209c0
def __init__(self, chatlist: 'TypeInputChatlist'):
"""
:returns chatlists.ExportedInvites: Instance of ExportedInvites.
"""
self.chatlist = chatlist
def to_dict(self):
return {
'_': 'GetExportedInvitesRequest',
'chatlist': self.chatlist.to_dict() if isinstance(self.chatlist, TLObject) else self.chatlist
}
def _bytes(self):
return b''.join((
b'\x83\xda\x03\xce',
self.chatlist._bytes(),
))
@classmethod
def from_reader(cls, reader):
_chatlist = reader.tgread_object()
return cls(chatlist=_chatlist)
class GetLeaveChatlistSuggestionsRequest(TLRequest):
CONSTRUCTOR_ID = 0xfdbcd714
SUBCLASS_OF_ID = 0xb9945d7e
def __init__(self, chatlist: 'TypeInputChatlist'):
"""
:returns Vector<Peer>: This type has no constructors.
"""
self.chatlist = chatlist
def to_dict(self):
return {
'_': 'GetLeaveChatlistSuggestionsRequest',
'chatlist': self.chatlist.to_dict() if isinstance(self.chatlist, TLObject) else self.chatlist
}
def _bytes(self):
return b''.join((
b'\x14\xd7\xbc\xfd',
self.chatlist._bytes(),
))
@classmethod
def from_reader(cls, reader):
_chatlist = reader.tgread_object()
return cls(chatlist=_chatlist)
class HideChatlistUpdatesRequest(TLRequest):
CONSTRUCTOR_ID = 0x66e486fb
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, chatlist: 'TypeInputChatlist'):
"""
:returns Bool: This type has no constructors.
"""
self.chatlist = chatlist
def to_dict(self):
return {
'_': 'HideChatlistUpdatesRequest',
'chatlist': self.chatlist.to_dict() if isinstance(self.chatlist, TLObject) else self.chatlist
}
def _bytes(self):
return b''.join((
b'\xfb\x86\xe4f',
self.chatlist._bytes(),
))
@classmethod
def from_reader(cls, reader):
_chatlist = reader.tgread_object()
return cls(chatlist=_chatlist)
class JoinChatlistInviteRequest(TLRequest):
CONSTRUCTOR_ID = 0xa6b1e39a
SUBCLASS_OF_ID = 0x8af52aac
def __init__(self, slug: str, peers: List['TypeInputPeer']):
"""
:returns Updates: Instance of either UpdatesTooLong, UpdateShortMessage, UpdateShortChatMessage, UpdateShort, UpdatesCombined, Updates, UpdateShortSentMessage.
"""
self.slug = slug
self.peers = peers
async def resolve(self, client, utils):
_tmp = []
for _x in self.peers:
_tmp.append(utils.get_input_peer(await client.get_input_entity(_x)))
self.peers = _tmp
def to_dict(self):
return {
'_': 'JoinChatlistInviteRequest',
'slug': self.slug,
'peers': [] if self.peers is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.peers]
}
def _bytes(self):
return b''.join((
b'\x9a\xe3\xb1\xa6',
self.serialize_bytes(self.slug),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.peers)),b''.join(x._bytes() for x in self.peers),
))
@classmethod
def from_reader(cls, reader):
_slug = reader.tgread_string()
reader.read_int()
_peers = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_peers.append(_x)
return cls(slug=_slug, peers=_peers)
class JoinChatlistUpdatesRequest(TLRequest):
CONSTRUCTOR_ID = 0xe089f8f5
SUBCLASS_OF_ID = 0x8af52aac
def __init__(self, chatlist: 'TypeInputChatlist', peers: List['TypeInputPeer']):
"""
:returns Updates: Instance of either UpdatesTooLong, UpdateShortMessage, UpdateShortChatMessage, UpdateShort, UpdatesCombined, Updates, UpdateShortSentMessage.
"""
self.chatlist = chatlist
self.peers = peers
async def resolve(self, client, utils):
_tmp = []
for _x in self.peers:
_tmp.append(utils.get_input_peer(await client.get_input_entity(_x)))
self.peers = _tmp
def to_dict(self):
return {
'_': 'JoinChatlistUpdatesRequest',
'chatlist': self.chatlist.to_dict() if isinstance(self.chatlist, TLObject) else self.chatlist,
'peers': [] if self.peers is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.peers]
}
def _bytes(self):
return b''.join((
b'\xf5\xf8\x89\xe0',
self.chatlist._bytes(),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.peers)),b''.join(x._bytes() for x in self.peers),
))
@classmethod
def from_reader(cls, reader):
_chatlist = reader.tgread_object()
reader.read_int()
_peers = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_peers.append(_x)
return cls(chatlist=_chatlist, peers=_peers)
class LeaveChatlistRequest(TLRequest):
CONSTRUCTOR_ID = 0x74fae13a
SUBCLASS_OF_ID = 0x8af52aac
def __init__(self, chatlist: 'TypeInputChatlist', peers: List['TypeInputPeer']):
"""
:returns Updates: Instance of either UpdatesTooLong, UpdateShortMessage, UpdateShortChatMessage, UpdateShort, UpdatesCombined, Updates, UpdateShortSentMessage.
"""
self.chatlist = chatlist
self.peers = peers
async def resolve(self, client, utils):
_tmp = []
for _x in self.peers:
_tmp.append(utils.get_input_peer(await client.get_input_entity(_x)))
self.peers = _tmp
def to_dict(self):
return {
'_': 'LeaveChatlistRequest',
'chatlist': self.chatlist.to_dict() if isinstance(self.chatlist, TLObject) else self.chatlist,
'peers': [] if self.peers is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.peers]
}
def _bytes(self):
return b''.join((
b':\xe1\xfat',
self.chatlist._bytes(),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.peers)),b''.join(x._bytes() for x in self.peers),
))
@classmethod
def from_reader(cls, reader):
_chatlist = reader.tgread_object()
reader.read_int()
_peers = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_peers.append(_x)
return cls(chatlist=_chatlist, peers=_peers)

View File

@@ -0,0 +1,852 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeInputContact, TypeInputGeoPoint, TypeInputPeer, TypeInputUser, TypeTopPeerCategory
class AcceptContactRequest(TLRequest):
CONSTRUCTOR_ID = 0xf831a20f
SUBCLASS_OF_ID = 0x8af52aac
def __init__(self, id: 'TypeInputUser'):
"""
:returns Updates: Instance of either UpdatesTooLong, UpdateShortMessage, UpdateShortChatMessage, UpdateShort, UpdatesCombined, Updates, UpdateShortSentMessage.
"""
self.id = id
async def resolve(self, client, utils):
self.id = utils.get_input_user(await client.get_input_entity(self.id))
def to_dict(self):
return {
'_': 'AcceptContactRequest',
'id': self.id.to_dict() if isinstance(self.id, TLObject) else self.id
}
def _bytes(self):
return b''.join((
b'\x0f\xa21\xf8',
self.id._bytes(),
))
@classmethod
def from_reader(cls, reader):
_id = reader.tgread_object()
return cls(id=_id)
class AddContactRequest(TLRequest):
CONSTRUCTOR_ID = 0xe8f463d0
SUBCLASS_OF_ID = 0x8af52aac
def __init__(self, id: 'TypeInputUser', first_name: str, last_name: str, phone: str, add_phone_privacy_exception: Optional[bool]=None):
"""
:returns Updates: Instance of either UpdatesTooLong, UpdateShortMessage, UpdateShortChatMessage, UpdateShort, UpdatesCombined, Updates, UpdateShortSentMessage.
"""
self.id = id
self.first_name = first_name
self.last_name = last_name
self.phone = phone
self.add_phone_privacy_exception = add_phone_privacy_exception
async def resolve(self, client, utils):
self.id = utils.get_input_user(await client.get_input_entity(self.id))
def to_dict(self):
return {
'_': 'AddContactRequest',
'id': self.id.to_dict() if isinstance(self.id, TLObject) else self.id,
'first_name': self.first_name,
'last_name': self.last_name,
'phone': self.phone,
'add_phone_privacy_exception': self.add_phone_privacy_exception
}
def _bytes(self):
return b''.join((
b'\xd0c\xf4\xe8',
struct.pack('<I', (0 if self.add_phone_privacy_exception is None or self.add_phone_privacy_exception is False else 1)),
self.id._bytes(),
self.serialize_bytes(self.first_name),
self.serialize_bytes(self.last_name),
self.serialize_bytes(self.phone),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_add_phone_privacy_exception = bool(flags & 1)
_id = reader.tgread_object()
_first_name = reader.tgread_string()
_last_name = reader.tgread_string()
_phone = reader.tgread_string()
return cls(id=_id, first_name=_first_name, last_name=_last_name, phone=_phone, add_phone_privacy_exception=_add_phone_privacy_exception)
class BlockRequest(TLRequest):
CONSTRUCTOR_ID = 0x2e2e8734
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, id: 'TypeInputPeer', my_stories_from: Optional[bool]=None):
"""
:returns Bool: This type has no constructors.
"""
self.id = id
self.my_stories_from = my_stories_from
async def resolve(self, client, utils):
self.id = utils.get_input_peer(await client.get_input_entity(self.id))
def to_dict(self):
return {
'_': 'BlockRequest',
'id': self.id.to_dict() if isinstance(self.id, TLObject) else self.id,
'my_stories_from': self.my_stories_from
}
def _bytes(self):
return b''.join((
b'4\x87..',
struct.pack('<I', (0 if self.my_stories_from is None or self.my_stories_from is False else 1)),
self.id._bytes(),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_my_stories_from = bool(flags & 1)
_id = reader.tgread_object()
return cls(id=_id, my_stories_from=_my_stories_from)
class BlockFromRepliesRequest(TLRequest):
CONSTRUCTOR_ID = 0x29a8962c
SUBCLASS_OF_ID = 0x8af52aac
def __init__(self, msg_id: int, delete_message: Optional[bool]=None, delete_history: Optional[bool]=None, report_spam: Optional[bool]=None):
"""
:returns Updates: Instance of either UpdatesTooLong, UpdateShortMessage, UpdateShortChatMessage, UpdateShort, UpdatesCombined, Updates, UpdateShortSentMessage.
"""
self.msg_id = msg_id
self.delete_message = delete_message
self.delete_history = delete_history
self.report_spam = report_spam
def to_dict(self):
return {
'_': 'BlockFromRepliesRequest',
'msg_id': self.msg_id,
'delete_message': self.delete_message,
'delete_history': self.delete_history,
'report_spam': self.report_spam
}
def _bytes(self):
return b''.join((
b',\x96\xa8)',
struct.pack('<I', (0 if self.delete_message is None or self.delete_message is False else 1) | (0 if self.delete_history is None or self.delete_history is False else 2) | (0 if self.report_spam is None or self.report_spam is False else 4)),
struct.pack('<i', self.msg_id),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_delete_message = bool(flags & 1)
_delete_history = bool(flags & 2)
_report_spam = bool(flags & 4)
_msg_id = reader.read_int()
return cls(msg_id=_msg_id, delete_message=_delete_message, delete_history=_delete_history, report_spam=_report_spam)
class DeleteByPhonesRequest(TLRequest):
CONSTRUCTOR_ID = 0x1013fd9e
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, phones: List[str]):
"""
:returns Bool: This type has no constructors.
"""
self.phones = phones
def to_dict(self):
return {
'_': 'DeleteByPhonesRequest',
'phones': [] if self.phones is None else self.phones[:]
}
def _bytes(self):
return b''.join((
b'\x9e\xfd\x13\x10',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.phones)),b''.join(self.serialize_bytes(x) for x in self.phones),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_phones = []
for _ in range(reader.read_int()):
_x = reader.tgread_string()
_phones.append(_x)
return cls(phones=_phones)
class DeleteContactsRequest(TLRequest):
CONSTRUCTOR_ID = 0x96a0e00
SUBCLASS_OF_ID = 0x8af52aac
def __init__(self, id: List['TypeInputUser']):
"""
:returns Updates: Instance of either UpdatesTooLong, UpdateShortMessage, UpdateShortChatMessage, UpdateShort, UpdatesCombined, Updates, UpdateShortSentMessage.
"""
self.id = id
async def resolve(self, client, utils):
_tmp = []
for _x in self.id:
_tmp.append(utils.get_input_user(await client.get_input_entity(_x)))
self.id = _tmp
def to_dict(self):
return {
'_': 'DeleteContactsRequest',
'id': [] if self.id is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.id]
}
def _bytes(self):
return b''.join((
b'\x00\x0ej\t',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.id)),b''.join(x._bytes() for x in self.id),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_id = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_id.append(_x)
return cls(id=_id)
class EditCloseFriendsRequest(TLRequest):
CONSTRUCTOR_ID = 0xba6705f0
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, id: List[int]):
"""
:returns Bool: This type has no constructors.
"""
self.id = id
def to_dict(self):
return {
'_': 'EditCloseFriendsRequest',
'id': [] if self.id is None else self.id[:]
}
def _bytes(self):
return b''.join((
b'\xf0\x05g\xba',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.id)),b''.join(struct.pack('<q', x) for x in self.id),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_id = []
for _ in range(reader.read_int()):
_x = reader.read_long()
_id.append(_x)
return cls(id=_id)
class ExportContactTokenRequest(TLRequest):
CONSTRUCTOR_ID = 0xf8654027
SUBCLASS_OF_ID = 0x86ddbed1
def to_dict(self):
return {
'_': 'ExportContactTokenRequest'
}
def _bytes(self):
return b''.join((
b"'@e\xf8",
))
@classmethod
def from_reader(cls, reader):
return cls()
class GetBlockedRequest(TLRequest):
CONSTRUCTOR_ID = 0x9a868f80
SUBCLASS_OF_ID = 0xffba4f4f
def __init__(self, offset: int, limit: int, my_stories_from: Optional[bool]=None):
"""
:returns contacts.Blocked: Instance of either Blocked, BlockedSlice.
"""
self.offset = offset
self.limit = limit
self.my_stories_from = my_stories_from
def to_dict(self):
return {
'_': 'GetBlockedRequest',
'offset': self.offset,
'limit': self.limit,
'my_stories_from': self.my_stories_from
}
def _bytes(self):
return b''.join((
b'\x80\x8f\x86\x9a',
struct.pack('<I', (0 if self.my_stories_from is None or self.my_stories_from is False else 1)),
struct.pack('<i', self.offset),
struct.pack('<i', self.limit),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_my_stories_from = bool(flags & 1)
_offset = reader.read_int()
_limit = reader.read_int()
return cls(offset=_offset, limit=_limit, my_stories_from=_my_stories_from)
class GetContactIDsRequest(TLRequest):
CONSTRUCTOR_ID = 0x7adc669d
SUBCLASS_OF_ID = 0x5026710f
def __init__(self, hash: int):
"""
:returns Vector<int>: This type has no constructors.
"""
self.hash = hash
def to_dict(self):
return {
'_': 'GetContactIDsRequest',
'hash': self.hash
}
def _bytes(self):
return b''.join((
b'\x9df\xdcz',
struct.pack('<q', self.hash),
))
@classmethod
def from_reader(cls, reader):
_hash = reader.read_long()
return cls(hash=_hash)
@staticmethod
def read_result(reader):
reader.read_int() # Vector ID
return [reader.read_int() for _ in range(reader.read_int())]
class GetContactsRequest(TLRequest):
CONSTRUCTOR_ID = 0x5dd69e12
SUBCLASS_OF_ID = 0x38be25f6
def __init__(self, hash: int):
"""
:returns contacts.Contacts: Instance of either ContactsNotModified, Contacts.
"""
self.hash = hash
def to_dict(self):
return {
'_': 'GetContactsRequest',
'hash': self.hash
}
def _bytes(self):
return b''.join((
b'\x12\x9e\xd6]',
struct.pack('<q', self.hash),
))
@classmethod
def from_reader(cls, reader):
_hash = reader.read_long()
return cls(hash=_hash)
class GetLocatedRequest(TLRequest):
CONSTRUCTOR_ID = 0xd348bc44
SUBCLASS_OF_ID = 0x8af52aac
def __init__(self, geo_point: 'TypeInputGeoPoint', background: Optional[bool]=None, self_expires: Optional[int]=None):
"""
:returns Updates: Instance of either UpdatesTooLong, UpdateShortMessage, UpdateShortChatMessage, UpdateShort, UpdatesCombined, Updates, UpdateShortSentMessage.
"""
self.geo_point = geo_point
self.background = background
self.self_expires = self_expires
def to_dict(self):
return {
'_': 'GetLocatedRequest',
'geo_point': self.geo_point.to_dict() if isinstance(self.geo_point, TLObject) else self.geo_point,
'background': self.background,
'self_expires': self.self_expires
}
def _bytes(self):
return b''.join((
b'D\xbcH\xd3',
struct.pack('<I', (0 if self.background is None or self.background is False else 2) | (0 if self.self_expires is None or self.self_expires is False else 1)),
self.geo_point._bytes(),
b'' if self.self_expires is None or self.self_expires is False else (struct.pack('<i', self.self_expires)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_background = bool(flags & 2)
_geo_point = reader.tgread_object()
if flags & 1:
_self_expires = reader.read_int()
else:
_self_expires = None
return cls(geo_point=_geo_point, background=_background, self_expires=_self_expires)
class GetSavedRequest(TLRequest):
CONSTRUCTOR_ID = 0x82f1e39f
SUBCLASS_OF_ID = 0x975dbef
def to_dict(self):
return {
'_': 'GetSavedRequest'
}
def _bytes(self):
return b''.join((
b'\x9f\xe3\xf1\x82',
))
@classmethod
def from_reader(cls, reader):
return cls()
class GetStatusesRequest(TLRequest):
CONSTRUCTOR_ID = 0xc4a353ee
SUBCLASS_OF_ID = 0xdf815c90
def to_dict(self):
return {
'_': 'GetStatusesRequest'
}
def _bytes(self):
return b''.join((
b'\xeeS\xa3\xc4',
))
@classmethod
def from_reader(cls, reader):
return cls()
class GetTopPeersRequest(TLRequest):
CONSTRUCTOR_ID = 0x973478b6
SUBCLASS_OF_ID = 0x9ee8bb88
def __init__(self, offset: int, limit: int, hash: int, correspondents: Optional[bool]=None, bots_pm: Optional[bool]=None, bots_inline: Optional[bool]=None, phone_calls: Optional[bool]=None, forward_users: Optional[bool]=None, forward_chats: Optional[bool]=None, groups: Optional[bool]=None, channels: Optional[bool]=None):
"""
:returns contacts.TopPeers: Instance of either TopPeersNotModified, TopPeers, TopPeersDisabled.
"""
self.offset = offset
self.limit = limit
self.hash = hash
self.correspondents = correspondents
self.bots_pm = bots_pm
self.bots_inline = bots_inline
self.phone_calls = phone_calls
self.forward_users = forward_users
self.forward_chats = forward_chats
self.groups = groups
self.channels = channels
def to_dict(self):
return {
'_': 'GetTopPeersRequest',
'offset': self.offset,
'limit': self.limit,
'hash': self.hash,
'correspondents': self.correspondents,
'bots_pm': self.bots_pm,
'bots_inline': self.bots_inline,
'phone_calls': self.phone_calls,
'forward_users': self.forward_users,
'forward_chats': self.forward_chats,
'groups': self.groups,
'channels': self.channels
}
def _bytes(self):
return b''.join((
b'\xb6x4\x97',
struct.pack('<I', (0 if self.correspondents is None or self.correspondents is False else 1) | (0 if self.bots_pm is None or self.bots_pm is False else 2) | (0 if self.bots_inline is None or self.bots_inline is False else 4) | (0 if self.phone_calls is None or self.phone_calls is False else 8) | (0 if self.forward_users is None or self.forward_users is False else 16) | (0 if self.forward_chats is None or self.forward_chats is False else 32) | (0 if self.groups is None or self.groups is False else 1024) | (0 if self.channels is None or self.channels is False else 32768)),
struct.pack('<i', self.offset),
struct.pack('<i', self.limit),
struct.pack('<q', self.hash),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_correspondents = bool(flags & 1)
_bots_pm = bool(flags & 2)
_bots_inline = bool(flags & 4)
_phone_calls = bool(flags & 8)
_forward_users = bool(flags & 16)
_forward_chats = bool(flags & 32)
_groups = bool(flags & 1024)
_channels = bool(flags & 32768)
_offset = reader.read_int()
_limit = reader.read_int()
_hash = reader.read_long()
return cls(offset=_offset, limit=_limit, hash=_hash, correspondents=_correspondents, bots_pm=_bots_pm, bots_inline=_bots_inline, phone_calls=_phone_calls, forward_users=_forward_users, forward_chats=_forward_chats, groups=_groups, channels=_channels)
class ImportContactTokenRequest(TLRequest):
CONSTRUCTOR_ID = 0x13005788
SUBCLASS_OF_ID = 0x2da17977
def __init__(self, token: str):
"""
:returns User: Instance of either UserEmpty, User.
"""
self.token = token
def to_dict(self):
return {
'_': 'ImportContactTokenRequest',
'token': self.token
}
def _bytes(self):
return b''.join((
b'\x88W\x00\x13',
self.serialize_bytes(self.token),
))
@classmethod
def from_reader(cls, reader):
_token = reader.tgread_string()
return cls(token=_token)
class ImportContactsRequest(TLRequest):
CONSTRUCTOR_ID = 0x2c800be5
SUBCLASS_OF_ID = 0x8172ad93
def __init__(self, contacts: List['TypeInputContact']):
"""
:returns contacts.ImportedContacts: Instance of ImportedContacts.
"""
self.contacts = contacts
def to_dict(self):
return {
'_': 'ImportContactsRequest',
'contacts': [] if self.contacts is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.contacts]
}
def _bytes(self):
return b''.join((
b'\xe5\x0b\x80,',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.contacts)),b''.join(x._bytes() for x in self.contacts),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_contacts = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_contacts.append(_x)
return cls(contacts=_contacts)
class ResetSavedRequest(TLRequest):
CONSTRUCTOR_ID = 0x879537f1
SUBCLASS_OF_ID = 0xf5b399ac
def to_dict(self):
return {
'_': 'ResetSavedRequest'
}
def _bytes(self):
return b''.join((
b'\xf17\x95\x87',
))
@classmethod
def from_reader(cls, reader):
return cls()
class ResetTopPeerRatingRequest(TLRequest):
CONSTRUCTOR_ID = 0x1ae373ac
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, category: 'TypeTopPeerCategory', peer: 'TypeInputPeer'):
"""
:returns Bool: This type has no constructors.
"""
self.category = category
self.peer = peer
async def resolve(self, client, utils):
self.peer = utils.get_input_peer(await client.get_input_entity(self.peer))
def to_dict(self):
return {
'_': 'ResetTopPeerRatingRequest',
'category': self.category.to_dict() if isinstance(self.category, TLObject) else self.category,
'peer': self.peer.to_dict() if isinstance(self.peer, TLObject) else self.peer
}
def _bytes(self):
return b''.join((
b'\xacs\xe3\x1a',
self.category._bytes(),
self.peer._bytes(),
))
@classmethod
def from_reader(cls, reader):
_category = reader.tgread_object()
_peer = reader.tgread_object()
return cls(category=_category, peer=_peer)
class ResolvePhoneRequest(TLRequest):
CONSTRUCTOR_ID = 0x8af94344
SUBCLASS_OF_ID = 0xf065b3a8
def __init__(self, phone: str):
"""
:returns contacts.ResolvedPeer: Instance of ResolvedPeer.
"""
self.phone = phone
def to_dict(self):
return {
'_': 'ResolvePhoneRequest',
'phone': self.phone
}
def _bytes(self):
return b''.join((
b'DC\xf9\x8a',
self.serialize_bytes(self.phone),
))
@classmethod
def from_reader(cls, reader):
_phone = reader.tgread_string()
return cls(phone=_phone)
class ResolveUsernameRequest(TLRequest):
CONSTRUCTOR_ID = 0xf93ccba3
SUBCLASS_OF_ID = 0xf065b3a8
def __init__(self, username: str):
"""
:returns contacts.ResolvedPeer: Instance of ResolvedPeer.
"""
self.username = username
def to_dict(self):
return {
'_': 'ResolveUsernameRequest',
'username': self.username
}
def _bytes(self):
return b''.join((
b'\xa3\xcb<\xf9',
self.serialize_bytes(self.username),
))
@classmethod
def from_reader(cls, reader):
_username = reader.tgread_string()
return cls(username=_username)
class SearchRequest(TLRequest):
CONSTRUCTOR_ID = 0x11f812d8
SUBCLASS_OF_ID = 0x4386a2e3
def __init__(self, q: str, limit: int):
"""
:returns contacts.Found: Instance of Found.
"""
self.q = q
self.limit = limit
def to_dict(self):
return {
'_': 'SearchRequest',
'q': self.q,
'limit': self.limit
}
def _bytes(self):
return b''.join((
b'\xd8\x12\xf8\x11',
self.serialize_bytes(self.q),
struct.pack('<i', self.limit),
))
@classmethod
def from_reader(cls, reader):
_q = reader.tgread_string()
_limit = reader.read_int()
return cls(q=_q, limit=_limit)
class SetBlockedRequest(TLRequest):
CONSTRUCTOR_ID = 0x94c65c76
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, id: List['TypeInputPeer'], limit: int, my_stories_from: Optional[bool]=None):
"""
:returns Bool: This type has no constructors.
"""
self.id = id
self.limit = limit
self.my_stories_from = my_stories_from
async def resolve(self, client, utils):
_tmp = []
for _x in self.id:
_tmp.append(utils.get_input_peer(await client.get_input_entity(_x)))
self.id = _tmp
def to_dict(self):
return {
'_': 'SetBlockedRequest',
'id': [] if self.id is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.id],
'limit': self.limit,
'my_stories_from': self.my_stories_from
}
def _bytes(self):
return b''.join((
b'v\\\xc6\x94',
struct.pack('<I', (0 if self.my_stories_from is None or self.my_stories_from is False else 1)),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.id)),b''.join(x._bytes() for x in self.id),
struct.pack('<i', self.limit),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_my_stories_from = bool(flags & 1)
reader.read_int()
_id = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_id.append(_x)
_limit = reader.read_int()
return cls(id=_id, limit=_limit, my_stories_from=_my_stories_from)
class ToggleTopPeersRequest(TLRequest):
CONSTRUCTOR_ID = 0x8514bdda
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, enabled: bool):
"""
:returns Bool: This type has no constructors.
"""
self.enabled = enabled
def to_dict(self):
return {
'_': 'ToggleTopPeersRequest',
'enabled': self.enabled
}
def _bytes(self):
return b''.join((
b'\xda\xbd\x14\x85',
b'\xb5ur\x99' if self.enabled else b'7\x97y\xbc',
))
@classmethod
def from_reader(cls, reader):
_enabled = reader.tgread_bool()
return cls(enabled=_enabled)
class UnblockRequest(TLRequest):
CONSTRUCTOR_ID = 0xb550d328
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, id: 'TypeInputPeer', my_stories_from: Optional[bool]=None):
"""
:returns Bool: This type has no constructors.
"""
self.id = id
self.my_stories_from = my_stories_from
async def resolve(self, client, utils):
self.id = utils.get_input_peer(await client.get_input_entity(self.id))
def to_dict(self):
return {
'_': 'UnblockRequest',
'id': self.id.to_dict() if isinstance(self.id, TLObject) else self.id,
'my_stories_from': self.my_stories_from
}
def _bytes(self):
return b''.join((
b'(\xd3P\xb5',
struct.pack('<I', (0 if self.my_stories_from is None or self.my_stories_from is False else 1)),
self.id._bytes(),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_my_stories_from = bool(flags & 1)
_id = reader.tgread_object()
return cls(id=_id, my_stories_from=_my_stories_from)

View File

@@ -0,0 +1,44 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeInputFolderPeer
class EditPeerFoldersRequest(TLRequest):
CONSTRUCTOR_ID = 0x6847d0ab
SUBCLASS_OF_ID = 0x8af52aac
def __init__(self, folder_peers: List['TypeInputFolderPeer']):
"""
:returns Updates: Instance of either UpdatesTooLong, UpdateShortMessage, UpdateShortChatMessage, UpdateShort, UpdatesCombined, Updates, UpdateShortSentMessage.
"""
self.folder_peers = folder_peers
def to_dict(self):
return {
'_': 'EditPeerFoldersRequest',
'folder_peers': [] if self.folder_peers is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.folder_peers]
}
def _bytes(self):
return b''.join((
b'\xab\xd0Gh',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.folder_peers)),b''.join(x._bytes() for x in self.folder_peers),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_folder_peers = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_folder_peers.append(_x)
return cls(folder_peers=_folder_peers)

View File

@@ -0,0 +1,644 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeDataJSON, TypeInputAppEvent, TypeInputPeer, TypeInputUser, TypeMessageEntity
class AcceptTermsOfServiceRequest(TLRequest):
CONSTRUCTOR_ID = 0xee72f79a
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, id: 'TypeDataJSON'):
"""
:returns Bool: This type has no constructors.
"""
self.id = id
def to_dict(self):
return {
'_': 'AcceptTermsOfServiceRequest',
'id': self.id.to_dict() if isinstance(self.id, TLObject) else self.id
}
def _bytes(self):
return b''.join((
b'\x9a\xf7r\xee',
self.id._bytes(),
))
@classmethod
def from_reader(cls, reader):
_id = reader.tgread_object()
return cls(id=_id)
class DismissSuggestionRequest(TLRequest):
CONSTRUCTOR_ID = 0xf50dbaa1
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, peer: 'TypeInputPeer', suggestion: str):
"""
:returns Bool: This type has no constructors.
"""
self.peer = peer
self.suggestion = suggestion
async def resolve(self, client, utils):
self.peer = utils.get_input_peer(await client.get_input_entity(self.peer))
def to_dict(self):
return {
'_': 'DismissSuggestionRequest',
'peer': self.peer.to_dict() if isinstance(self.peer, TLObject) else self.peer,
'suggestion': self.suggestion
}
def _bytes(self):
return b''.join((
b'\xa1\xba\r\xf5',
self.peer._bytes(),
self.serialize_bytes(self.suggestion),
))
@classmethod
def from_reader(cls, reader):
_peer = reader.tgread_object()
_suggestion = reader.tgread_string()
return cls(peer=_peer, suggestion=_suggestion)
class EditUserInfoRequest(TLRequest):
CONSTRUCTOR_ID = 0x66b91b70
SUBCLASS_OF_ID = 0x5c53d7d8
def __init__(self, user_id: 'TypeInputUser', message: str, entities: List['TypeMessageEntity']):
"""
:returns help.UserInfo: Instance of either UserInfoEmpty, UserInfo.
"""
self.user_id = user_id
self.message = message
self.entities = entities
async def resolve(self, client, utils):
self.user_id = utils.get_input_user(await client.get_input_entity(self.user_id))
def to_dict(self):
return {
'_': 'EditUserInfoRequest',
'user_id': self.user_id.to_dict() if isinstance(self.user_id, TLObject) else self.user_id,
'message': self.message,
'entities': [] if self.entities is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.entities]
}
def _bytes(self):
return b''.join((
b'p\x1b\xb9f',
self.user_id._bytes(),
self.serialize_bytes(self.message),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.entities)),b''.join(x._bytes() for x in self.entities),
))
@classmethod
def from_reader(cls, reader):
_user_id = reader.tgread_object()
_message = reader.tgread_string()
reader.read_int()
_entities = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_entities.append(_x)
return cls(user_id=_user_id, message=_message, entities=_entities)
class GetAppConfigRequest(TLRequest):
CONSTRUCTOR_ID = 0x61e3f854
SUBCLASS_OF_ID = 0x14381c9a
def __init__(self, hash: int):
"""
:returns help.AppConfig: Instance of either AppConfigNotModified, AppConfig.
"""
self.hash = hash
def to_dict(self):
return {
'_': 'GetAppConfigRequest',
'hash': self.hash
}
def _bytes(self):
return b''.join((
b'T\xf8\xe3a',
struct.pack('<i', self.hash),
))
@classmethod
def from_reader(cls, reader):
_hash = reader.read_int()
return cls(hash=_hash)
class GetAppUpdateRequest(TLRequest):
CONSTRUCTOR_ID = 0x522d5a7d
SUBCLASS_OF_ID = 0x5897069e
def __init__(self, source: str):
"""
:returns help.AppUpdate: Instance of either AppUpdate, NoAppUpdate.
"""
self.source = source
def to_dict(self):
return {
'_': 'GetAppUpdateRequest',
'source': self.source
}
def _bytes(self):
return b''.join((
b'}Z-R',
self.serialize_bytes(self.source),
))
@classmethod
def from_reader(cls, reader):
_source = reader.tgread_string()
return cls(source=_source)
class GetCdnConfigRequest(TLRequest):
CONSTRUCTOR_ID = 0x52029342
SUBCLASS_OF_ID = 0xecda397c
def to_dict(self):
return {
'_': 'GetCdnConfigRequest'
}
def _bytes(self):
return b''.join((
b'B\x93\x02R',
))
@classmethod
def from_reader(cls, reader):
return cls()
class GetConfigRequest(TLRequest):
CONSTRUCTOR_ID = 0xc4f9186b
SUBCLASS_OF_ID = 0xd3262a4a
def to_dict(self):
return {
'_': 'GetConfigRequest'
}
def _bytes(self):
return b''.join((
b'k\x18\xf9\xc4',
))
@classmethod
def from_reader(cls, reader):
return cls()
class GetCountriesListRequest(TLRequest):
CONSTRUCTOR_ID = 0x735787a8
SUBCLASS_OF_ID = 0xea31fe88
def __init__(self, lang_code: str, hash: int):
"""
:returns help.CountriesList: Instance of either CountriesListNotModified, CountriesList.
"""
self.lang_code = lang_code
self.hash = hash
def to_dict(self):
return {
'_': 'GetCountriesListRequest',
'lang_code': self.lang_code,
'hash': self.hash
}
def _bytes(self):
return b''.join((
b'\xa8\x87Ws',
self.serialize_bytes(self.lang_code),
struct.pack('<i', self.hash),
))
@classmethod
def from_reader(cls, reader):
_lang_code = reader.tgread_string()
_hash = reader.read_int()
return cls(lang_code=_lang_code, hash=_hash)
class GetDeepLinkInfoRequest(TLRequest):
CONSTRUCTOR_ID = 0x3fedc75f
SUBCLASS_OF_ID = 0x984aac38
def __init__(self, path: str):
"""
:returns help.DeepLinkInfo: Instance of either DeepLinkInfoEmpty, DeepLinkInfo.
"""
self.path = path
def to_dict(self):
return {
'_': 'GetDeepLinkInfoRequest',
'path': self.path
}
def _bytes(self):
return b''.join((
b'_\xc7\xed?',
self.serialize_bytes(self.path),
))
@classmethod
def from_reader(cls, reader):
_path = reader.tgread_string()
return cls(path=_path)
class GetInviteTextRequest(TLRequest):
CONSTRUCTOR_ID = 0x4d392343
SUBCLASS_OF_ID = 0xcf70aa35
def to_dict(self):
return {
'_': 'GetInviteTextRequest'
}
def _bytes(self):
return b''.join((
b'C#9M',
))
@classmethod
def from_reader(cls, reader):
return cls()
class GetNearestDcRequest(TLRequest):
CONSTRUCTOR_ID = 0x1fb33026
SUBCLASS_OF_ID = 0x3877045f
def to_dict(self):
return {
'_': 'GetNearestDcRequest'
}
def _bytes(self):
return b''.join((
b'&0\xb3\x1f',
))
@classmethod
def from_reader(cls, reader):
return cls()
class GetPassportConfigRequest(TLRequest):
CONSTRUCTOR_ID = 0xc661ad08
SUBCLASS_OF_ID = 0xc666c0ad
def __init__(self, hash: int):
"""
:returns help.PassportConfig: Instance of either PassportConfigNotModified, PassportConfig.
"""
self.hash = hash
def to_dict(self):
return {
'_': 'GetPassportConfigRequest',
'hash': self.hash
}
def _bytes(self):
return b''.join((
b'\x08\xada\xc6',
struct.pack('<i', self.hash),
))
@classmethod
def from_reader(cls, reader):
_hash = reader.read_int()
return cls(hash=_hash)
class GetPeerColorsRequest(TLRequest):
CONSTRUCTOR_ID = 0xda80f42f
SUBCLASS_OF_ID = 0xe3f6733
def __init__(self, hash: int):
"""
:returns help.PeerColors: Instance of either PeerColorsNotModified, PeerColors.
"""
self.hash = hash
def to_dict(self):
return {
'_': 'GetPeerColorsRequest',
'hash': self.hash
}
def _bytes(self):
return b''.join((
b'/\xf4\x80\xda',
struct.pack('<i', self.hash),
))
@classmethod
def from_reader(cls, reader):
_hash = reader.read_int()
return cls(hash=_hash)
class GetPeerProfileColorsRequest(TLRequest):
CONSTRUCTOR_ID = 0xabcfa9fd
SUBCLASS_OF_ID = 0xe3f6733
def __init__(self, hash: int):
"""
:returns help.PeerColors: Instance of either PeerColorsNotModified, PeerColors.
"""
self.hash = hash
def to_dict(self):
return {
'_': 'GetPeerProfileColorsRequest',
'hash': self.hash
}
def _bytes(self):
return b''.join((
b'\xfd\xa9\xcf\xab',
struct.pack('<i', self.hash),
))
@classmethod
def from_reader(cls, reader):
_hash = reader.read_int()
return cls(hash=_hash)
class GetPremiumPromoRequest(TLRequest):
CONSTRUCTOR_ID = 0xb81b93d4
SUBCLASS_OF_ID = 0xc987a338
def to_dict(self):
return {
'_': 'GetPremiumPromoRequest'
}
def _bytes(self):
return b''.join((
b'\xd4\x93\x1b\xb8',
))
@classmethod
def from_reader(cls, reader):
return cls()
class GetPromoDataRequest(TLRequest):
CONSTRUCTOR_ID = 0xc0977421
SUBCLASS_OF_ID = 0x9d595542
def to_dict(self):
return {
'_': 'GetPromoDataRequest'
}
def _bytes(self):
return b''.join((
b'!t\x97\xc0',
))
@classmethod
def from_reader(cls, reader):
return cls()
class GetRecentMeUrlsRequest(TLRequest):
CONSTRUCTOR_ID = 0x3dc0f114
SUBCLASS_OF_ID = 0xf269c477
def __init__(self, referer: str):
"""
:returns help.RecentMeUrls: Instance of RecentMeUrls.
"""
self.referer = referer
def to_dict(self):
return {
'_': 'GetRecentMeUrlsRequest',
'referer': self.referer
}
def _bytes(self):
return b''.join((
b'\x14\xf1\xc0=',
self.serialize_bytes(self.referer),
))
@classmethod
def from_reader(cls, reader):
_referer = reader.tgread_string()
return cls(referer=_referer)
class GetSupportRequest(TLRequest):
CONSTRUCTOR_ID = 0x9cdf08cd
SUBCLASS_OF_ID = 0x7159bceb
def to_dict(self):
return {
'_': 'GetSupportRequest'
}
def _bytes(self):
return b''.join((
b'\xcd\x08\xdf\x9c',
))
@classmethod
def from_reader(cls, reader):
return cls()
class GetSupportNameRequest(TLRequest):
CONSTRUCTOR_ID = 0xd360e72c
SUBCLASS_OF_ID = 0x7f50b7c2
def to_dict(self):
return {
'_': 'GetSupportNameRequest'
}
def _bytes(self):
return b''.join((
b',\xe7`\xd3',
))
@classmethod
def from_reader(cls, reader):
return cls()
class GetTermsOfServiceUpdateRequest(TLRequest):
CONSTRUCTOR_ID = 0x2ca51fd1
SUBCLASS_OF_ID = 0x293c2977
def to_dict(self):
return {
'_': 'GetTermsOfServiceUpdateRequest'
}
def _bytes(self):
return b''.join((
b'\xd1\x1f\xa5,',
))
@classmethod
def from_reader(cls, reader):
return cls()
class GetUserInfoRequest(TLRequest):
CONSTRUCTOR_ID = 0x38a08d3
SUBCLASS_OF_ID = 0x5c53d7d8
def __init__(self, user_id: 'TypeInputUser'):
"""
:returns help.UserInfo: Instance of either UserInfoEmpty, UserInfo.
"""
self.user_id = user_id
async def resolve(self, client, utils):
self.user_id = utils.get_input_user(await client.get_input_entity(self.user_id))
def to_dict(self):
return {
'_': 'GetUserInfoRequest',
'user_id': self.user_id.to_dict() if isinstance(self.user_id, TLObject) else self.user_id
}
def _bytes(self):
return b''.join((
b'\xd3\x08\x8a\x03',
self.user_id._bytes(),
))
@classmethod
def from_reader(cls, reader):
_user_id = reader.tgread_object()
return cls(user_id=_user_id)
class HidePromoDataRequest(TLRequest):
CONSTRUCTOR_ID = 0x1e251c95
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, peer: 'TypeInputPeer'):
"""
:returns Bool: This type has no constructors.
"""
self.peer = peer
async def resolve(self, client, utils):
self.peer = utils.get_input_peer(await client.get_input_entity(self.peer))
def to_dict(self):
return {
'_': 'HidePromoDataRequest',
'peer': self.peer.to_dict() if isinstance(self.peer, TLObject) else self.peer
}
def _bytes(self):
return b''.join((
b'\x95\x1c%\x1e',
self.peer._bytes(),
))
@classmethod
def from_reader(cls, reader):
_peer = reader.tgread_object()
return cls(peer=_peer)
class SaveAppLogRequest(TLRequest):
CONSTRUCTOR_ID = 0x6f02f748
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, events: List['TypeInputAppEvent']):
"""
:returns Bool: This type has no constructors.
"""
self.events = events
def to_dict(self):
return {
'_': 'SaveAppLogRequest',
'events': [] if self.events is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.events]
}
def _bytes(self):
return b''.join((
b'H\xf7\x02o',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.events)),b''.join(x._bytes() for x in self.events),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_events = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_events.append(_x)
return cls(events=_events)
class SetBotUpdatesStatusRequest(TLRequest):
CONSTRUCTOR_ID = 0xec22cfcd
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, pending_updates_count: int, message: str):
"""
:returns Bool: This type has no constructors.
"""
self.pending_updates_count = pending_updates_count
self.message = message
def to_dict(self):
return {
'_': 'SetBotUpdatesStatusRequest',
'pending_updates_count': self.pending_updates_count,
'message': self.message
}
def _bytes(self):
return b''.join((
b'\xcd\xcf"\xec',
struct.pack('<i', self.pending_updates_count),
self.serialize_bytes(self.message),
))
@classmethod
def from_reader(cls, reader):
_pending_updates_count = reader.read_int()
_message = reader.tgread_string()
return cls(pending_updates_count=_pending_updates_count, message=_message)

View File

@@ -0,0 +1,178 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
class GetDifferenceRequest(TLRequest):
CONSTRUCTOR_ID = 0xcd984aa5
SUBCLASS_OF_ID = 0x52662d55
def __init__(self, lang_pack: str, lang_code: str, from_version: int):
"""
:returns LangPackDifference: Instance of LangPackDifference.
"""
self.lang_pack = lang_pack
self.lang_code = lang_code
self.from_version = from_version
def to_dict(self):
return {
'_': 'GetDifferenceRequest',
'lang_pack': self.lang_pack,
'lang_code': self.lang_code,
'from_version': self.from_version
}
def _bytes(self):
return b''.join((
b'\xa5J\x98\xcd',
self.serialize_bytes(self.lang_pack),
self.serialize_bytes(self.lang_code),
struct.pack('<i', self.from_version),
))
@classmethod
def from_reader(cls, reader):
_lang_pack = reader.tgread_string()
_lang_code = reader.tgread_string()
_from_version = reader.read_int()
return cls(lang_pack=_lang_pack, lang_code=_lang_code, from_version=_from_version)
class GetLangPackRequest(TLRequest):
CONSTRUCTOR_ID = 0xf2f2330a
SUBCLASS_OF_ID = 0x52662d55
def __init__(self, lang_pack: str, lang_code: str):
"""
:returns LangPackDifference: Instance of LangPackDifference.
"""
self.lang_pack = lang_pack
self.lang_code = lang_code
def to_dict(self):
return {
'_': 'GetLangPackRequest',
'lang_pack': self.lang_pack,
'lang_code': self.lang_code
}
def _bytes(self):
return b''.join((
b'\n3\xf2\xf2',
self.serialize_bytes(self.lang_pack),
self.serialize_bytes(self.lang_code),
))
@classmethod
def from_reader(cls, reader):
_lang_pack = reader.tgread_string()
_lang_code = reader.tgread_string()
return cls(lang_pack=_lang_pack, lang_code=_lang_code)
class GetLanguageRequest(TLRequest):
CONSTRUCTOR_ID = 0x6a596502
SUBCLASS_OF_ID = 0xabac89b7
def __init__(self, lang_pack: str, lang_code: str):
"""
:returns LangPackLanguage: Instance of LangPackLanguage.
"""
self.lang_pack = lang_pack
self.lang_code = lang_code
def to_dict(self):
return {
'_': 'GetLanguageRequest',
'lang_pack': self.lang_pack,
'lang_code': self.lang_code
}
def _bytes(self):
return b''.join((
b'\x02eYj',
self.serialize_bytes(self.lang_pack),
self.serialize_bytes(self.lang_code),
))
@classmethod
def from_reader(cls, reader):
_lang_pack = reader.tgread_string()
_lang_code = reader.tgread_string()
return cls(lang_pack=_lang_pack, lang_code=_lang_code)
class GetLanguagesRequest(TLRequest):
CONSTRUCTOR_ID = 0x42c6978f
SUBCLASS_OF_ID = 0x280912c9
def __init__(self, lang_pack: str):
"""
:returns Vector<LangPackLanguage>: This type has no constructors.
"""
self.lang_pack = lang_pack
def to_dict(self):
return {
'_': 'GetLanguagesRequest',
'lang_pack': self.lang_pack
}
def _bytes(self):
return b''.join((
b'\x8f\x97\xc6B',
self.serialize_bytes(self.lang_pack),
))
@classmethod
def from_reader(cls, reader):
_lang_pack = reader.tgread_string()
return cls(lang_pack=_lang_pack)
class GetStringsRequest(TLRequest):
CONSTRUCTOR_ID = 0xefea3803
SUBCLASS_OF_ID = 0xc7b7353d
# noinspection PyShadowingBuiltins
def __init__(self, lang_pack: str, lang_code: str, keys: List[str]):
"""
:returns Vector<LangPackString>: This type has no constructors.
"""
self.lang_pack = lang_pack
self.lang_code = lang_code
self.keys = keys
def to_dict(self):
return {
'_': 'GetStringsRequest',
'lang_pack': self.lang_pack,
'lang_code': self.lang_code,
'keys': [] if self.keys is None else self.keys[:]
}
def _bytes(self):
return b''.join((
b'\x038\xea\xef',
self.serialize_bytes(self.lang_pack),
self.serialize_bytes(self.lang_code),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.keys)),b''.join(self.serialize_bytes(x) for x in self.keys),
))
@classmethod
def from_reader(cls, reader):
_lang_pack = reader.tgread_string()
_lang_code = reader.tgread_string()
reader.read_int()
_keys = []
for _ in range(reader.read_int()):
_x = reader.tgread_string()
_keys.append(_x)
return cls(lang_pack=_lang_pack, lang_code=_lang_code, keys=_keys)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,553 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeDataJSON, TypeInputInvoice, TypeInputMedia, TypeInputPaymentCredentials, TypeInputPeer, TypeInputStorePaymentPurpose, TypePaymentRequestedInfo
class ApplyGiftCodeRequest(TLRequest):
CONSTRUCTOR_ID = 0xf6e26854
SUBCLASS_OF_ID = 0x8af52aac
def __init__(self, slug: str):
"""
:returns Updates: Instance of either UpdatesTooLong, UpdateShortMessage, UpdateShortChatMessage, UpdateShort, UpdatesCombined, Updates, UpdateShortSentMessage.
"""
self.slug = slug
def to_dict(self):
return {
'_': 'ApplyGiftCodeRequest',
'slug': self.slug
}
def _bytes(self):
return b''.join((
b'Th\xe2\xf6',
self.serialize_bytes(self.slug),
))
@classmethod
def from_reader(cls, reader):
_slug = reader.tgread_string()
return cls(slug=_slug)
class AssignAppStoreTransactionRequest(TLRequest):
CONSTRUCTOR_ID = 0x80ed747d
SUBCLASS_OF_ID = 0x8af52aac
def __init__(self, receipt: bytes, purpose: 'TypeInputStorePaymentPurpose'):
"""
:returns Updates: Instance of either UpdatesTooLong, UpdateShortMessage, UpdateShortChatMessage, UpdateShort, UpdatesCombined, Updates, UpdateShortSentMessage.
"""
self.receipt = receipt
self.purpose = purpose
def to_dict(self):
return {
'_': 'AssignAppStoreTransactionRequest',
'receipt': self.receipt,
'purpose': self.purpose.to_dict() if isinstance(self.purpose, TLObject) else self.purpose
}
def _bytes(self):
return b''.join((
b'}t\xed\x80',
self.serialize_bytes(self.receipt),
self.purpose._bytes(),
))
@classmethod
def from_reader(cls, reader):
_receipt = reader.tgread_bytes()
_purpose = reader.tgread_object()
return cls(receipt=_receipt, purpose=_purpose)
class AssignPlayMarketTransactionRequest(TLRequest):
CONSTRUCTOR_ID = 0xdffd50d3
SUBCLASS_OF_ID = 0x8af52aac
def __init__(self, receipt: 'TypeDataJSON', purpose: 'TypeInputStorePaymentPurpose'):
"""
:returns Updates: Instance of either UpdatesTooLong, UpdateShortMessage, UpdateShortChatMessage, UpdateShort, UpdatesCombined, Updates, UpdateShortSentMessage.
"""
self.receipt = receipt
self.purpose = purpose
def to_dict(self):
return {
'_': 'AssignPlayMarketTransactionRequest',
'receipt': self.receipt.to_dict() if isinstance(self.receipt, TLObject) else self.receipt,
'purpose': self.purpose.to_dict() if isinstance(self.purpose, TLObject) else self.purpose
}
def _bytes(self):
return b''.join((
b'\xd3P\xfd\xdf',
self.receipt._bytes(),
self.purpose._bytes(),
))
@classmethod
def from_reader(cls, reader):
_receipt = reader.tgread_object()
_purpose = reader.tgread_object()
return cls(receipt=_receipt, purpose=_purpose)
class CanPurchasePremiumRequest(TLRequest):
CONSTRUCTOR_ID = 0x9fc19eb6
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, purpose: 'TypeInputStorePaymentPurpose'):
"""
:returns Bool: This type has no constructors.
"""
self.purpose = purpose
def to_dict(self):
return {
'_': 'CanPurchasePremiumRequest',
'purpose': self.purpose.to_dict() if isinstance(self.purpose, TLObject) else self.purpose
}
def _bytes(self):
return b''.join((
b'\xb6\x9e\xc1\x9f',
self.purpose._bytes(),
))
@classmethod
def from_reader(cls, reader):
_purpose = reader.tgread_object()
return cls(purpose=_purpose)
class CheckGiftCodeRequest(TLRequest):
CONSTRUCTOR_ID = 0x8e51b4c1
SUBCLASS_OF_ID = 0x5b2997e8
def __init__(self, slug: str):
"""
:returns payments.CheckedGiftCode: Instance of CheckedGiftCode.
"""
self.slug = slug
def to_dict(self):
return {
'_': 'CheckGiftCodeRequest',
'slug': self.slug
}
def _bytes(self):
return b''.join((
b'\xc1\xb4Q\x8e',
self.serialize_bytes(self.slug),
))
@classmethod
def from_reader(cls, reader):
_slug = reader.tgread_string()
return cls(slug=_slug)
class ClearSavedInfoRequest(TLRequest):
CONSTRUCTOR_ID = 0xd83d70c1
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, credentials: Optional[bool]=None, info: Optional[bool]=None):
"""
:returns Bool: This type has no constructors.
"""
self.credentials = credentials
self.info = info
def to_dict(self):
return {
'_': 'ClearSavedInfoRequest',
'credentials': self.credentials,
'info': self.info
}
def _bytes(self):
return b''.join((
b'\xc1p=\xd8',
struct.pack('<I', (0 if self.credentials is None or self.credentials is False else 1) | (0 if self.info is None or self.info is False else 2)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_credentials = bool(flags & 1)
_info = bool(flags & 2)
return cls(credentials=_credentials, info=_info)
class ExportInvoiceRequest(TLRequest):
CONSTRUCTOR_ID = 0xf91b065
SUBCLASS_OF_ID = 0x36105432
def __init__(self, invoice_media: 'TypeInputMedia'):
"""
:returns payments.ExportedInvoice: Instance of ExportedInvoice.
"""
self.invoice_media = invoice_media
async def resolve(self, client, utils):
self.invoice_media = utils.get_input_media(self.invoice_media)
def to_dict(self):
return {
'_': 'ExportInvoiceRequest',
'invoice_media': self.invoice_media.to_dict() if isinstance(self.invoice_media, TLObject) else self.invoice_media
}
def _bytes(self):
return b''.join((
b'e\xb0\x91\x0f',
self.invoice_media._bytes(),
))
@classmethod
def from_reader(cls, reader):
_invoice_media = reader.tgread_object()
return cls(invoice_media=_invoice_media)
class GetBankCardDataRequest(TLRequest):
CONSTRUCTOR_ID = 0x2e79d779
SUBCLASS_OF_ID = 0x8c6dd68b
def __init__(self, number: str):
"""
:returns payments.BankCardData: Instance of BankCardData.
"""
self.number = number
def to_dict(self):
return {
'_': 'GetBankCardDataRequest',
'number': self.number
}
def _bytes(self):
return b''.join((
b'y\xd7y.',
self.serialize_bytes(self.number),
))
@classmethod
def from_reader(cls, reader):
_number = reader.tgread_string()
return cls(number=_number)
class GetGiveawayInfoRequest(TLRequest):
CONSTRUCTOR_ID = 0xf4239425
SUBCLASS_OF_ID = 0x96a377bd
def __init__(self, peer: 'TypeInputPeer', msg_id: int):
"""
:returns payments.GiveawayInfo: Instance of either GiveawayInfo, GiveawayInfoResults.
"""
self.peer = peer
self.msg_id = msg_id
async def resolve(self, client, utils):
self.peer = utils.get_input_peer(await client.get_input_entity(self.peer))
def to_dict(self):
return {
'_': 'GetGiveawayInfoRequest',
'peer': self.peer.to_dict() if isinstance(self.peer, TLObject) else self.peer,
'msg_id': self.msg_id
}
def _bytes(self):
return b''.join((
b'%\x94#\xf4',
self.peer._bytes(),
struct.pack('<i', self.msg_id),
))
@classmethod
def from_reader(cls, reader):
_peer = reader.tgread_object()
_msg_id = reader.read_int()
return cls(peer=_peer, msg_id=_msg_id)
class GetPaymentFormRequest(TLRequest):
CONSTRUCTOR_ID = 0x37148dbb
SUBCLASS_OF_ID = 0xa0483f19
def __init__(self, invoice: 'TypeInputInvoice', theme_params: Optional['TypeDataJSON']=None):
"""
:returns payments.PaymentForm: Instance of PaymentForm.
"""
self.invoice = invoice
self.theme_params = theme_params
def to_dict(self):
return {
'_': 'GetPaymentFormRequest',
'invoice': self.invoice.to_dict() if isinstance(self.invoice, TLObject) else self.invoice,
'theme_params': self.theme_params.to_dict() if isinstance(self.theme_params, TLObject) else self.theme_params
}
def _bytes(self):
return b''.join((
b'\xbb\x8d\x147',
struct.pack('<I', (0 if self.theme_params is None or self.theme_params is False else 1)),
self.invoice._bytes(),
b'' if self.theme_params is None or self.theme_params is False else (self.theme_params._bytes()),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_invoice = reader.tgread_object()
if flags & 1:
_theme_params = reader.tgread_object()
else:
_theme_params = None
return cls(invoice=_invoice, theme_params=_theme_params)
class GetPaymentReceiptRequest(TLRequest):
CONSTRUCTOR_ID = 0x2478d1cc
SUBCLASS_OF_ID = 0x590093c9
def __init__(self, peer: 'TypeInputPeer', msg_id: int):
"""
:returns payments.PaymentReceipt: Instance of PaymentReceipt.
"""
self.peer = peer
self.msg_id = msg_id
async def resolve(self, client, utils):
self.peer = utils.get_input_peer(await client.get_input_entity(self.peer))
def to_dict(self):
return {
'_': 'GetPaymentReceiptRequest',
'peer': self.peer.to_dict() if isinstance(self.peer, TLObject) else self.peer,
'msg_id': self.msg_id
}
def _bytes(self):
return b''.join((
b'\xcc\xd1x$',
self.peer._bytes(),
struct.pack('<i', self.msg_id),
))
@classmethod
def from_reader(cls, reader):
_peer = reader.tgread_object()
_msg_id = reader.read_int()
return cls(peer=_peer, msg_id=_msg_id)
class GetPremiumGiftCodeOptionsRequest(TLRequest):
CONSTRUCTOR_ID = 0x2757ba54
SUBCLASS_OF_ID = 0xaa92583
def __init__(self, boost_peer: Optional['TypeInputPeer']=None):
"""
:returns Vector<PremiumGiftCodeOption>: This type has no constructors.
"""
self.boost_peer = boost_peer
async def resolve(self, client, utils):
if self.boost_peer:
self.boost_peer = utils.get_input_peer(await client.get_input_entity(self.boost_peer))
def to_dict(self):
return {
'_': 'GetPremiumGiftCodeOptionsRequest',
'boost_peer': self.boost_peer.to_dict() if isinstance(self.boost_peer, TLObject) else self.boost_peer
}
def _bytes(self):
return b''.join((
b"T\xbaW'",
struct.pack('<I', (0 if self.boost_peer is None or self.boost_peer is False else 1)),
b'' if self.boost_peer is None or self.boost_peer is False else (self.boost_peer._bytes()),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
if flags & 1:
_boost_peer = reader.tgread_object()
else:
_boost_peer = None
return cls(boost_peer=_boost_peer)
class GetSavedInfoRequest(TLRequest):
CONSTRUCTOR_ID = 0x227d824b
SUBCLASS_OF_ID = 0xad3cf146
def to_dict(self):
return {
'_': 'GetSavedInfoRequest'
}
def _bytes(self):
return b''.join((
b'K\x82}"',
))
@classmethod
def from_reader(cls, reader):
return cls()
class LaunchPrepaidGiveawayRequest(TLRequest):
CONSTRUCTOR_ID = 0x5ff58f20
SUBCLASS_OF_ID = 0x8af52aac
def __init__(self, peer: 'TypeInputPeer', giveaway_id: int, purpose: 'TypeInputStorePaymentPurpose'):
"""
:returns Updates: Instance of either UpdatesTooLong, UpdateShortMessage, UpdateShortChatMessage, UpdateShort, UpdatesCombined, Updates, UpdateShortSentMessage.
"""
self.peer = peer
self.giveaway_id = giveaway_id
self.purpose = purpose
async def resolve(self, client, utils):
self.peer = utils.get_input_peer(await client.get_input_entity(self.peer))
def to_dict(self):
return {
'_': 'LaunchPrepaidGiveawayRequest',
'peer': self.peer.to_dict() if isinstance(self.peer, TLObject) else self.peer,
'giveaway_id': self.giveaway_id,
'purpose': self.purpose.to_dict() if isinstance(self.purpose, TLObject) else self.purpose
}
def _bytes(self):
return b''.join((
b' \x8f\xf5_',
self.peer._bytes(),
struct.pack('<q', self.giveaway_id),
self.purpose._bytes(),
))
@classmethod
def from_reader(cls, reader):
_peer = reader.tgread_object()
_giveaway_id = reader.read_long()
_purpose = reader.tgread_object()
return cls(peer=_peer, giveaway_id=_giveaway_id, purpose=_purpose)
class SendPaymentFormRequest(TLRequest):
CONSTRUCTOR_ID = 0x2d03522f
SUBCLASS_OF_ID = 0x8ae16a9d
def __init__(self, form_id: int, invoice: 'TypeInputInvoice', credentials: 'TypeInputPaymentCredentials', requested_info_id: Optional[str]=None, shipping_option_id: Optional[str]=None, tip_amount: Optional[int]=None):
"""
:returns payments.PaymentResult: Instance of either PaymentResult, PaymentVerificationNeeded.
"""
self.form_id = form_id
self.invoice = invoice
self.credentials = credentials
self.requested_info_id = requested_info_id
self.shipping_option_id = shipping_option_id
self.tip_amount = tip_amount
def to_dict(self):
return {
'_': 'SendPaymentFormRequest',
'form_id': self.form_id,
'invoice': self.invoice.to_dict() if isinstance(self.invoice, TLObject) else self.invoice,
'credentials': self.credentials.to_dict() if isinstance(self.credentials, TLObject) else self.credentials,
'requested_info_id': self.requested_info_id,
'shipping_option_id': self.shipping_option_id,
'tip_amount': self.tip_amount
}
def _bytes(self):
return b''.join((
b'/R\x03-',
struct.pack('<I', (0 if self.requested_info_id is None or self.requested_info_id is False else 1) | (0 if self.shipping_option_id is None or self.shipping_option_id is False else 2) | (0 if self.tip_amount is None or self.tip_amount is False else 4)),
struct.pack('<q', self.form_id),
self.invoice._bytes(),
b'' if self.requested_info_id is None or self.requested_info_id is False else (self.serialize_bytes(self.requested_info_id)),
b'' if self.shipping_option_id is None or self.shipping_option_id is False else (self.serialize_bytes(self.shipping_option_id)),
self.credentials._bytes(),
b'' if self.tip_amount is None or self.tip_amount is False else (struct.pack('<q', self.tip_amount)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_form_id = reader.read_long()
_invoice = reader.tgread_object()
if flags & 1:
_requested_info_id = reader.tgread_string()
else:
_requested_info_id = None
if flags & 2:
_shipping_option_id = reader.tgread_string()
else:
_shipping_option_id = None
_credentials = reader.tgread_object()
if flags & 4:
_tip_amount = reader.read_long()
else:
_tip_amount = None
return cls(form_id=_form_id, invoice=_invoice, credentials=_credentials, requested_info_id=_requested_info_id, shipping_option_id=_shipping_option_id, tip_amount=_tip_amount)
class ValidateRequestedInfoRequest(TLRequest):
CONSTRUCTOR_ID = 0xb6c8f12b
SUBCLASS_OF_ID = 0x8f8044b7
def __init__(self, invoice: 'TypeInputInvoice', info: 'TypePaymentRequestedInfo', save: Optional[bool]=None):
"""
:returns payments.ValidatedRequestedInfo: Instance of ValidatedRequestedInfo.
"""
self.invoice = invoice
self.info = info
self.save = save
def to_dict(self):
return {
'_': 'ValidateRequestedInfoRequest',
'invoice': self.invoice.to_dict() if isinstance(self.invoice, TLObject) else self.invoice,
'info': self.info.to_dict() if isinstance(self.info, TLObject) else self.info,
'save': self.save
}
def _bytes(self):
return b''.join((
b'+\xf1\xc8\xb6',
struct.pack('<I', (0 if self.save is None or self.save is False else 1)),
self.invoice._bytes(),
self.info._bytes(),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_save = bool(flags & 1)
_invoice = reader.tgread_object()
_info = reader.tgread_object()
return cls(invoice=_invoice, info=_info, save=_save)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,282 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeInputFile, TypeInputPhoto, TypeInputUser, TypeVideoSize
class DeletePhotosRequest(TLRequest):
CONSTRUCTOR_ID = 0x87cf7f2f
SUBCLASS_OF_ID = 0x8918e168
def __init__(self, id: List['TypeInputPhoto']):
"""
:returns Vector<long>: This type has no constructors.
"""
self.id = id
async def resolve(self, client, utils):
_tmp = []
for _x in self.id:
_tmp.append(utils.get_input_photo(_x))
self.id = _tmp
def to_dict(self):
return {
'_': 'DeletePhotosRequest',
'id': [] if self.id is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.id]
}
def _bytes(self):
return b''.join((
b'/\x7f\xcf\x87',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.id)),b''.join(x._bytes() for x in self.id),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_id = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_id.append(_x)
return cls(id=_id)
@staticmethod
def read_result(reader):
reader.read_int() # Vector ID
return [reader.read_long() for _ in range(reader.read_int())]
class GetUserPhotosRequest(TLRequest):
CONSTRUCTOR_ID = 0x91cd32a8
SUBCLASS_OF_ID = 0x27cfb967
def __init__(self, user_id: 'TypeInputUser', offset: int, max_id: int, limit: int):
"""
:returns photos.Photos: Instance of either Photos, PhotosSlice.
"""
self.user_id = user_id
self.offset = offset
self.max_id = max_id
self.limit = limit
async def resolve(self, client, utils):
self.user_id = utils.get_input_user(await client.get_input_entity(self.user_id))
def to_dict(self):
return {
'_': 'GetUserPhotosRequest',
'user_id': self.user_id.to_dict() if isinstance(self.user_id, TLObject) else self.user_id,
'offset': self.offset,
'max_id': self.max_id,
'limit': self.limit
}
def _bytes(self):
return b''.join((
b'\xa82\xcd\x91',
self.user_id._bytes(),
struct.pack('<i', self.offset),
struct.pack('<q', self.max_id),
struct.pack('<i', self.limit),
))
@classmethod
def from_reader(cls, reader):
_user_id = reader.tgread_object()
_offset = reader.read_int()
_max_id = reader.read_long()
_limit = reader.read_int()
return cls(user_id=_user_id, offset=_offset, max_id=_max_id, limit=_limit)
class UpdateProfilePhotoRequest(TLRequest):
CONSTRUCTOR_ID = 0x9e82039
SUBCLASS_OF_ID = 0xc292bd24
def __init__(self, id: 'TypeInputPhoto', fallback: Optional[bool]=None, bot: Optional['TypeInputUser']=None):
"""
:returns photos.Photo: Instance of Photo.
"""
self.id = id
self.fallback = fallback
self.bot = bot
async def resolve(self, client, utils):
self.id = utils.get_input_photo(self.id)
if self.bot:
self.bot = utils.get_input_user(await client.get_input_entity(self.bot))
def to_dict(self):
return {
'_': 'UpdateProfilePhotoRequest',
'id': self.id.to_dict() if isinstance(self.id, TLObject) else self.id,
'fallback': self.fallback,
'bot': self.bot.to_dict() if isinstance(self.bot, TLObject) else self.bot
}
def _bytes(self):
return b''.join((
b'9 \xe8\t',
struct.pack('<I', (0 if self.fallback is None or self.fallback is False else 1) | (0 if self.bot is None or self.bot is False else 2)),
b'' if self.bot is None or self.bot is False else (self.bot._bytes()),
self.id._bytes(),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_fallback = bool(flags & 1)
if flags & 2:
_bot = reader.tgread_object()
else:
_bot = None
_id = reader.tgread_object()
return cls(id=_id, fallback=_fallback, bot=_bot)
class UploadContactProfilePhotoRequest(TLRequest):
CONSTRUCTOR_ID = 0xe14c4a71
SUBCLASS_OF_ID = 0xc292bd24
def __init__(self, user_id: 'TypeInputUser', suggest: Optional[bool]=None, save: Optional[bool]=None, file: Optional['TypeInputFile']=None, video: Optional['TypeInputFile']=None, video_start_ts: Optional[float]=None, video_emoji_markup: Optional['TypeVideoSize']=None):
"""
:returns photos.Photo: Instance of Photo.
"""
self.user_id = user_id
self.suggest = suggest
self.save = save
self.file = file
self.video = video
self.video_start_ts = video_start_ts
self.video_emoji_markup = video_emoji_markup
async def resolve(self, client, utils):
self.user_id = utils.get_input_user(await client.get_input_entity(self.user_id))
def to_dict(self):
return {
'_': 'UploadContactProfilePhotoRequest',
'user_id': self.user_id.to_dict() if isinstance(self.user_id, TLObject) else self.user_id,
'suggest': self.suggest,
'save': self.save,
'file': self.file.to_dict() if isinstance(self.file, TLObject) else self.file,
'video': self.video.to_dict() if isinstance(self.video, TLObject) else self.video,
'video_start_ts': self.video_start_ts,
'video_emoji_markup': self.video_emoji_markup.to_dict() if isinstance(self.video_emoji_markup, TLObject) else self.video_emoji_markup
}
def _bytes(self):
return b''.join((
b'qJL\xe1',
struct.pack('<I', (0 if self.suggest is None or self.suggest is False else 8) | (0 if self.save is None or self.save is False else 16) | (0 if self.file is None or self.file is False else 1) | (0 if self.video is None or self.video is False else 2) | (0 if self.video_start_ts is None or self.video_start_ts is False else 4) | (0 if self.video_emoji_markup is None or self.video_emoji_markup is False else 32)),
self.user_id._bytes(),
b'' if self.file is None or self.file is False else (self.file._bytes()),
b'' if self.video is None or self.video is False else (self.video._bytes()),
b'' if self.video_start_ts is None or self.video_start_ts is False else (struct.pack('<d', self.video_start_ts)),
b'' if self.video_emoji_markup is None or self.video_emoji_markup is False else (self.video_emoji_markup._bytes()),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_suggest = bool(flags & 8)
_save = bool(flags & 16)
_user_id = reader.tgread_object()
if flags & 1:
_file = reader.tgread_object()
else:
_file = None
if flags & 2:
_video = reader.tgread_object()
else:
_video = None
if flags & 4:
_video_start_ts = reader.read_double()
else:
_video_start_ts = None
if flags & 32:
_video_emoji_markup = reader.tgread_object()
else:
_video_emoji_markup = None
return cls(user_id=_user_id, suggest=_suggest, save=_save, file=_file, video=_video, video_start_ts=_video_start_ts, video_emoji_markup=_video_emoji_markup)
class UploadProfilePhotoRequest(TLRequest):
CONSTRUCTOR_ID = 0x388a3b5
SUBCLASS_OF_ID = 0xc292bd24
def __init__(self, fallback: Optional[bool]=None, bot: Optional['TypeInputUser']=None, file: Optional['TypeInputFile']=None, video: Optional['TypeInputFile']=None, video_start_ts: Optional[float]=None, video_emoji_markup: Optional['TypeVideoSize']=None):
"""
:returns photos.Photo: Instance of Photo.
"""
self.fallback = fallback
self.bot = bot
self.file = file
self.video = video
self.video_start_ts = video_start_ts
self.video_emoji_markup = video_emoji_markup
async def resolve(self, client, utils):
if self.bot:
self.bot = utils.get_input_user(await client.get_input_entity(self.bot))
def to_dict(self):
return {
'_': 'UploadProfilePhotoRequest',
'fallback': self.fallback,
'bot': self.bot.to_dict() if isinstance(self.bot, TLObject) else self.bot,
'file': self.file.to_dict() if isinstance(self.file, TLObject) else self.file,
'video': self.video.to_dict() if isinstance(self.video, TLObject) else self.video,
'video_start_ts': self.video_start_ts,
'video_emoji_markup': self.video_emoji_markup.to_dict() if isinstance(self.video_emoji_markup, TLObject) else self.video_emoji_markup
}
def _bytes(self):
return b''.join((
b'\xb5\xa3\x88\x03',
struct.pack('<I', (0 if self.fallback is None or self.fallback is False else 8) | (0 if self.bot is None or self.bot is False else 32) | (0 if self.file is None or self.file is False else 1) | (0 if self.video is None or self.video is False else 2) | (0 if self.video_start_ts is None or self.video_start_ts is False else 4) | (0 if self.video_emoji_markup is None or self.video_emoji_markup is False else 16)),
b'' if self.bot is None or self.bot is False else (self.bot._bytes()),
b'' if self.file is None or self.file is False else (self.file._bytes()),
b'' if self.video is None or self.video is False else (self.video._bytes()),
b'' if self.video_start_ts is None or self.video_start_ts is False else (struct.pack('<d', self.video_start_ts)),
b'' if self.video_emoji_markup is None or self.video_emoji_markup is False else (self.video_emoji_markup._bytes()),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_fallback = bool(flags & 8)
if flags & 32:
_bot = reader.tgread_object()
else:
_bot = None
if flags & 1:
_file = reader.tgread_object()
else:
_file = None
if flags & 2:
_video = reader.tgread_object()
else:
_video = None
if flags & 4:
_video_start_ts = reader.read_double()
else:
_video_start_ts = None
if flags & 16:
_video_emoji_markup = reader.tgread_object()
else:
_video_emoji_markup = None
return cls(fallback=_fallback, bot=_bot, file=_file, video=_video, video_start_ts=_video_start_ts, video_emoji_markup=_video_emoji_markup)

View File

@@ -0,0 +1,188 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeInputPeer, TypeInputUser
class ApplyBoostRequest(TLRequest):
CONSTRUCTOR_ID = 0x6b7da746
SUBCLASS_OF_ID = 0xad3512db
def __init__(self, peer: 'TypeInputPeer', slots: Optional[List[int]]=None):
"""
:returns premium.MyBoosts: Instance of MyBoosts.
"""
self.peer = peer
self.slots = slots
async def resolve(self, client, utils):
self.peer = utils.get_input_peer(await client.get_input_entity(self.peer))
def to_dict(self):
return {
'_': 'ApplyBoostRequest',
'peer': self.peer.to_dict() if isinstance(self.peer, TLObject) else self.peer,
'slots': [] if self.slots is None else self.slots[:]
}
def _bytes(self):
return b''.join((
b'F\xa7}k',
struct.pack('<I', (0 if self.slots is None or self.slots is False else 1)),
b'' if self.slots is None or self.slots is False else b''.join((b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.slots)),b''.join(struct.pack('<i', x) for x in self.slots))),
self.peer._bytes(),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
if flags & 1:
reader.read_int()
_slots = []
for _ in range(reader.read_int()):
_x = reader.read_int()
_slots.append(_x)
else:
_slots = None
_peer = reader.tgread_object()
return cls(peer=_peer, slots=_slots)
class GetBoostsListRequest(TLRequest):
CONSTRUCTOR_ID = 0x60f67660
SUBCLASS_OF_ID = 0x2235a8bd
def __init__(self, peer: 'TypeInputPeer', offset: str, limit: int, gifts: Optional[bool]=None):
"""
:returns premium.BoostsList: Instance of BoostsList.
"""
self.peer = peer
self.offset = offset
self.limit = limit
self.gifts = gifts
async def resolve(self, client, utils):
self.peer = utils.get_input_peer(await client.get_input_entity(self.peer))
def to_dict(self):
return {
'_': 'GetBoostsListRequest',
'peer': self.peer.to_dict() if isinstance(self.peer, TLObject) else self.peer,
'offset': self.offset,
'limit': self.limit,
'gifts': self.gifts
}
def _bytes(self):
return b''.join((
b'`v\xf6`',
struct.pack('<I', (0 if self.gifts is None or self.gifts is False else 1)),
self.peer._bytes(),
self.serialize_bytes(self.offset),
struct.pack('<i', self.limit),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_gifts = bool(flags & 1)
_peer = reader.tgread_object()
_offset = reader.tgread_string()
_limit = reader.read_int()
return cls(peer=_peer, offset=_offset, limit=_limit, gifts=_gifts)
class GetBoostsStatusRequest(TLRequest):
CONSTRUCTOR_ID = 0x42f1f61
SUBCLASS_OF_ID = 0xc31b1ab9
def __init__(self, peer: 'TypeInputPeer'):
"""
:returns premium.BoostsStatus: Instance of BoostsStatus.
"""
self.peer = peer
async def resolve(self, client, utils):
self.peer = utils.get_input_peer(await client.get_input_entity(self.peer))
def to_dict(self):
return {
'_': 'GetBoostsStatusRequest',
'peer': self.peer.to_dict() if isinstance(self.peer, TLObject) else self.peer
}
def _bytes(self):
return b''.join((
b'a\x1f/\x04',
self.peer._bytes(),
))
@classmethod
def from_reader(cls, reader):
_peer = reader.tgread_object()
return cls(peer=_peer)
class GetMyBoostsRequest(TLRequest):
CONSTRUCTOR_ID = 0xbe77b4a
SUBCLASS_OF_ID = 0xad3512db
def to_dict(self):
return {
'_': 'GetMyBoostsRequest'
}
def _bytes(self):
return b''.join((
b'J{\xe7\x0b',
))
@classmethod
def from_reader(cls, reader):
return cls()
class GetUserBoostsRequest(TLRequest):
CONSTRUCTOR_ID = 0x39854d1f
SUBCLASS_OF_ID = 0x2235a8bd
def __init__(self, peer: 'TypeInputPeer', user_id: 'TypeInputUser'):
"""
:returns premium.BoostsList: Instance of BoostsList.
"""
self.peer = peer
self.user_id = user_id
async def resolve(self, client, utils):
self.peer = utils.get_input_peer(await client.get_input_entity(self.peer))
self.user_id = utils.get_input_user(await client.get_input_entity(self.user_id))
def to_dict(self):
return {
'_': 'GetUserBoostsRequest',
'peer': self.peer.to_dict() if isinstance(self.peer, TLObject) else self.peer,
'user_id': self.user_id.to_dict() if isinstance(self.user_id, TLObject) else self.user_id
}
def _bytes(self):
return b''.join((
b'\x1fM\x859',
self.peer._bytes(),
self.user_id._bytes(),
))
@classmethod
def from_reader(cls, reader):
_peer = reader.tgread_object()
_user_id = reader.tgread_object()
return cls(peer=_peer, user_id=_user_id)

View File

@@ -0,0 +1,291 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeInputChannel, TypeInputPeer
class GetBroadcastStatsRequest(TLRequest):
CONSTRUCTOR_ID = 0xab42441a
SUBCLASS_OF_ID = 0x7ff25428
def __init__(self, channel: 'TypeInputChannel', dark: Optional[bool]=None):
"""
:returns stats.BroadcastStats: Instance of BroadcastStats.
"""
self.channel = channel
self.dark = dark
async def resolve(self, client, utils):
self.channel = utils.get_input_channel(await client.get_input_entity(self.channel))
def to_dict(self):
return {
'_': 'GetBroadcastStatsRequest',
'channel': self.channel.to_dict() if isinstance(self.channel, TLObject) else self.channel,
'dark': self.dark
}
def _bytes(self):
return b''.join((
b'\x1aDB\xab',
struct.pack('<I', (0 if self.dark is None or self.dark is False else 1)),
self.channel._bytes(),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_dark = bool(flags & 1)
_channel = reader.tgread_object()
return cls(channel=_channel, dark=_dark)
class GetMegagroupStatsRequest(TLRequest):
CONSTRUCTOR_ID = 0xdcdf8607
SUBCLASS_OF_ID = 0x5b59be8d
def __init__(self, channel: 'TypeInputChannel', dark: Optional[bool]=None):
"""
:returns stats.MegagroupStats: Instance of MegagroupStats.
"""
self.channel = channel
self.dark = dark
async def resolve(self, client, utils):
self.channel = utils.get_input_channel(await client.get_input_entity(self.channel))
def to_dict(self):
return {
'_': 'GetMegagroupStatsRequest',
'channel': self.channel.to_dict() if isinstance(self.channel, TLObject) else self.channel,
'dark': self.dark
}
def _bytes(self):
return b''.join((
b'\x07\x86\xdf\xdc',
struct.pack('<I', (0 if self.dark is None or self.dark is False else 1)),
self.channel._bytes(),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_dark = bool(flags & 1)
_channel = reader.tgread_object()
return cls(channel=_channel, dark=_dark)
class GetMessagePublicForwardsRequest(TLRequest):
CONSTRUCTOR_ID = 0x5f150144
SUBCLASS_OF_ID = 0xa7283211
def __init__(self, channel: 'TypeInputChannel', msg_id: int, offset: str, limit: int):
"""
:returns stats.PublicForwards: Instance of PublicForwards.
"""
self.channel = channel
self.msg_id = msg_id
self.offset = offset
self.limit = limit
async def resolve(self, client, utils):
self.channel = utils.get_input_channel(await client.get_input_entity(self.channel))
def to_dict(self):
return {
'_': 'GetMessagePublicForwardsRequest',
'channel': self.channel.to_dict() if isinstance(self.channel, TLObject) else self.channel,
'msg_id': self.msg_id,
'offset': self.offset,
'limit': self.limit
}
def _bytes(self):
return b''.join((
b'D\x01\x15_',
self.channel._bytes(),
struct.pack('<i', self.msg_id),
self.serialize_bytes(self.offset),
struct.pack('<i', self.limit),
))
@classmethod
def from_reader(cls, reader):
_channel = reader.tgread_object()
_msg_id = reader.read_int()
_offset = reader.tgread_string()
_limit = reader.read_int()
return cls(channel=_channel, msg_id=_msg_id, offset=_offset, limit=_limit)
class GetMessageStatsRequest(TLRequest):
CONSTRUCTOR_ID = 0xb6e0a3f5
SUBCLASS_OF_ID = 0x9604a322
def __init__(self, channel: 'TypeInputChannel', msg_id: int, dark: Optional[bool]=None):
"""
:returns stats.MessageStats: Instance of MessageStats.
"""
self.channel = channel
self.msg_id = msg_id
self.dark = dark
async def resolve(self, client, utils):
self.channel = utils.get_input_channel(await client.get_input_entity(self.channel))
def to_dict(self):
return {
'_': 'GetMessageStatsRequest',
'channel': self.channel.to_dict() if isinstance(self.channel, TLObject) else self.channel,
'msg_id': self.msg_id,
'dark': self.dark
}
def _bytes(self):
return b''.join((
b'\xf5\xa3\xe0\xb6',
struct.pack('<I', (0 if self.dark is None or self.dark is False else 1)),
self.channel._bytes(),
struct.pack('<i', self.msg_id),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_dark = bool(flags & 1)
_channel = reader.tgread_object()
_msg_id = reader.read_int()
return cls(channel=_channel, msg_id=_msg_id, dark=_dark)
class GetStoryPublicForwardsRequest(TLRequest):
CONSTRUCTOR_ID = 0xa6437ef6
SUBCLASS_OF_ID = 0xa7283211
def __init__(self, peer: 'TypeInputPeer', id: int, offset: str, limit: int):
"""
:returns stats.PublicForwards: Instance of PublicForwards.
"""
self.peer = peer
self.id = id
self.offset = offset
self.limit = limit
async def resolve(self, client, utils):
self.peer = utils.get_input_peer(await client.get_input_entity(self.peer))
def to_dict(self):
return {
'_': 'GetStoryPublicForwardsRequest',
'peer': self.peer.to_dict() if isinstance(self.peer, TLObject) else self.peer,
'id': self.id,
'offset': self.offset,
'limit': self.limit
}
def _bytes(self):
return b''.join((
b'\xf6~C\xa6',
self.peer._bytes(),
struct.pack('<i', self.id),
self.serialize_bytes(self.offset),
struct.pack('<i', self.limit),
))
@classmethod
def from_reader(cls, reader):
_peer = reader.tgread_object()
_id = reader.read_int()
_offset = reader.tgread_string()
_limit = reader.read_int()
return cls(peer=_peer, id=_id, offset=_offset, limit=_limit)
class GetStoryStatsRequest(TLRequest):
CONSTRUCTOR_ID = 0x374fef40
SUBCLASS_OF_ID = 0x8b4d43d4
def __init__(self, peer: 'TypeInputPeer', id: int, dark: Optional[bool]=None):
"""
:returns stats.StoryStats: Instance of StoryStats.
"""
self.peer = peer
self.id = id
self.dark = dark
async def resolve(self, client, utils):
self.peer = utils.get_input_peer(await client.get_input_entity(self.peer))
def to_dict(self):
return {
'_': 'GetStoryStatsRequest',
'peer': self.peer.to_dict() if isinstance(self.peer, TLObject) else self.peer,
'id': self.id,
'dark': self.dark
}
def _bytes(self):
return b''.join((
b'@\xefO7',
struct.pack('<I', (0 if self.dark is None or self.dark is False else 1)),
self.peer._bytes(),
struct.pack('<i', self.id),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_dark = bool(flags & 1)
_peer = reader.tgread_object()
_id = reader.read_int()
return cls(peer=_peer, id=_id, dark=_dark)
class LoadAsyncGraphRequest(TLRequest):
CONSTRUCTOR_ID = 0x621d5fa0
SUBCLASS_OF_ID = 0x9b903153
def __init__(self, token: str, x: Optional[int]=None):
"""
:returns StatsGraph: Instance of either StatsGraphAsync, StatsGraphError, StatsGraph.
"""
self.token = token
self.x = x
def to_dict(self):
return {
'_': 'LoadAsyncGraphRequest',
'token': self.token,
'x': self.x
}
def _bytes(self):
return b''.join((
b'\xa0_\x1db',
struct.pack('<I', (0 if self.x is None or self.x is False else 1)),
self.serialize_bytes(self.token),
b'' if self.x is None or self.x is False else (struct.pack('<q', self.x)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_token = reader.tgread_string()
if flags & 1:
_x = reader.read_long()
else:
_x = None
return cls(token=_token, x=_x)

View File

@@ -0,0 +1,411 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeInputDocument, TypeInputStickerSet, TypeInputStickerSetItem, TypeInputUser, TypeMaskCoords
class AddStickerToSetRequest(TLRequest):
CONSTRUCTOR_ID = 0x8653febe
SUBCLASS_OF_ID = 0x9b704a5a
def __init__(self, stickerset: 'TypeInputStickerSet', sticker: 'TypeInputStickerSetItem'):
"""
:returns messages.StickerSet: Instance of either StickerSet, StickerSetNotModified.
"""
self.stickerset = stickerset
self.sticker = sticker
def to_dict(self):
return {
'_': 'AddStickerToSetRequest',
'stickerset': self.stickerset.to_dict() if isinstance(self.stickerset, TLObject) else self.stickerset,
'sticker': self.sticker.to_dict() if isinstance(self.sticker, TLObject) else self.sticker
}
def _bytes(self):
return b''.join((
b'\xbe\xfeS\x86',
self.stickerset._bytes(),
self.sticker._bytes(),
))
@classmethod
def from_reader(cls, reader):
_stickerset = reader.tgread_object()
_sticker = reader.tgread_object()
return cls(stickerset=_stickerset, sticker=_sticker)
class ChangeStickerRequest(TLRequest):
CONSTRUCTOR_ID = 0xf5537ebc
SUBCLASS_OF_ID = 0x9b704a5a
def __init__(self, sticker: 'TypeInputDocument', emoji: Optional[str]=None, mask_coords: Optional['TypeMaskCoords']=None, keywords: Optional[str]=None):
"""
:returns messages.StickerSet: Instance of either StickerSet, StickerSetNotModified.
"""
self.sticker = sticker
self.emoji = emoji
self.mask_coords = mask_coords
self.keywords = keywords
async def resolve(self, client, utils):
self.sticker = utils.get_input_document(self.sticker)
def to_dict(self):
return {
'_': 'ChangeStickerRequest',
'sticker': self.sticker.to_dict() if isinstance(self.sticker, TLObject) else self.sticker,
'emoji': self.emoji,
'mask_coords': self.mask_coords.to_dict() if isinstance(self.mask_coords, TLObject) else self.mask_coords,
'keywords': self.keywords
}
def _bytes(self):
return b''.join((
b'\xbc~S\xf5',
struct.pack('<I', (0 if self.emoji is None or self.emoji is False else 1) | (0 if self.mask_coords is None or self.mask_coords is False else 2) | (0 if self.keywords is None or self.keywords is False else 4)),
self.sticker._bytes(),
b'' if self.emoji is None or self.emoji is False else (self.serialize_bytes(self.emoji)),
b'' if self.mask_coords is None or self.mask_coords is False else (self.mask_coords._bytes()),
b'' if self.keywords is None or self.keywords is False else (self.serialize_bytes(self.keywords)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_sticker = reader.tgread_object()
if flags & 1:
_emoji = reader.tgread_string()
else:
_emoji = None
if flags & 2:
_mask_coords = reader.tgread_object()
else:
_mask_coords = None
if flags & 4:
_keywords = reader.tgread_string()
else:
_keywords = None
return cls(sticker=_sticker, emoji=_emoji, mask_coords=_mask_coords, keywords=_keywords)
class ChangeStickerPositionRequest(TLRequest):
CONSTRUCTOR_ID = 0xffb6d4ca
SUBCLASS_OF_ID = 0x9b704a5a
def __init__(self, sticker: 'TypeInputDocument', position: int):
"""
:returns messages.StickerSet: Instance of either StickerSet, StickerSetNotModified.
"""
self.sticker = sticker
self.position = position
async def resolve(self, client, utils):
self.sticker = utils.get_input_document(self.sticker)
def to_dict(self):
return {
'_': 'ChangeStickerPositionRequest',
'sticker': self.sticker.to_dict() if isinstance(self.sticker, TLObject) else self.sticker,
'position': self.position
}
def _bytes(self):
return b''.join((
b'\xca\xd4\xb6\xff',
self.sticker._bytes(),
struct.pack('<i', self.position),
))
@classmethod
def from_reader(cls, reader):
_sticker = reader.tgread_object()
_position = reader.read_int()
return cls(sticker=_sticker, position=_position)
class CheckShortNameRequest(TLRequest):
CONSTRUCTOR_ID = 0x284b3639
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, short_name: str):
"""
:returns Bool: This type has no constructors.
"""
self.short_name = short_name
def to_dict(self):
return {
'_': 'CheckShortNameRequest',
'short_name': self.short_name
}
def _bytes(self):
return b''.join((
b'96K(',
self.serialize_bytes(self.short_name),
))
@classmethod
def from_reader(cls, reader):
_short_name = reader.tgread_string()
return cls(short_name=_short_name)
class CreateStickerSetRequest(TLRequest):
CONSTRUCTOR_ID = 0x9021ab67
SUBCLASS_OF_ID = 0x9b704a5a
def __init__(self, user_id: 'TypeInputUser', title: str, short_name: str, stickers: List['TypeInputStickerSetItem'], masks: Optional[bool]=None, animated: Optional[bool]=None, videos: Optional[bool]=None, emojis: Optional[bool]=None, text_color: Optional[bool]=None, thumb: Optional['TypeInputDocument']=None, software: Optional[str]=None):
"""
:returns messages.StickerSet: Instance of either StickerSet, StickerSetNotModified.
"""
self.user_id = user_id
self.title = title
self.short_name = short_name
self.stickers = stickers
self.masks = masks
self.animated = animated
self.videos = videos
self.emojis = emojis
self.text_color = text_color
self.thumb = thumb
self.software = software
async def resolve(self, client, utils):
self.user_id = utils.get_input_user(await client.get_input_entity(self.user_id))
if self.thumb:
self.thumb = utils.get_input_document(self.thumb)
def to_dict(self):
return {
'_': 'CreateStickerSetRequest',
'user_id': self.user_id.to_dict() if isinstance(self.user_id, TLObject) else self.user_id,
'title': self.title,
'short_name': self.short_name,
'stickers': [] if self.stickers is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.stickers],
'masks': self.masks,
'animated': self.animated,
'videos': self.videos,
'emojis': self.emojis,
'text_color': self.text_color,
'thumb': self.thumb.to_dict() if isinstance(self.thumb, TLObject) else self.thumb,
'software': self.software
}
def _bytes(self):
return b''.join((
b'g\xab!\x90',
struct.pack('<I', (0 if self.masks is None or self.masks is False else 1) | (0 if self.animated is None or self.animated is False else 2) | (0 if self.videos is None or self.videos is False else 16) | (0 if self.emojis is None or self.emojis is False else 32) | (0 if self.text_color is None or self.text_color is False else 64) | (0 if self.thumb is None or self.thumb is False else 4) | (0 if self.software is None or self.software is False else 8)),
self.user_id._bytes(),
self.serialize_bytes(self.title),
self.serialize_bytes(self.short_name),
b'' if self.thumb is None or self.thumb is False else (self.thumb._bytes()),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.stickers)),b''.join(x._bytes() for x in self.stickers),
b'' if self.software is None or self.software is False else (self.serialize_bytes(self.software)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_masks = bool(flags & 1)
_animated = bool(flags & 2)
_videos = bool(flags & 16)
_emojis = bool(flags & 32)
_text_color = bool(flags & 64)
_user_id = reader.tgread_object()
_title = reader.tgread_string()
_short_name = reader.tgread_string()
if flags & 4:
_thumb = reader.tgread_object()
else:
_thumb = None
reader.read_int()
_stickers = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_stickers.append(_x)
if flags & 8:
_software = reader.tgread_string()
else:
_software = None
return cls(user_id=_user_id, title=_title, short_name=_short_name, stickers=_stickers, masks=_masks, animated=_animated, videos=_videos, emojis=_emojis, text_color=_text_color, thumb=_thumb, software=_software)
class DeleteStickerSetRequest(TLRequest):
CONSTRUCTOR_ID = 0x87704394
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, stickerset: 'TypeInputStickerSet'):
"""
:returns Bool: This type has no constructors.
"""
self.stickerset = stickerset
def to_dict(self):
return {
'_': 'DeleteStickerSetRequest',
'stickerset': self.stickerset.to_dict() if isinstance(self.stickerset, TLObject) else self.stickerset
}
def _bytes(self):
return b''.join((
b'\x94Cp\x87',
self.stickerset._bytes(),
))
@classmethod
def from_reader(cls, reader):
_stickerset = reader.tgread_object()
return cls(stickerset=_stickerset)
class RemoveStickerFromSetRequest(TLRequest):
CONSTRUCTOR_ID = 0xf7760f51
SUBCLASS_OF_ID = 0x9b704a5a
def __init__(self, sticker: 'TypeInputDocument'):
"""
:returns messages.StickerSet: Instance of either StickerSet, StickerSetNotModified.
"""
self.sticker = sticker
async def resolve(self, client, utils):
self.sticker = utils.get_input_document(self.sticker)
def to_dict(self):
return {
'_': 'RemoveStickerFromSetRequest',
'sticker': self.sticker.to_dict() if isinstance(self.sticker, TLObject) else self.sticker
}
def _bytes(self):
return b''.join((
b'Q\x0fv\xf7',
self.sticker._bytes(),
))
@classmethod
def from_reader(cls, reader):
_sticker = reader.tgread_object()
return cls(sticker=_sticker)
class RenameStickerSetRequest(TLRequest):
CONSTRUCTOR_ID = 0x124b1c00
SUBCLASS_OF_ID = 0x9b704a5a
def __init__(self, stickerset: 'TypeInputStickerSet', title: str):
"""
:returns messages.StickerSet: Instance of either StickerSet, StickerSetNotModified.
"""
self.stickerset = stickerset
self.title = title
def to_dict(self):
return {
'_': 'RenameStickerSetRequest',
'stickerset': self.stickerset.to_dict() if isinstance(self.stickerset, TLObject) else self.stickerset,
'title': self.title
}
def _bytes(self):
return b''.join((
b'\x00\x1cK\x12',
self.stickerset._bytes(),
self.serialize_bytes(self.title),
))
@classmethod
def from_reader(cls, reader):
_stickerset = reader.tgread_object()
_title = reader.tgread_string()
return cls(stickerset=_stickerset, title=_title)
class SetStickerSetThumbRequest(TLRequest):
CONSTRUCTOR_ID = 0xa76a5392
SUBCLASS_OF_ID = 0x9b704a5a
def __init__(self, stickerset: 'TypeInputStickerSet', thumb: Optional['TypeInputDocument']=None, thumb_document_id: Optional[int]=None):
"""
:returns messages.StickerSet: Instance of either StickerSet, StickerSetNotModified.
"""
self.stickerset = stickerset
self.thumb = thumb
self.thumb_document_id = thumb_document_id
async def resolve(self, client, utils):
if self.thumb:
self.thumb = utils.get_input_document(self.thumb)
def to_dict(self):
return {
'_': 'SetStickerSetThumbRequest',
'stickerset': self.stickerset.to_dict() if isinstance(self.stickerset, TLObject) else self.stickerset,
'thumb': self.thumb.to_dict() if isinstance(self.thumb, TLObject) else self.thumb,
'thumb_document_id': self.thumb_document_id
}
def _bytes(self):
return b''.join((
b'\x92Sj\xa7',
struct.pack('<I', (0 if self.thumb is None or self.thumb is False else 1) | (0 if self.thumb_document_id is None or self.thumb_document_id is False else 2)),
self.stickerset._bytes(),
b'' if self.thumb is None or self.thumb is False else (self.thumb._bytes()),
b'' if self.thumb_document_id is None or self.thumb_document_id is False else (struct.pack('<q', self.thumb_document_id)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_stickerset = reader.tgread_object()
if flags & 1:
_thumb = reader.tgread_object()
else:
_thumb = None
if flags & 2:
_thumb_document_id = reader.read_long()
else:
_thumb_document_id = None
return cls(stickerset=_stickerset, thumb=_thumb, thumb_document_id=_thumb_document_id)
class SuggestShortNameRequest(TLRequest):
CONSTRUCTOR_ID = 0x4dafc503
SUBCLASS_OF_ID = 0xc44a4b21
def __init__(self, title: str):
"""
:returns stickers.SuggestedShortName: Instance of SuggestedShortName.
"""
self.title = title
def to_dict(self):
return {
'_': 'SuggestShortNameRequest',
'title': self.title
}
def _bytes(self):
return b''.join((
b'\x03\xc5\xafM',
self.serialize_bytes(self.title),
))
@classmethod
def from_reader(cls, reader):
_title = reader.tgread_string()
return cls(title=_title)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,139 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeChannelMessagesFilter, TypeInputChannel
class GetChannelDifferenceRequest(TLRequest):
CONSTRUCTOR_ID = 0x3173d78
SUBCLASS_OF_ID = 0x29896f5d
def __init__(self, channel: 'TypeInputChannel', filter: 'TypeChannelMessagesFilter', pts: int, limit: int, force: Optional[bool]=None):
"""
:returns updates.ChannelDifference: Instance of either ChannelDifferenceEmpty, ChannelDifferenceTooLong, ChannelDifference.
"""
self.channel = channel
self.filter = filter
self.pts = pts
self.limit = limit
self.force = force
async def resolve(self, client, utils):
self.channel = utils.get_input_channel(await client.get_input_entity(self.channel))
def to_dict(self):
return {
'_': 'GetChannelDifferenceRequest',
'channel': self.channel.to_dict() if isinstance(self.channel, TLObject) else self.channel,
'filter': self.filter.to_dict() if isinstance(self.filter, TLObject) else self.filter,
'pts': self.pts,
'limit': self.limit,
'force': self.force
}
def _bytes(self):
return b''.join((
b'x=\x17\x03',
struct.pack('<I', (0 if self.force is None or self.force is False else 1)),
self.channel._bytes(),
self.filter._bytes(),
struct.pack('<i', self.pts),
struct.pack('<i', self.limit),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_force = bool(flags & 1)
_channel = reader.tgread_object()
_filter = reader.tgread_object()
_pts = reader.read_int()
_limit = reader.read_int()
return cls(channel=_channel, filter=_filter, pts=_pts, limit=_limit, force=_force)
class GetDifferenceRequest(TLRequest):
CONSTRUCTOR_ID = 0x19c2f763
SUBCLASS_OF_ID = 0x20482874
def __init__(self, pts: int, date: Optional[datetime], qts: int, pts_limit: Optional[int]=None, pts_total_limit: Optional[int]=None, qts_limit: Optional[int]=None):
"""
:returns updates.Difference: Instance of either DifferenceEmpty, Difference, DifferenceSlice, DifferenceTooLong.
"""
self.pts = pts
self.date = date
self.qts = qts
self.pts_limit = pts_limit
self.pts_total_limit = pts_total_limit
self.qts_limit = qts_limit
def to_dict(self):
return {
'_': 'GetDifferenceRequest',
'pts': self.pts,
'date': self.date,
'qts': self.qts,
'pts_limit': self.pts_limit,
'pts_total_limit': self.pts_total_limit,
'qts_limit': self.qts_limit
}
def _bytes(self):
return b''.join((
b'c\xf7\xc2\x19',
struct.pack('<I', (0 if self.pts_limit is None or self.pts_limit is False else 2) | (0 if self.pts_total_limit is None or self.pts_total_limit is False else 1) | (0 if self.qts_limit is None or self.qts_limit is False else 4)),
struct.pack('<i', self.pts),
b'' if self.pts_limit is None or self.pts_limit is False else (struct.pack('<i', self.pts_limit)),
b'' if self.pts_total_limit is None or self.pts_total_limit is False else (struct.pack('<i', self.pts_total_limit)),
self.serialize_datetime(self.date),
struct.pack('<i', self.qts),
b'' if self.qts_limit is None or self.qts_limit is False else (struct.pack('<i', self.qts_limit)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_pts = reader.read_int()
if flags & 2:
_pts_limit = reader.read_int()
else:
_pts_limit = None
if flags & 1:
_pts_total_limit = reader.read_int()
else:
_pts_total_limit = None
_date = reader.tgread_date()
_qts = reader.read_int()
if flags & 4:
_qts_limit = reader.read_int()
else:
_qts_limit = None
return cls(pts=_pts, date=_date, qts=_qts, pts_limit=_pts_limit, pts_total_limit=_pts_total_limit, qts_limit=_qts_limit)
class GetStateRequest(TLRequest):
CONSTRUCTOR_ID = 0xedd4882a
SUBCLASS_OF_ID = 0x23df1a01
def to_dict(self):
return {
'_': 'GetStateRequest'
}
def _bytes(self):
return b''.join((
b'*\x88\xd4\xed',
))
@classmethod
def from_reader(cls, reader):
return cls()

View File

@@ -0,0 +1,300 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeInputFileLocation, TypeInputWebFileLocation
class GetCdnFileRequest(TLRequest):
CONSTRUCTOR_ID = 0x395f69da
SUBCLASS_OF_ID = 0xf5ccf928
def __init__(self, file_token: bytes, offset: int, limit: int):
"""
:returns upload.CdnFile: Instance of either CdnFileReuploadNeeded, CdnFile.
"""
self.file_token = file_token
self.offset = offset
self.limit = limit
def to_dict(self):
return {
'_': 'GetCdnFileRequest',
'file_token': self.file_token,
'offset': self.offset,
'limit': self.limit
}
def _bytes(self):
return b''.join((
b'\xdai_9',
self.serialize_bytes(self.file_token),
struct.pack('<q', self.offset),
struct.pack('<i', self.limit),
))
@classmethod
def from_reader(cls, reader):
_file_token = reader.tgread_bytes()
_offset = reader.read_long()
_limit = reader.read_int()
return cls(file_token=_file_token, offset=_offset, limit=_limit)
class GetCdnFileHashesRequest(TLRequest):
CONSTRUCTOR_ID = 0x91dc3f31
SUBCLASS_OF_ID = 0xa5940726
def __init__(self, file_token: bytes, offset: int):
"""
:returns Vector<FileHash>: This type has no constructors.
"""
self.file_token = file_token
self.offset = offset
def to_dict(self):
return {
'_': 'GetCdnFileHashesRequest',
'file_token': self.file_token,
'offset': self.offset
}
def _bytes(self):
return b''.join((
b'1?\xdc\x91',
self.serialize_bytes(self.file_token),
struct.pack('<q', self.offset),
))
@classmethod
def from_reader(cls, reader):
_file_token = reader.tgread_bytes()
_offset = reader.read_long()
return cls(file_token=_file_token, offset=_offset)
class GetFileRequest(TLRequest):
CONSTRUCTOR_ID = 0xbe5335be
SUBCLASS_OF_ID = 0x6c9bd728
def __init__(self, location: 'TypeInputFileLocation', offset: int, limit: int, precise: Optional[bool]=None, cdn_supported: Optional[bool]=None):
"""
:returns upload.File: Instance of either File, FileCdnRedirect.
"""
self.location = location
self.offset = offset
self.limit = limit
self.precise = precise
self.cdn_supported = cdn_supported
def to_dict(self):
return {
'_': 'GetFileRequest',
'location': self.location.to_dict() if isinstance(self.location, TLObject) else self.location,
'offset': self.offset,
'limit': self.limit,
'precise': self.precise,
'cdn_supported': self.cdn_supported
}
def _bytes(self):
return b''.join((
b'\xbe5S\xbe',
struct.pack('<I', (0 if self.precise is None or self.precise is False else 1) | (0 if self.cdn_supported is None or self.cdn_supported is False else 2)),
self.location._bytes(),
struct.pack('<q', self.offset),
struct.pack('<i', self.limit),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_precise = bool(flags & 1)
_cdn_supported = bool(flags & 2)
_location = reader.tgread_object()
_offset = reader.read_long()
_limit = reader.read_int()
return cls(location=_location, offset=_offset, limit=_limit, precise=_precise, cdn_supported=_cdn_supported)
class GetFileHashesRequest(TLRequest):
CONSTRUCTOR_ID = 0x9156982a
SUBCLASS_OF_ID = 0xa5940726
def __init__(self, location: 'TypeInputFileLocation', offset: int):
"""
:returns Vector<FileHash>: This type has no constructors.
"""
self.location = location
self.offset = offset
def to_dict(self):
return {
'_': 'GetFileHashesRequest',
'location': self.location.to_dict() if isinstance(self.location, TLObject) else self.location,
'offset': self.offset
}
def _bytes(self):
return b''.join((
b'*\x98V\x91',
self.location._bytes(),
struct.pack('<q', self.offset),
))
@classmethod
def from_reader(cls, reader):
_location = reader.tgread_object()
_offset = reader.read_long()
return cls(location=_location, offset=_offset)
class GetWebFileRequest(TLRequest):
CONSTRUCTOR_ID = 0x24e6818d
SUBCLASS_OF_ID = 0x68f17f51
def __init__(self, location: 'TypeInputWebFileLocation', offset: int, limit: int):
"""
:returns upload.WebFile: Instance of WebFile.
"""
self.location = location
self.offset = offset
self.limit = limit
def to_dict(self):
return {
'_': 'GetWebFileRequest',
'location': self.location.to_dict() if isinstance(self.location, TLObject) else self.location,
'offset': self.offset,
'limit': self.limit
}
def _bytes(self):
return b''.join((
b'\x8d\x81\xe6$',
self.location._bytes(),
struct.pack('<i', self.offset),
struct.pack('<i', self.limit),
))
@classmethod
def from_reader(cls, reader):
_location = reader.tgread_object()
_offset = reader.read_int()
_limit = reader.read_int()
return cls(location=_location, offset=_offset, limit=_limit)
class ReuploadCdnFileRequest(TLRequest):
CONSTRUCTOR_ID = 0x9b2754a8
SUBCLASS_OF_ID = 0xa5940726
def __init__(self, file_token: bytes, request_token: bytes):
"""
:returns Vector<FileHash>: This type has no constructors.
"""
self.file_token = file_token
self.request_token = request_token
def to_dict(self):
return {
'_': 'ReuploadCdnFileRequest',
'file_token': self.file_token,
'request_token': self.request_token
}
def _bytes(self):
return b''.join((
b"\xa8T'\x9b",
self.serialize_bytes(self.file_token),
self.serialize_bytes(self.request_token),
))
@classmethod
def from_reader(cls, reader):
_file_token = reader.tgread_bytes()
_request_token = reader.tgread_bytes()
return cls(file_token=_file_token, request_token=_request_token)
class SaveBigFilePartRequest(TLRequest):
CONSTRUCTOR_ID = 0xde7b673d
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, file_id: int, file_part: int, file_total_parts: int, bytes: bytes):
"""
:returns Bool: This type has no constructors.
"""
self.file_id = file_id
self.file_part = file_part
self.file_total_parts = file_total_parts
self.bytes = bytes
def to_dict(self):
return {
'_': 'SaveBigFilePartRequest',
'file_id': self.file_id,
'file_part': self.file_part,
'file_total_parts': self.file_total_parts,
'bytes': self.bytes
}
def _bytes(self):
return b''.join((
b'=g{\xde',
struct.pack('<q', self.file_id),
struct.pack('<i', self.file_part),
struct.pack('<i', self.file_total_parts),
self.serialize_bytes(self.bytes),
))
@classmethod
def from_reader(cls, reader):
_file_id = reader.read_long()
_file_part = reader.read_int()
_file_total_parts = reader.read_int()
_bytes = reader.tgread_bytes()
return cls(file_id=_file_id, file_part=_file_part, file_total_parts=_file_total_parts, bytes=_bytes)
class SaveFilePartRequest(TLRequest):
CONSTRUCTOR_ID = 0xb304a621
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, file_id: int, file_part: int, bytes: bytes):
"""
:returns Bool: This type has no constructors.
"""
self.file_id = file_id
self.file_part = file_part
self.bytes = bytes
def to_dict(self):
return {
'_': 'SaveFilePartRequest',
'file_id': self.file_id,
'file_part': self.file_part,
'bytes': self.bytes
}
def _bytes(self):
return b''.join((
b'!\xa6\x04\xb3',
struct.pack('<q', self.file_id),
struct.pack('<i', self.file_part),
self.serialize_bytes(self.bytes),
))
@classmethod
def from_reader(cls, reader):
_file_id = reader.read_long()
_file_part = reader.read_int()
_bytes = reader.tgread_bytes()
return cls(file_id=_file_id, file_part=_file_part, bytes=_bytes)

View File

@@ -0,0 +1,162 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from ...tl.tlobject import TLRequest
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeInputUser, TypeSecureValueError
class GetFullUserRequest(TLRequest):
CONSTRUCTOR_ID = 0xb60f5918
SUBCLASS_OF_ID = 0x83df9df5
def __init__(self, id: 'TypeInputUser'):
"""
:returns users.UserFull: Instance of UserFull.
"""
self.id = id
async def resolve(self, client, utils):
self.id = utils.get_input_user(await client.get_input_entity(self.id))
def to_dict(self):
return {
'_': 'GetFullUserRequest',
'id': self.id.to_dict() if isinstance(self.id, TLObject) else self.id
}
def _bytes(self):
return b''.join((
b'\x18Y\x0f\xb6',
self.id._bytes(),
))
@classmethod
def from_reader(cls, reader):
_id = reader.tgread_object()
return cls(id=_id)
class GetIsPremiumRequiredToContactRequest(TLRequest):
CONSTRUCTOR_ID = 0xa622aa10
SUBCLASS_OF_ID = 0x15dfc3f1
def __init__(self, id: List['TypeInputUser']):
"""
:returns Vector<Bool>: This type has no constructors.
"""
self.id = id
async def resolve(self, client, utils):
_tmp = []
for _x in self.id:
_tmp.append(utils.get_input_user(await client.get_input_entity(_x)))
self.id = _tmp
def to_dict(self):
return {
'_': 'GetIsPremiumRequiredToContactRequest',
'id': [] if self.id is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.id]
}
def _bytes(self):
return b''.join((
b'\x10\xaa"\xa6',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.id)),b''.join(x._bytes() for x in self.id),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_id = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_id.append(_x)
return cls(id=_id)
class GetUsersRequest(TLRequest):
CONSTRUCTOR_ID = 0xd91a548
SUBCLASS_OF_ID = 0x406da4d
def __init__(self, id: List['TypeInputUser']):
"""
:returns Vector<User>: This type has no constructors.
"""
self.id = id
async def resolve(self, client, utils):
_tmp = []
for _x in self.id:
_tmp.append(utils.get_input_user(await client.get_input_entity(_x)))
self.id = _tmp
def to_dict(self):
return {
'_': 'GetUsersRequest',
'id': [] if self.id is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.id]
}
def _bytes(self):
return b''.join((
b'H\xa5\x91\r',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.id)),b''.join(x._bytes() for x in self.id),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_id = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_id.append(_x)
return cls(id=_id)
class SetSecureValueErrorsRequest(TLRequest):
CONSTRUCTOR_ID = 0x90c894b5
SUBCLASS_OF_ID = 0xf5b399ac
def __init__(self, id: 'TypeInputUser', errors: List['TypeSecureValueError']):
"""
:returns Bool: This type has no constructors.
"""
self.id = id
self.errors = errors
async def resolve(self, client, utils):
self.id = utils.get_input_user(await client.get_input_entity(self.id))
def to_dict(self):
return {
'_': 'SetSecureValueErrorsRequest',
'id': self.id.to_dict() if isinstance(self.id, TLObject) else self.id,
'errors': [] if self.errors is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.errors]
}
def _bytes(self):
return b''.join((
b'\xb5\x94\xc8\x90',
self.id._bytes(),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.errors)),b''.join(x._bytes() for x in self.errors),
))
@classmethod
def from_reader(cls, reader):
_id = reader.tgread_object()
reader.read_int()
_errors = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_errors.append(_x)
return cls(id=_id, errors=_errors)

View File

@@ -0,0 +1,20 @@
from .. import types, alltlobjects
from ..custom.message import Message as _Message
class MessageEmpty(_Message, types.MessageEmpty):
pass
types.MessageEmpty = MessageEmpty
alltlobjects.tlobjects[MessageEmpty.CONSTRUCTOR_ID] = MessageEmpty
class MessageService(_Message, types.MessageService):
pass
types.MessageService = MessageService
alltlobjects.tlobjects[MessageService.CONSTRUCTOR_ID] = MessageService
class Message(_Message, types.Message):
pass
types.Message = Message
alltlobjects.tlobjects[Message.CONSTRUCTOR_ID] = Message

View File

@@ -0,0 +1,222 @@
import base64
import json
import struct
from datetime import datetime, date, timedelta, timezone
import time
_EPOCH_NAIVE = datetime(*time.gmtime(0)[:6])
_EPOCH_NAIVE_LOCAL = datetime(*time.localtime(0)[:6])
_EPOCH = _EPOCH_NAIVE.replace(tzinfo=timezone.utc)
def _datetime_to_timestamp(dt):
# If no timezone is specified, it is assumed to be in utc zone
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
# We use .total_seconds() method instead of simply dt.timestamp(),
# because on Windows the latter raises OSError on datetimes ~< datetime(1970,1,1)
secs = int((dt - _EPOCH).total_seconds())
# Make sure it's a valid signed 32 bit integer, as used by Telegram.
# This does make very large dates wrap around, but it's the best we
# can do with Telegram's limitations.
return struct.unpack('i', struct.pack('I', secs & 0xffffffff))[0]
def _json_default(value):
if isinstance(value, bytes):
return base64.b64encode(value).decode('ascii')
elif isinstance(value, datetime):
return value.isoformat()
else:
return repr(value)
class TLObject:
CONSTRUCTOR_ID = None
SUBCLASS_OF_ID = None
@staticmethod
def pretty_format(obj, indent=None):
"""
Pretty formats the given object as a string which is returned.
If indent is None, a single line will be returned.
"""
if indent is None:
if isinstance(obj, TLObject):
obj = obj.to_dict()
if isinstance(obj, dict):
return '{}({})'.format(obj.get('_', 'dict'), ', '.join(
'{}={}'.format(k, TLObject.pretty_format(v))
for k, v in obj.items() if k != '_'
))
elif isinstance(obj, str) or isinstance(obj, bytes):
return repr(obj)
elif hasattr(obj, '__iter__'):
return '[{}]'.format(
', '.join(TLObject.pretty_format(x) for x in obj)
)
else:
return repr(obj)
else:
result = []
if isinstance(obj, TLObject):
obj = obj.to_dict()
if isinstance(obj, dict):
result.append(obj.get('_', 'dict'))
result.append('(')
if obj:
result.append('\n')
indent += 1
for k, v in obj.items():
if k == '_':
continue
result.append('\t' * indent)
result.append(k)
result.append('=')
result.append(TLObject.pretty_format(v, indent))
result.append(',\n')
result.pop() # last ',\n'
indent -= 1
result.append('\n')
result.append('\t' * indent)
result.append(')')
elif isinstance(obj, str) or isinstance(obj, bytes):
result.append(repr(obj))
elif hasattr(obj, '__iter__'):
result.append('[\n')
indent += 1
for x in obj:
result.append('\t' * indent)
result.append(TLObject.pretty_format(x, indent))
result.append(',\n')
indent -= 1
result.append('\t' * indent)
result.append(']')
else:
result.append(repr(obj))
return ''.join(result)
@staticmethod
def serialize_bytes(data):
"""Write bytes by using Telegram guidelines"""
if not isinstance(data, bytes):
if isinstance(data, str):
data = data.encode('utf-8')
else:
raise TypeError(
'bytes or str expected, not {}'.format(type(data)))
r = []
if len(data) < 254:
padding = (len(data) + 1) % 4
if padding != 0:
padding = 4 - padding
r.append(bytes([len(data)]))
r.append(data)
else:
padding = len(data) % 4
if padding != 0:
padding = 4 - padding
r.append(bytes([
254,
len(data) % 256,
(len(data) >> 8) % 256,
(len(data) >> 16) % 256
]))
r.append(data)
r.append(bytes(padding))
return b''.join(r)
@staticmethod
def serialize_datetime(dt):
if not dt and not isinstance(dt, timedelta):
return b'\0\0\0\0'
if isinstance(dt, datetime):
dt = _datetime_to_timestamp(dt)
elif isinstance(dt, date):
dt = _datetime_to_timestamp(datetime(dt.year, dt.month, dt.day))
elif isinstance(dt, float):
dt = int(dt)
elif isinstance(dt, timedelta):
# Timezones are tricky. datetime.utcnow() + ... timestamp() works
dt = _datetime_to_timestamp(datetime.utcnow() + dt)
if isinstance(dt, int):
return struct.pack('<i', dt)
raise TypeError('Cannot interpret "{}" as a date.'.format(dt))
def __eq__(self, o):
return isinstance(o, type(self)) and self.to_dict() == o.to_dict()
def __ne__(self, o):
return not isinstance(o, type(self)) or self.to_dict() != o.to_dict()
def __str__(self):
return TLObject.pretty_format(self)
def stringify(self):
return TLObject.pretty_format(self, indent=0)
def to_dict(self):
raise NotImplementedError
def to_json(self, fp=None, default=_json_default, **kwargs):
"""
Represent the current `TLObject` as JSON.
If ``fp`` is given, the JSON will be dumped to said
file pointer, otherwise a JSON string will be returned.
Note that bytes and datetimes cannot be represented
in JSON, so if those are found, they will be base64
encoded and ISO-formatted, respectively, by default.
"""
d = self.to_dict()
if fp:
return json.dump(d, fp, default=default, **kwargs)
else:
return json.dumps(d, default=default, **kwargs)
def __bytes__(self):
try:
return self._bytes()
except AttributeError:
# If a type is wrong (e.g. expected `TLObject` but `int` was
# provided) it will try to access `._bytes()`, which will fail
# with `AttributeError`. This occurs in fact because the type
# was wrong, so raise the correct error type.
raise TypeError('a TLObject was expected but found something else')
# Custom objects will call `(...)._bytes()` and not `bytes(...)` so that
# if the wrong type is used (e.g. `int`) we won't try allocating a huge
# amount of data, which would cause a `MemoryError`.
def _bytes(self):
raise NotImplementedError
@classmethod
def from_reader(cls, reader):
raise NotImplementedError
class TLRequest(TLObject):
"""
Represents a content-related `TLObject` (a request that can be sent).
"""
@staticmethod
def read_result(reader):
return reader.tgread_object()
async def resolve(self, client, utils):
pass

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,777 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeUser
from ...tl.types.help import TypeTermsOfService
from ...tl.types.auth import TypeAuthorization, TypeCodeType, TypeSentCodeType
class Authorization(TLObject):
CONSTRUCTOR_ID = 0x2ea2c0d4
SUBCLASS_OF_ID = 0xb9e04e39
def __init__(self, user: 'TypeUser', setup_password_required: Optional[bool]=None, otherwise_relogin_days: Optional[int]=None, tmp_sessions: Optional[int]=None, future_auth_token: Optional[bytes]=None):
"""
Constructor for auth.Authorization: Instance of either Authorization, AuthorizationSignUpRequired.
"""
self.user = user
self.setup_password_required = setup_password_required
self.otherwise_relogin_days = otherwise_relogin_days
self.tmp_sessions = tmp_sessions
self.future_auth_token = future_auth_token
def to_dict(self):
return {
'_': 'Authorization',
'user': self.user.to_dict() if isinstance(self.user, TLObject) else self.user,
'setup_password_required': self.setup_password_required,
'otherwise_relogin_days': self.otherwise_relogin_days,
'tmp_sessions': self.tmp_sessions,
'future_auth_token': self.future_auth_token
}
def _bytes(self):
assert ((self.setup_password_required or self.setup_password_required is not None) and (self.otherwise_relogin_days or self.otherwise_relogin_days is not None)) or ((self.setup_password_required is None or self.setup_password_required is False) and (self.otherwise_relogin_days is None or self.otherwise_relogin_days is False)), 'setup_password_required, otherwise_relogin_days parameters must all be False-y (like None) or all me True-y'
return b''.join((
b'\xd4\xc0\xa2.',
struct.pack('<I', (0 if self.setup_password_required is None or self.setup_password_required is False else 2) | (0 if self.otherwise_relogin_days is None or self.otherwise_relogin_days is False else 2) | (0 if self.tmp_sessions is None or self.tmp_sessions is False else 1) | (0 if self.future_auth_token is None or self.future_auth_token is False else 4)),
b'' if self.otherwise_relogin_days is None or self.otherwise_relogin_days is False else (struct.pack('<i', self.otherwise_relogin_days)),
b'' if self.tmp_sessions is None or self.tmp_sessions is False else (struct.pack('<i', self.tmp_sessions)),
b'' if self.future_auth_token is None or self.future_auth_token is False else (self.serialize_bytes(self.future_auth_token)),
self.user._bytes(),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_setup_password_required = bool(flags & 2)
if flags & 2:
_otherwise_relogin_days = reader.read_int()
else:
_otherwise_relogin_days = None
if flags & 1:
_tmp_sessions = reader.read_int()
else:
_tmp_sessions = None
if flags & 4:
_future_auth_token = reader.tgread_bytes()
else:
_future_auth_token = None
_user = reader.tgread_object()
return cls(user=_user, setup_password_required=_setup_password_required, otherwise_relogin_days=_otherwise_relogin_days, tmp_sessions=_tmp_sessions, future_auth_token=_future_auth_token)
class AuthorizationSignUpRequired(TLObject):
CONSTRUCTOR_ID = 0x44747e9a
SUBCLASS_OF_ID = 0xb9e04e39
def __init__(self, terms_of_service: Optional['TypeTermsOfService']=None):
"""
Constructor for auth.Authorization: Instance of either Authorization, AuthorizationSignUpRequired.
"""
self.terms_of_service = terms_of_service
def to_dict(self):
return {
'_': 'AuthorizationSignUpRequired',
'terms_of_service': self.terms_of_service.to_dict() if isinstance(self.terms_of_service, TLObject) else self.terms_of_service
}
def _bytes(self):
return b''.join((
b'\x9a~tD',
struct.pack('<I', (0 if self.terms_of_service is None or self.terms_of_service is False else 1)),
b'' if self.terms_of_service is None or self.terms_of_service is False else (self.terms_of_service._bytes()),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
if flags & 1:
_terms_of_service = reader.tgread_object()
else:
_terms_of_service = None
return cls(terms_of_service=_terms_of_service)
class CodeTypeCall(TLObject):
CONSTRUCTOR_ID = 0x741cd3e3
SUBCLASS_OF_ID = 0xb3f3e401
def to_dict(self):
return {
'_': 'CodeTypeCall'
}
def _bytes(self):
return b''.join((
b'\xe3\xd3\x1ct',
))
@classmethod
def from_reader(cls, reader):
return cls()
class CodeTypeFlashCall(TLObject):
CONSTRUCTOR_ID = 0x226ccefb
SUBCLASS_OF_ID = 0xb3f3e401
def to_dict(self):
return {
'_': 'CodeTypeFlashCall'
}
def _bytes(self):
return b''.join((
b'\xfb\xcel"',
))
@classmethod
def from_reader(cls, reader):
return cls()
class CodeTypeFragmentSms(TLObject):
CONSTRUCTOR_ID = 0x6ed998c
SUBCLASS_OF_ID = 0xb3f3e401
def to_dict(self):
return {
'_': 'CodeTypeFragmentSms'
}
def _bytes(self):
return b''.join((
b'\x8c\x99\xed\x06',
))
@classmethod
def from_reader(cls, reader):
return cls()
class CodeTypeMissedCall(TLObject):
CONSTRUCTOR_ID = 0xd61ad6ee
SUBCLASS_OF_ID = 0xb3f3e401
def to_dict(self):
return {
'_': 'CodeTypeMissedCall'
}
def _bytes(self):
return b''.join((
b'\xee\xd6\x1a\xd6',
))
@classmethod
def from_reader(cls, reader):
return cls()
class CodeTypeSms(TLObject):
CONSTRUCTOR_ID = 0x72a3158c
SUBCLASS_OF_ID = 0xb3f3e401
def to_dict(self):
return {
'_': 'CodeTypeSms'
}
def _bytes(self):
return b''.join((
b'\x8c\x15\xa3r',
))
@classmethod
def from_reader(cls, reader):
return cls()
class ExportedAuthorization(TLObject):
CONSTRUCTOR_ID = 0xb434e2b8
SUBCLASS_OF_ID = 0x5fd1ec51
def __init__(self, id: int, bytes: bytes):
"""
Constructor for auth.ExportedAuthorization: Instance of ExportedAuthorization.
"""
self.id = id
self.bytes = bytes
def to_dict(self):
return {
'_': 'ExportedAuthorization',
'id': self.id,
'bytes': self.bytes
}
def _bytes(self):
return b''.join((
b'\xb8\xe24\xb4',
struct.pack('<q', self.id),
self.serialize_bytes(self.bytes),
))
@classmethod
def from_reader(cls, reader):
_id = reader.read_long()
_bytes = reader.tgread_bytes()
return cls(id=_id, bytes=_bytes)
class LoggedOut(TLObject):
CONSTRUCTOR_ID = 0xc3a2835f
SUBCLASS_OF_ID = 0xa804315
def __init__(self, future_auth_token: Optional[bytes]=None):
"""
Constructor for auth.LoggedOut: Instance of LoggedOut.
"""
self.future_auth_token = future_auth_token
def to_dict(self):
return {
'_': 'LoggedOut',
'future_auth_token': self.future_auth_token
}
def _bytes(self):
return b''.join((
b'_\x83\xa2\xc3',
struct.pack('<I', (0 if self.future_auth_token is None or self.future_auth_token is False else 1)),
b'' if self.future_auth_token is None or self.future_auth_token is False else (self.serialize_bytes(self.future_auth_token)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
if flags & 1:
_future_auth_token = reader.tgread_bytes()
else:
_future_auth_token = None
return cls(future_auth_token=_future_auth_token)
class LoginToken(TLObject):
CONSTRUCTOR_ID = 0x629f1980
SUBCLASS_OF_ID = 0x6b55f636
def __init__(self, expires: Optional[datetime], token: bytes):
"""
Constructor for auth.LoginToken: Instance of either LoginToken, LoginTokenMigrateTo, LoginTokenSuccess.
"""
self.expires = expires
self.token = token
def to_dict(self):
return {
'_': 'LoginToken',
'expires': self.expires,
'token': self.token
}
def _bytes(self):
return b''.join((
b'\x80\x19\x9fb',
self.serialize_datetime(self.expires),
self.serialize_bytes(self.token),
))
@classmethod
def from_reader(cls, reader):
_expires = reader.tgread_date()
_token = reader.tgread_bytes()
return cls(expires=_expires, token=_token)
class LoginTokenMigrateTo(TLObject):
CONSTRUCTOR_ID = 0x68e9916
SUBCLASS_OF_ID = 0x6b55f636
def __init__(self, dc_id: int, token: bytes):
"""
Constructor for auth.LoginToken: Instance of either LoginToken, LoginTokenMigrateTo, LoginTokenSuccess.
"""
self.dc_id = dc_id
self.token = token
def to_dict(self):
return {
'_': 'LoginTokenMigrateTo',
'dc_id': self.dc_id,
'token': self.token
}
def _bytes(self):
return b''.join((
b'\x16\x99\x8e\x06',
struct.pack('<i', self.dc_id),
self.serialize_bytes(self.token),
))
@classmethod
def from_reader(cls, reader):
_dc_id = reader.read_int()
_token = reader.tgread_bytes()
return cls(dc_id=_dc_id, token=_token)
class LoginTokenSuccess(TLObject):
CONSTRUCTOR_ID = 0x390d5c5e
SUBCLASS_OF_ID = 0x6b55f636
def __init__(self, authorization: 'TypeAuthorization'):
"""
Constructor for auth.LoginToken: Instance of either LoginToken, LoginTokenMigrateTo, LoginTokenSuccess.
"""
self.authorization = authorization
def to_dict(self):
return {
'_': 'LoginTokenSuccess',
'authorization': self.authorization.to_dict() if isinstance(self.authorization, TLObject) else self.authorization
}
def _bytes(self):
return b''.join((
b'^\\\r9',
self.authorization._bytes(),
))
@classmethod
def from_reader(cls, reader):
_authorization = reader.tgread_object()
return cls(authorization=_authorization)
class PasswordRecovery(TLObject):
CONSTRUCTOR_ID = 0x137948a5
SUBCLASS_OF_ID = 0xfa72d43a
def __init__(self, email_pattern: str):
"""
Constructor for auth.PasswordRecovery: Instance of PasswordRecovery.
"""
self.email_pattern = email_pattern
def to_dict(self):
return {
'_': 'PasswordRecovery',
'email_pattern': self.email_pattern
}
def _bytes(self):
return b''.join((
b'\xa5Hy\x13',
self.serialize_bytes(self.email_pattern),
))
@classmethod
def from_reader(cls, reader):
_email_pattern = reader.tgread_string()
return cls(email_pattern=_email_pattern)
class SentCode(TLObject):
CONSTRUCTOR_ID = 0x5e002502
SUBCLASS_OF_ID = 0x6ce87081
def __init__(self, type: 'TypeSentCodeType', phone_code_hash: str, next_type: Optional['TypeCodeType']=None, timeout: Optional[int]=None):
"""
Constructor for auth.SentCode: Instance of either SentCode, SentCodeSuccess.
"""
self.type = type
self.phone_code_hash = phone_code_hash
self.next_type = next_type
self.timeout = timeout
def to_dict(self):
return {
'_': 'SentCode',
'type': self.type.to_dict() if isinstance(self.type, TLObject) else self.type,
'phone_code_hash': self.phone_code_hash,
'next_type': self.next_type.to_dict() if isinstance(self.next_type, TLObject) else self.next_type,
'timeout': self.timeout
}
def _bytes(self):
return b''.join((
b'\x02%\x00^',
struct.pack('<I', (0 if self.next_type is None or self.next_type is False else 2) | (0 if self.timeout is None or self.timeout is False else 4)),
self.type._bytes(),
self.serialize_bytes(self.phone_code_hash),
b'' if self.next_type is None or self.next_type is False else (self.next_type._bytes()),
b'' if self.timeout is None or self.timeout is False else (struct.pack('<i', self.timeout)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_type = reader.tgread_object()
_phone_code_hash = reader.tgread_string()
if flags & 2:
_next_type = reader.tgread_object()
else:
_next_type = None
if flags & 4:
_timeout = reader.read_int()
else:
_timeout = None
return cls(type=_type, phone_code_hash=_phone_code_hash, next_type=_next_type, timeout=_timeout)
class SentCodeSuccess(TLObject):
CONSTRUCTOR_ID = 0x2390fe44
SUBCLASS_OF_ID = 0x6ce87081
def __init__(self, authorization: 'TypeAuthorization'):
"""
Constructor for auth.SentCode: Instance of either SentCode, SentCodeSuccess.
"""
self.authorization = authorization
def to_dict(self):
return {
'_': 'SentCodeSuccess',
'authorization': self.authorization.to_dict() if isinstance(self.authorization, TLObject) else self.authorization
}
def _bytes(self):
return b''.join((
b'D\xfe\x90#',
self.authorization._bytes(),
))
@classmethod
def from_reader(cls, reader):
_authorization = reader.tgread_object()
return cls(authorization=_authorization)
class SentCodeTypeApp(TLObject):
CONSTRUCTOR_ID = 0x3dbb5986
SUBCLASS_OF_ID = 0xff5b158e
def __init__(self, length: int):
"""
Constructor for auth.SentCodeType: Instance of either SentCodeTypeApp, SentCodeTypeSms, SentCodeTypeCall, SentCodeTypeFlashCall, SentCodeTypeMissedCall, SentCodeTypeEmailCode, SentCodeTypeSetUpEmailRequired, SentCodeTypeFragmentSms, SentCodeTypeFirebaseSms.
"""
self.length = length
def to_dict(self):
return {
'_': 'SentCodeTypeApp',
'length': self.length
}
def _bytes(self):
return b''.join((
b'\x86Y\xbb=',
struct.pack('<i', self.length),
))
@classmethod
def from_reader(cls, reader):
_length = reader.read_int()
return cls(length=_length)
class SentCodeTypeCall(TLObject):
CONSTRUCTOR_ID = 0x5353e5a7
SUBCLASS_OF_ID = 0xff5b158e
def __init__(self, length: int):
"""
Constructor for auth.SentCodeType: Instance of either SentCodeTypeApp, SentCodeTypeSms, SentCodeTypeCall, SentCodeTypeFlashCall, SentCodeTypeMissedCall, SentCodeTypeEmailCode, SentCodeTypeSetUpEmailRequired, SentCodeTypeFragmentSms, SentCodeTypeFirebaseSms.
"""
self.length = length
def to_dict(self):
return {
'_': 'SentCodeTypeCall',
'length': self.length
}
def _bytes(self):
return b''.join((
b'\xa7\xe5SS',
struct.pack('<i', self.length),
))
@classmethod
def from_reader(cls, reader):
_length = reader.read_int()
return cls(length=_length)
class SentCodeTypeEmailCode(TLObject):
CONSTRUCTOR_ID = 0xf450f59b
SUBCLASS_OF_ID = 0xff5b158e
def __init__(self, email_pattern: str, length: int, apple_signin_allowed: Optional[bool]=None, google_signin_allowed: Optional[bool]=None, reset_available_period: Optional[int]=None, reset_pending_date: Optional[datetime]=None):
"""
Constructor for auth.SentCodeType: Instance of either SentCodeTypeApp, SentCodeTypeSms, SentCodeTypeCall, SentCodeTypeFlashCall, SentCodeTypeMissedCall, SentCodeTypeEmailCode, SentCodeTypeSetUpEmailRequired, SentCodeTypeFragmentSms, SentCodeTypeFirebaseSms.
"""
self.email_pattern = email_pattern
self.length = length
self.apple_signin_allowed = apple_signin_allowed
self.google_signin_allowed = google_signin_allowed
self.reset_available_period = reset_available_period
self.reset_pending_date = reset_pending_date
def to_dict(self):
return {
'_': 'SentCodeTypeEmailCode',
'email_pattern': self.email_pattern,
'length': self.length,
'apple_signin_allowed': self.apple_signin_allowed,
'google_signin_allowed': self.google_signin_allowed,
'reset_available_period': self.reset_available_period,
'reset_pending_date': self.reset_pending_date
}
def _bytes(self):
return b''.join((
b'\x9b\xf5P\xf4',
struct.pack('<I', (0 if self.apple_signin_allowed is None or self.apple_signin_allowed is False else 1) | (0 if self.google_signin_allowed is None or self.google_signin_allowed is False else 2) | (0 if self.reset_available_period is None or self.reset_available_period is False else 8) | (0 if self.reset_pending_date is None or self.reset_pending_date is False else 16)),
self.serialize_bytes(self.email_pattern),
struct.pack('<i', self.length),
b'' if self.reset_available_period is None or self.reset_available_period is False else (struct.pack('<i', self.reset_available_period)),
b'' if self.reset_pending_date is None or self.reset_pending_date is False else (self.serialize_datetime(self.reset_pending_date)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_apple_signin_allowed = bool(flags & 1)
_google_signin_allowed = bool(flags & 2)
_email_pattern = reader.tgread_string()
_length = reader.read_int()
if flags & 8:
_reset_available_period = reader.read_int()
else:
_reset_available_period = None
if flags & 16:
_reset_pending_date = reader.tgread_date()
else:
_reset_pending_date = None
return cls(email_pattern=_email_pattern, length=_length, apple_signin_allowed=_apple_signin_allowed, google_signin_allowed=_google_signin_allowed, reset_available_period=_reset_available_period, reset_pending_date=_reset_pending_date)
class SentCodeTypeFirebaseSms(TLObject):
CONSTRUCTOR_ID = 0xe57b1432
SUBCLASS_OF_ID = 0xff5b158e
def __init__(self, length: int, nonce: Optional[bytes]=None, receipt: Optional[str]=None, push_timeout: Optional[int]=None):
"""
Constructor for auth.SentCodeType: Instance of either SentCodeTypeApp, SentCodeTypeSms, SentCodeTypeCall, SentCodeTypeFlashCall, SentCodeTypeMissedCall, SentCodeTypeEmailCode, SentCodeTypeSetUpEmailRequired, SentCodeTypeFragmentSms, SentCodeTypeFirebaseSms.
"""
self.length = length
self.nonce = nonce
self.receipt = receipt
self.push_timeout = push_timeout
def to_dict(self):
return {
'_': 'SentCodeTypeFirebaseSms',
'length': self.length,
'nonce': self.nonce,
'receipt': self.receipt,
'push_timeout': self.push_timeout
}
def _bytes(self):
assert ((self.receipt or self.receipt is not None) and (self.push_timeout or self.push_timeout is not None)) or ((self.receipt is None or self.receipt is False) and (self.push_timeout is None or self.push_timeout is False)), 'receipt, push_timeout parameters must all be False-y (like None) or all me True-y'
return b''.join((
b'2\x14{\xe5',
struct.pack('<I', (0 if self.nonce is None or self.nonce is False else 1) | (0 if self.receipt is None or self.receipt is False else 2) | (0 if self.push_timeout is None or self.push_timeout is False else 2)),
b'' if self.nonce is None or self.nonce is False else (self.serialize_bytes(self.nonce)),
b'' if self.receipt is None or self.receipt is False else (self.serialize_bytes(self.receipt)),
b'' if self.push_timeout is None or self.push_timeout is False else (struct.pack('<i', self.push_timeout)),
struct.pack('<i', self.length),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
if flags & 1:
_nonce = reader.tgread_bytes()
else:
_nonce = None
if flags & 2:
_receipt = reader.tgread_string()
else:
_receipt = None
if flags & 2:
_push_timeout = reader.read_int()
else:
_push_timeout = None
_length = reader.read_int()
return cls(length=_length, nonce=_nonce, receipt=_receipt, push_timeout=_push_timeout)
class SentCodeTypeFlashCall(TLObject):
CONSTRUCTOR_ID = 0xab03c6d9
SUBCLASS_OF_ID = 0xff5b158e
def __init__(self, pattern: str):
"""
Constructor for auth.SentCodeType: Instance of either SentCodeTypeApp, SentCodeTypeSms, SentCodeTypeCall, SentCodeTypeFlashCall, SentCodeTypeMissedCall, SentCodeTypeEmailCode, SentCodeTypeSetUpEmailRequired, SentCodeTypeFragmentSms, SentCodeTypeFirebaseSms.
"""
self.pattern = pattern
def to_dict(self):
return {
'_': 'SentCodeTypeFlashCall',
'pattern': self.pattern
}
def _bytes(self):
return b''.join((
b'\xd9\xc6\x03\xab',
self.serialize_bytes(self.pattern),
))
@classmethod
def from_reader(cls, reader):
_pattern = reader.tgread_string()
return cls(pattern=_pattern)
class SentCodeTypeFragmentSms(TLObject):
CONSTRUCTOR_ID = 0xd9565c39
SUBCLASS_OF_ID = 0xff5b158e
def __init__(self, url: str, length: int):
"""
Constructor for auth.SentCodeType: Instance of either SentCodeTypeApp, SentCodeTypeSms, SentCodeTypeCall, SentCodeTypeFlashCall, SentCodeTypeMissedCall, SentCodeTypeEmailCode, SentCodeTypeSetUpEmailRequired, SentCodeTypeFragmentSms, SentCodeTypeFirebaseSms.
"""
self.url = url
self.length = length
def to_dict(self):
return {
'_': 'SentCodeTypeFragmentSms',
'url': self.url,
'length': self.length
}
def _bytes(self):
return b''.join((
b'9\\V\xd9',
self.serialize_bytes(self.url),
struct.pack('<i', self.length),
))
@classmethod
def from_reader(cls, reader):
_url = reader.tgread_string()
_length = reader.read_int()
return cls(url=_url, length=_length)
class SentCodeTypeMissedCall(TLObject):
CONSTRUCTOR_ID = 0x82006484
SUBCLASS_OF_ID = 0xff5b158e
def __init__(self, prefix: str, length: int):
"""
Constructor for auth.SentCodeType: Instance of either SentCodeTypeApp, SentCodeTypeSms, SentCodeTypeCall, SentCodeTypeFlashCall, SentCodeTypeMissedCall, SentCodeTypeEmailCode, SentCodeTypeSetUpEmailRequired, SentCodeTypeFragmentSms, SentCodeTypeFirebaseSms.
"""
self.prefix = prefix
self.length = length
def to_dict(self):
return {
'_': 'SentCodeTypeMissedCall',
'prefix': self.prefix,
'length': self.length
}
def _bytes(self):
return b''.join((
b'\x84d\x00\x82',
self.serialize_bytes(self.prefix),
struct.pack('<i', self.length),
))
@classmethod
def from_reader(cls, reader):
_prefix = reader.tgread_string()
_length = reader.read_int()
return cls(prefix=_prefix, length=_length)
class SentCodeTypeSetUpEmailRequired(TLObject):
CONSTRUCTOR_ID = 0xa5491dea
SUBCLASS_OF_ID = 0xff5b158e
def __init__(self, apple_signin_allowed: Optional[bool]=None, google_signin_allowed: Optional[bool]=None):
"""
Constructor for auth.SentCodeType: Instance of either SentCodeTypeApp, SentCodeTypeSms, SentCodeTypeCall, SentCodeTypeFlashCall, SentCodeTypeMissedCall, SentCodeTypeEmailCode, SentCodeTypeSetUpEmailRequired, SentCodeTypeFragmentSms, SentCodeTypeFirebaseSms.
"""
self.apple_signin_allowed = apple_signin_allowed
self.google_signin_allowed = google_signin_allowed
def to_dict(self):
return {
'_': 'SentCodeTypeSetUpEmailRequired',
'apple_signin_allowed': self.apple_signin_allowed,
'google_signin_allowed': self.google_signin_allowed
}
def _bytes(self):
return b''.join((
b'\xea\x1dI\xa5',
struct.pack('<I', (0 if self.apple_signin_allowed is None or self.apple_signin_allowed is False else 1) | (0 if self.google_signin_allowed is None or self.google_signin_allowed is False else 2)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_apple_signin_allowed = bool(flags & 1)
_google_signin_allowed = bool(flags & 2)
return cls(apple_signin_allowed=_apple_signin_allowed, google_signin_allowed=_google_signin_allowed)
class SentCodeTypeSms(TLObject):
CONSTRUCTOR_ID = 0xc000bba2
SUBCLASS_OF_ID = 0xff5b158e
def __init__(self, length: int):
"""
Constructor for auth.SentCodeType: Instance of either SentCodeTypeApp, SentCodeTypeSms, SentCodeTypeCall, SentCodeTypeFlashCall, SentCodeTypeMissedCall, SentCodeTypeEmailCode, SentCodeTypeSetUpEmailRequired, SentCodeTypeFragmentSms, SentCodeTypeFirebaseSms.
"""
self.length = length
def to_dict(self):
return {
'_': 'SentCodeTypeSms',
'length': self.length
}
def _bytes(self):
return b''.join((
b'\xa2\xbb\x00\xc0',
struct.pack('<i', self.length),
))
@classmethod
def from_reader(cls, reader):
_length = reader.read_int()
return cls(length=_length)

View File

@@ -0,0 +1,43 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
class BotInfo(TLObject):
CONSTRUCTOR_ID = 0xe8a775b0
SUBCLASS_OF_ID = 0xca7b2235
def __init__(self, name: str, about: str, description: str):
"""
Constructor for bots.BotInfo: Instance of BotInfo.
"""
self.name = name
self.about = about
self.description = description
def to_dict(self):
return {
'_': 'BotInfo',
'name': self.name,
'about': self.about,
'description': self.description
}
def _bytes(self):
return b''.join((
b'\xb0u\xa7\xe8',
self.serialize_bytes(self.name),
self.serialize_bytes(self.about),
self.serialize_bytes(self.description),
))
@classmethod
def from_reader(cls, reader):
_name = reader.tgread_string()
_about = reader.tgread_string()
_description = reader.tgread_string()
return cls(name=_name, about=_about, description=_description)

View File

@@ -0,0 +1,232 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeChannelAdminLogEvent, TypeChannelParticipant, TypeChat, TypeSendAsPeer, TypeUser
class AdminLogResults(TLObject):
CONSTRUCTOR_ID = 0xed8af74d
SUBCLASS_OF_ID = 0x51f076bc
def __init__(self, events: List['TypeChannelAdminLogEvent'], chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for channels.AdminLogResults: Instance of AdminLogResults.
"""
self.events = events
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'AdminLogResults',
'events': [] if self.events is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.events],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'M\xf7\x8a\xed',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.events)),b''.join(x._bytes() for x in self.events),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_events = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_events.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(events=_events, chats=_chats, users=_users)
class ChannelParticipant(TLObject):
CONSTRUCTOR_ID = 0xdfb80317
SUBCLASS_OF_ID = 0x6658151a
def __init__(self, participant: 'TypeChannelParticipant', chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for channels.ChannelParticipant: Instance of ChannelParticipant.
"""
self.participant = participant
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'ChannelParticipant',
'participant': self.participant.to_dict() if isinstance(self.participant, TLObject) else self.participant,
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\x17\x03\xb8\xdf',
self.participant._bytes(),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
_participant = reader.tgread_object()
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(participant=_participant, chats=_chats, users=_users)
class ChannelParticipants(TLObject):
CONSTRUCTOR_ID = 0x9ab0feaf
SUBCLASS_OF_ID = 0xe60a6e64
def __init__(self, count: int, participants: List['TypeChannelParticipant'], chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for channels.ChannelParticipants: Instance of either ChannelParticipants, ChannelParticipantsNotModified.
"""
self.count = count
self.participants = participants
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'ChannelParticipants',
'count': self.count,
'participants': [] if self.participants is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.participants],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\xaf\xfe\xb0\x9a',
struct.pack('<i', self.count),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.participants)),b''.join(x._bytes() for x in self.participants),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
_count = reader.read_int()
reader.read_int()
_participants = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_participants.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(count=_count, participants=_participants, chats=_chats, users=_users)
class ChannelParticipantsNotModified(TLObject):
CONSTRUCTOR_ID = 0xf0173fe9
SUBCLASS_OF_ID = 0xe60a6e64
def to_dict(self):
return {
'_': 'ChannelParticipantsNotModified'
}
def _bytes(self):
return b''.join((
b'\xe9?\x17\xf0',
))
@classmethod
def from_reader(cls, reader):
return cls()
class SendAsPeers(TLObject):
CONSTRUCTOR_ID = 0xf496b0c6
SUBCLASS_OF_ID = 0x38cb8d21
def __init__(self, peers: List['TypeSendAsPeer'], chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for channels.SendAsPeers: Instance of SendAsPeers.
"""
self.peers = peers
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'SendAsPeers',
'peers': [] if self.peers is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.peers],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\xc6\xb0\x96\xf4',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.peers)),b''.join(x._bytes() for x in self.peers),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_peers = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_peers.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(peers=_peers, chats=_chats, users=_users)

View File

@@ -0,0 +1,273 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeChat, TypeDialogFilter, TypeExportedChatlistInvite, TypePeer, TypeUser
class ChatlistInvite(TLObject):
CONSTRUCTOR_ID = 0x1dcd839d
SUBCLASS_OF_ID = 0x41720e75
def __init__(self, title: str, peers: List['TypePeer'], chats: List['TypeChat'], users: List['TypeUser'], emoticon: Optional[str]=None):
"""
Constructor for chatlists.ChatlistInvite: Instance of either ChatlistInviteAlready, ChatlistInvite.
"""
self.title = title
self.peers = peers
self.chats = chats
self.users = users
self.emoticon = emoticon
def to_dict(self):
return {
'_': 'ChatlistInvite',
'title': self.title,
'peers': [] if self.peers is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.peers],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users],
'emoticon': self.emoticon
}
def _bytes(self):
return b''.join((
b'\x9d\x83\xcd\x1d',
struct.pack('<I', (0 if self.emoticon is None or self.emoticon is False else 1)),
self.serialize_bytes(self.title),
b'' if self.emoticon is None or self.emoticon is False else (self.serialize_bytes(self.emoticon)),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.peers)),b''.join(x._bytes() for x in self.peers),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_title = reader.tgread_string()
if flags & 1:
_emoticon = reader.tgread_string()
else:
_emoticon = None
reader.read_int()
_peers = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_peers.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(title=_title, peers=_peers, chats=_chats, users=_users, emoticon=_emoticon)
class ChatlistInviteAlready(TLObject):
CONSTRUCTOR_ID = 0xfa87f659
SUBCLASS_OF_ID = 0x41720e75
def __init__(self, filter_id: int, missing_peers: List['TypePeer'], already_peers: List['TypePeer'], chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for chatlists.ChatlistInvite: Instance of either ChatlistInviteAlready, ChatlistInvite.
"""
self.filter_id = filter_id
self.missing_peers = missing_peers
self.already_peers = already_peers
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'ChatlistInviteAlready',
'filter_id': self.filter_id,
'missing_peers': [] if self.missing_peers is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.missing_peers],
'already_peers': [] if self.already_peers is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.already_peers],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'Y\xf6\x87\xfa',
struct.pack('<i', self.filter_id),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.missing_peers)),b''.join(x._bytes() for x in self.missing_peers),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.already_peers)),b''.join(x._bytes() for x in self.already_peers),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
_filter_id = reader.read_int()
reader.read_int()
_missing_peers = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_missing_peers.append(_x)
reader.read_int()
_already_peers = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_already_peers.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(filter_id=_filter_id, missing_peers=_missing_peers, already_peers=_already_peers, chats=_chats, users=_users)
class ChatlistUpdates(TLObject):
CONSTRUCTOR_ID = 0x93bd878d
SUBCLASS_OF_ID = 0x7d1641ea
def __init__(self, missing_peers: List['TypePeer'], chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for chatlists.ChatlistUpdates: Instance of ChatlistUpdates.
"""
self.missing_peers = missing_peers
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'ChatlistUpdates',
'missing_peers': [] if self.missing_peers is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.missing_peers],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\x8d\x87\xbd\x93',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.missing_peers)),b''.join(x._bytes() for x in self.missing_peers),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_missing_peers = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_missing_peers.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(missing_peers=_missing_peers, chats=_chats, users=_users)
class ExportedChatlistInvite(TLObject):
CONSTRUCTOR_ID = 0x10e6e3a6
SUBCLASS_OF_ID = 0xc2694ee9
def __init__(self, filter: 'TypeDialogFilter', invite: 'TypeExportedChatlistInvite'):
"""
Constructor for chatlists.ExportedChatlistInvite: Instance of ExportedChatlistInvite.
"""
self.filter = filter
self.invite = invite
def to_dict(self):
return {
'_': 'ExportedChatlistInvite',
'filter': self.filter.to_dict() if isinstance(self.filter, TLObject) else self.filter,
'invite': self.invite.to_dict() if isinstance(self.invite, TLObject) else self.invite
}
def _bytes(self):
return b''.join((
b'\xa6\xe3\xe6\x10',
self.filter._bytes(),
self.invite._bytes(),
))
@classmethod
def from_reader(cls, reader):
_filter = reader.tgread_object()
_invite = reader.tgread_object()
return cls(filter=_filter, invite=_invite)
class ExportedInvites(TLObject):
CONSTRUCTOR_ID = 0x10ab6dc7
SUBCLASS_OF_ID = 0xe6c209c0
def __init__(self, invites: List['TypeExportedChatlistInvite'], chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for chatlists.ExportedInvites: Instance of ExportedInvites.
"""
self.invites = invites
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'ExportedInvites',
'invites': [] if self.invites is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.invites],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\xc7m\xab\x10',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.invites)),b''.join(x._bytes() for x in self.invites),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_invites = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_invites.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(invites=_invites, chats=_chats, users=_users)

View File

@@ -0,0 +1,436 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeChat, TypeContact, TypeImportedContact, TypePeer, TypePeerBlocked, TypePopularContact, TypeTopPeerCategoryPeers, TypeUser
class Blocked(TLObject):
CONSTRUCTOR_ID = 0xade1591
SUBCLASS_OF_ID = 0xffba4f4f
def __init__(self, blocked: List['TypePeerBlocked'], chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for contacts.Blocked: Instance of either Blocked, BlockedSlice.
"""
self.blocked = blocked
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'Blocked',
'blocked': [] if self.blocked is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.blocked],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\x91\x15\xde\n',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.blocked)),b''.join(x._bytes() for x in self.blocked),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_blocked = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_blocked.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(blocked=_blocked, chats=_chats, users=_users)
class BlockedSlice(TLObject):
CONSTRUCTOR_ID = 0xe1664194
SUBCLASS_OF_ID = 0xffba4f4f
def __init__(self, count: int, blocked: List['TypePeerBlocked'], chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for contacts.Blocked: Instance of either Blocked, BlockedSlice.
"""
self.count = count
self.blocked = blocked
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'BlockedSlice',
'count': self.count,
'blocked': [] if self.blocked is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.blocked],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\x94Af\xe1',
struct.pack('<i', self.count),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.blocked)),b''.join(x._bytes() for x in self.blocked),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
_count = reader.read_int()
reader.read_int()
_blocked = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_blocked.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(count=_count, blocked=_blocked, chats=_chats, users=_users)
class Contacts(TLObject):
CONSTRUCTOR_ID = 0xeae87e42
SUBCLASS_OF_ID = 0x38be25f6
def __init__(self, contacts: List['TypeContact'], saved_count: int, users: List['TypeUser']):
"""
Constructor for contacts.Contacts: Instance of either ContactsNotModified, Contacts.
"""
self.contacts = contacts
self.saved_count = saved_count
self.users = users
def to_dict(self):
return {
'_': 'Contacts',
'contacts': [] if self.contacts is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.contacts],
'saved_count': self.saved_count,
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'B~\xe8\xea',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.contacts)),b''.join(x._bytes() for x in self.contacts),
struct.pack('<i', self.saved_count),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_contacts = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_contacts.append(_x)
_saved_count = reader.read_int()
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(contacts=_contacts, saved_count=_saved_count, users=_users)
class ContactsNotModified(TLObject):
CONSTRUCTOR_ID = 0xb74ba9d2
SUBCLASS_OF_ID = 0x38be25f6
def to_dict(self):
return {
'_': 'ContactsNotModified'
}
def _bytes(self):
return b''.join((
b'\xd2\xa9K\xb7',
))
@classmethod
def from_reader(cls, reader):
return cls()
class Found(TLObject):
CONSTRUCTOR_ID = 0xb3134d9d
SUBCLASS_OF_ID = 0x4386a2e3
def __init__(self, my_results: List['TypePeer'], results: List['TypePeer'], chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for contacts.Found: Instance of Found.
"""
self.my_results = my_results
self.results = results
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'Found',
'my_results': [] if self.my_results is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.my_results],
'results': [] if self.results is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.results],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\x9dM\x13\xb3',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.my_results)),b''.join(x._bytes() for x in self.my_results),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.results)),b''.join(x._bytes() for x in self.results),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_my_results = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_my_results.append(_x)
reader.read_int()
_results = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_results.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(my_results=_my_results, results=_results, chats=_chats, users=_users)
class ImportedContacts(TLObject):
CONSTRUCTOR_ID = 0x77d01c3b
SUBCLASS_OF_ID = 0x8172ad93
def __init__(self, imported: List['TypeImportedContact'], popular_invites: List['TypePopularContact'], retry_contacts: List[int], users: List['TypeUser']):
"""
Constructor for contacts.ImportedContacts: Instance of ImportedContacts.
"""
self.imported = imported
self.popular_invites = popular_invites
self.retry_contacts = retry_contacts
self.users = users
def to_dict(self):
return {
'_': 'ImportedContacts',
'imported': [] if self.imported is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.imported],
'popular_invites': [] if self.popular_invites is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.popular_invites],
'retry_contacts': [] if self.retry_contacts is None else self.retry_contacts[:],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b';\x1c\xd0w',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.imported)),b''.join(x._bytes() for x in self.imported),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.popular_invites)),b''.join(x._bytes() for x in self.popular_invites),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.retry_contacts)),b''.join(struct.pack('<q', x) for x in self.retry_contacts),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_imported = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_imported.append(_x)
reader.read_int()
_popular_invites = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_popular_invites.append(_x)
reader.read_int()
_retry_contacts = []
for _ in range(reader.read_int()):
_x = reader.read_long()
_retry_contacts.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(imported=_imported, popular_invites=_popular_invites, retry_contacts=_retry_contacts, users=_users)
class ResolvedPeer(TLObject):
CONSTRUCTOR_ID = 0x7f077ad9
SUBCLASS_OF_ID = 0xf065b3a8
def __init__(self, peer: 'TypePeer', chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for contacts.ResolvedPeer: Instance of ResolvedPeer.
"""
self.peer = peer
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'ResolvedPeer',
'peer': self.peer.to_dict() if isinstance(self.peer, TLObject) else self.peer,
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\xd9z\x07\x7f',
self.peer._bytes(),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
_peer = reader.tgread_object()
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(peer=_peer, chats=_chats, users=_users)
class TopPeers(TLObject):
CONSTRUCTOR_ID = 0x70b772a8
SUBCLASS_OF_ID = 0x9ee8bb88
def __init__(self, categories: List['TypeTopPeerCategoryPeers'], chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for contacts.TopPeers: Instance of either TopPeersNotModified, TopPeers, TopPeersDisabled.
"""
self.categories = categories
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'TopPeers',
'categories': [] if self.categories is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.categories],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\xa8r\xb7p',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.categories)),b''.join(x._bytes() for x in self.categories),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_categories = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_categories.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(categories=_categories, chats=_chats, users=_users)
class TopPeersDisabled(TLObject):
CONSTRUCTOR_ID = 0xb52c939d
SUBCLASS_OF_ID = 0x9ee8bb88
def to_dict(self):
return {
'_': 'TopPeersDisabled'
}
def _bytes(self):
return b''.join((
b'\x9d\x93,\xb5',
))
@classmethod
def from_reader(cls, reader):
return cls()
class TopPeersNotModified(TLObject):
CONSTRUCTOR_ID = 0xde266ef5
SUBCLASS_OF_ID = 0x9ee8bb88
def to_dict(self):
return {
'_': 'TopPeersNotModified'
}
def _bytes(self):
return b''.join((
b'\xf5n&\xde',
))
@classmethod
def from_reader(cls, reader):
return cls()

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,636 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeBankCardOpenUrl, TypeChat, TypeDataJSON, TypeInvoice, TypePaymentFormMethod, TypePaymentRequestedInfo, TypePaymentSavedCredentials, TypePeer, TypeShippingOption, TypeUpdates, TypeUser, TypeWebDocument
class BankCardData(TLObject):
CONSTRUCTOR_ID = 0x3e24e573
SUBCLASS_OF_ID = 0x8c6dd68b
def __init__(self, title: str, open_urls: List['TypeBankCardOpenUrl']):
"""
Constructor for payments.BankCardData: Instance of BankCardData.
"""
self.title = title
self.open_urls = open_urls
def to_dict(self):
return {
'_': 'BankCardData',
'title': self.title,
'open_urls': [] if self.open_urls is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.open_urls]
}
def _bytes(self):
return b''.join((
b's\xe5$>',
self.serialize_bytes(self.title),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.open_urls)),b''.join(x._bytes() for x in self.open_urls),
))
@classmethod
def from_reader(cls, reader):
_title = reader.tgread_string()
reader.read_int()
_open_urls = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_open_urls.append(_x)
return cls(title=_title, open_urls=_open_urls)
class CheckedGiftCode(TLObject):
CONSTRUCTOR_ID = 0x284a1096
SUBCLASS_OF_ID = 0x5b2997e8
def __init__(self, date: Optional[datetime], months: int, chats: List['TypeChat'], users: List['TypeUser'], via_giveaway: Optional[bool]=None, from_id: Optional['TypePeer']=None, giveaway_msg_id: Optional[int]=None, to_id: Optional[int]=None, used_date: Optional[datetime]=None):
"""
Constructor for payments.CheckedGiftCode: Instance of CheckedGiftCode.
"""
self.date = date
self.months = months
self.chats = chats
self.users = users
self.via_giveaway = via_giveaway
self.from_id = from_id
self.giveaway_msg_id = giveaway_msg_id
self.to_id = to_id
self.used_date = used_date
def to_dict(self):
return {
'_': 'CheckedGiftCode',
'date': self.date,
'months': self.months,
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users],
'via_giveaway': self.via_giveaway,
'from_id': self.from_id.to_dict() if isinstance(self.from_id, TLObject) else self.from_id,
'giveaway_msg_id': self.giveaway_msg_id,
'to_id': self.to_id,
'used_date': self.used_date
}
def _bytes(self):
return b''.join((
b'\x96\x10J(',
struct.pack('<I', (0 if self.via_giveaway is None or self.via_giveaway is False else 4) | (0 if self.from_id is None or self.from_id is False else 16) | (0 if self.giveaway_msg_id is None or self.giveaway_msg_id is False else 8) | (0 if self.to_id is None or self.to_id is False else 1) | (0 if self.used_date is None or self.used_date is False else 2)),
b'' if self.from_id is None or self.from_id is False else (self.from_id._bytes()),
b'' if self.giveaway_msg_id is None or self.giveaway_msg_id is False else (struct.pack('<i', self.giveaway_msg_id)),
b'' if self.to_id is None or self.to_id is False else (struct.pack('<q', self.to_id)),
self.serialize_datetime(self.date),
struct.pack('<i', self.months),
b'' if self.used_date is None or self.used_date is False else (self.serialize_datetime(self.used_date)),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_via_giveaway = bool(flags & 4)
if flags & 16:
_from_id = reader.tgread_object()
else:
_from_id = None
if flags & 8:
_giveaway_msg_id = reader.read_int()
else:
_giveaway_msg_id = None
if flags & 1:
_to_id = reader.read_long()
else:
_to_id = None
_date = reader.tgread_date()
_months = reader.read_int()
if flags & 2:
_used_date = reader.tgread_date()
else:
_used_date = None
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(date=_date, months=_months, chats=_chats, users=_users, via_giveaway=_via_giveaway, from_id=_from_id, giveaway_msg_id=_giveaway_msg_id, to_id=_to_id, used_date=_used_date)
class ExportedInvoice(TLObject):
CONSTRUCTOR_ID = 0xaed0cbd9
SUBCLASS_OF_ID = 0x36105432
def __init__(self, url: str):
"""
Constructor for payments.ExportedInvoice: Instance of ExportedInvoice.
"""
self.url = url
def to_dict(self):
return {
'_': 'ExportedInvoice',
'url': self.url
}
def _bytes(self):
return b''.join((
b'\xd9\xcb\xd0\xae',
self.serialize_bytes(self.url),
))
@classmethod
def from_reader(cls, reader):
_url = reader.tgread_string()
return cls(url=_url)
class GiveawayInfo(TLObject):
CONSTRUCTOR_ID = 0x4367daa0
SUBCLASS_OF_ID = 0x96a377bd
def __init__(self, start_date: Optional[datetime], participating: Optional[bool]=None, preparing_results: Optional[bool]=None, joined_too_early_date: Optional[datetime]=None, admin_disallowed_chat_id: Optional[int]=None, disallowed_country: Optional[str]=None):
"""
Constructor for payments.GiveawayInfo: Instance of either GiveawayInfo, GiveawayInfoResults.
"""
self.start_date = start_date
self.participating = participating
self.preparing_results = preparing_results
self.joined_too_early_date = joined_too_early_date
self.admin_disallowed_chat_id = admin_disallowed_chat_id
self.disallowed_country = disallowed_country
def to_dict(self):
return {
'_': 'GiveawayInfo',
'start_date': self.start_date,
'participating': self.participating,
'preparing_results': self.preparing_results,
'joined_too_early_date': self.joined_too_early_date,
'admin_disallowed_chat_id': self.admin_disallowed_chat_id,
'disallowed_country': self.disallowed_country
}
def _bytes(self):
return b''.join((
b'\xa0\xdagC',
struct.pack('<I', (0 if self.participating is None or self.participating is False else 1) | (0 if self.preparing_results is None or self.preparing_results is False else 8) | (0 if self.joined_too_early_date is None or self.joined_too_early_date is False else 2) | (0 if self.admin_disallowed_chat_id is None or self.admin_disallowed_chat_id is False else 4) | (0 if self.disallowed_country is None or self.disallowed_country is False else 16)),
self.serialize_datetime(self.start_date),
b'' if self.joined_too_early_date is None or self.joined_too_early_date is False else (self.serialize_datetime(self.joined_too_early_date)),
b'' if self.admin_disallowed_chat_id is None or self.admin_disallowed_chat_id is False else (struct.pack('<q', self.admin_disallowed_chat_id)),
b'' if self.disallowed_country is None or self.disallowed_country is False else (self.serialize_bytes(self.disallowed_country)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_participating = bool(flags & 1)
_preparing_results = bool(flags & 8)
_start_date = reader.tgread_date()
if flags & 2:
_joined_too_early_date = reader.tgread_date()
else:
_joined_too_early_date = None
if flags & 4:
_admin_disallowed_chat_id = reader.read_long()
else:
_admin_disallowed_chat_id = None
if flags & 16:
_disallowed_country = reader.tgread_string()
else:
_disallowed_country = None
return cls(start_date=_start_date, participating=_participating, preparing_results=_preparing_results, joined_too_early_date=_joined_too_early_date, admin_disallowed_chat_id=_admin_disallowed_chat_id, disallowed_country=_disallowed_country)
class GiveawayInfoResults(TLObject):
CONSTRUCTOR_ID = 0xcd5570
SUBCLASS_OF_ID = 0x96a377bd
def __init__(self, start_date: Optional[datetime], finish_date: Optional[datetime], winners_count: int, activated_count: int, winner: Optional[bool]=None, refunded: Optional[bool]=None, gift_code_slug: Optional[str]=None):
"""
Constructor for payments.GiveawayInfo: Instance of either GiveawayInfo, GiveawayInfoResults.
"""
self.start_date = start_date
self.finish_date = finish_date
self.winners_count = winners_count
self.activated_count = activated_count
self.winner = winner
self.refunded = refunded
self.gift_code_slug = gift_code_slug
def to_dict(self):
return {
'_': 'GiveawayInfoResults',
'start_date': self.start_date,
'finish_date': self.finish_date,
'winners_count': self.winners_count,
'activated_count': self.activated_count,
'winner': self.winner,
'refunded': self.refunded,
'gift_code_slug': self.gift_code_slug
}
def _bytes(self):
assert ((self.winner or self.winner is not None) and (self.gift_code_slug or self.gift_code_slug is not None)) or ((self.winner is None or self.winner is False) and (self.gift_code_slug is None or self.gift_code_slug is False)), 'winner, gift_code_slug parameters must all be False-y (like None) or all me True-y'
return b''.join((
b'pU\xcd\x00',
struct.pack('<I', (0 if self.winner is None or self.winner is False else 1) | (0 if self.refunded is None or self.refunded is False else 2) | (0 if self.gift_code_slug is None or self.gift_code_slug is False else 1)),
self.serialize_datetime(self.start_date),
b'' if self.gift_code_slug is None or self.gift_code_slug is False else (self.serialize_bytes(self.gift_code_slug)),
self.serialize_datetime(self.finish_date),
struct.pack('<i', self.winners_count),
struct.pack('<i', self.activated_count),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_winner = bool(flags & 1)
_refunded = bool(flags & 2)
_start_date = reader.tgread_date()
if flags & 1:
_gift_code_slug = reader.tgread_string()
else:
_gift_code_slug = None
_finish_date = reader.tgread_date()
_winners_count = reader.read_int()
_activated_count = reader.read_int()
return cls(start_date=_start_date, finish_date=_finish_date, winners_count=_winners_count, activated_count=_activated_count, winner=_winner, refunded=_refunded, gift_code_slug=_gift_code_slug)
class PaymentForm(TLObject):
CONSTRUCTOR_ID = 0xa0058751
SUBCLASS_OF_ID = 0xa0483f19
def __init__(self, form_id: int, bot_id: int, title: str, description: str, invoice: 'TypeInvoice', provider_id: int, url: str, users: List['TypeUser'], can_save_credentials: Optional[bool]=None, password_missing: Optional[bool]=None, photo: Optional['TypeWebDocument']=None, native_provider: Optional[str]=None, native_params: Optional['TypeDataJSON']=None, additional_methods: Optional[List['TypePaymentFormMethod']]=None, saved_info: Optional['TypePaymentRequestedInfo']=None, saved_credentials: Optional[List['TypePaymentSavedCredentials']]=None):
"""
Constructor for payments.PaymentForm: Instance of PaymentForm.
"""
self.form_id = form_id
self.bot_id = bot_id
self.title = title
self.description = description
self.invoice = invoice
self.provider_id = provider_id
self.url = url
self.users = users
self.can_save_credentials = can_save_credentials
self.password_missing = password_missing
self.photo = photo
self.native_provider = native_provider
self.native_params = native_params
self.additional_methods = additional_methods
self.saved_info = saved_info
self.saved_credentials = saved_credentials
def to_dict(self):
return {
'_': 'PaymentForm',
'form_id': self.form_id,
'bot_id': self.bot_id,
'title': self.title,
'description': self.description,
'invoice': self.invoice.to_dict() if isinstance(self.invoice, TLObject) else self.invoice,
'provider_id': self.provider_id,
'url': self.url,
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users],
'can_save_credentials': self.can_save_credentials,
'password_missing': self.password_missing,
'photo': self.photo.to_dict() if isinstance(self.photo, TLObject) else self.photo,
'native_provider': self.native_provider,
'native_params': self.native_params.to_dict() if isinstance(self.native_params, TLObject) else self.native_params,
'additional_methods': [] if self.additional_methods is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.additional_methods],
'saved_info': self.saved_info.to_dict() if isinstance(self.saved_info, TLObject) else self.saved_info,
'saved_credentials': [] if self.saved_credentials is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.saved_credentials]
}
def _bytes(self):
assert ((self.native_provider or self.native_provider is not None) and (self.native_params or self.native_params is not None)) or ((self.native_provider is None or self.native_provider is False) and (self.native_params is None or self.native_params is False)), 'native_provider, native_params parameters must all be False-y (like None) or all me True-y'
return b''.join((
b'Q\x87\x05\xa0',
struct.pack('<I', (0 if self.can_save_credentials is None or self.can_save_credentials is False else 4) | (0 if self.password_missing is None or self.password_missing is False else 8) | (0 if self.photo is None or self.photo is False else 32) | (0 if self.native_provider is None or self.native_provider is False else 16) | (0 if self.native_params is None or self.native_params is False else 16) | (0 if self.additional_methods is None or self.additional_methods is False else 64) | (0 if self.saved_info is None or self.saved_info is False else 1) | (0 if self.saved_credentials is None or self.saved_credentials is False else 2)),
struct.pack('<q', self.form_id),
struct.pack('<q', self.bot_id),
self.serialize_bytes(self.title),
self.serialize_bytes(self.description),
b'' if self.photo is None or self.photo is False else (self.photo._bytes()),
self.invoice._bytes(),
struct.pack('<q', self.provider_id),
self.serialize_bytes(self.url),
b'' if self.native_provider is None or self.native_provider is False else (self.serialize_bytes(self.native_provider)),
b'' if self.native_params is None or self.native_params is False else (self.native_params._bytes()),
b'' if self.additional_methods is None or self.additional_methods is False else b''.join((b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.additional_methods)),b''.join(x._bytes() for x in self.additional_methods))),
b'' if self.saved_info is None or self.saved_info is False else (self.saved_info._bytes()),
b'' if self.saved_credentials is None or self.saved_credentials is False else b''.join((b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.saved_credentials)),b''.join(x._bytes() for x in self.saved_credentials))),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_can_save_credentials = bool(flags & 4)
_password_missing = bool(flags & 8)
_form_id = reader.read_long()
_bot_id = reader.read_long()
_title = reader.tgread_string()
_description = reader.tgread_string()
if flags & 32:
_photo = reader.tgread_object()
else:
_photo = None
_invoice = reader.tgread_object()
_provider_id = reader.read_long()
_url = reader.tgread_string()
if flags & 16:
_native_provider = reader.tgread_string()
else:
_native_provider = None
if flags & 16:
_native_params = reader.tgread_object()
else:
_native_params = None
if flags & 64:
reader.read_int()
_additional_methods = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_additional_methods.append(_x)
else:
_additional_methods = None
if flags & 1:
_saved_info = reader.tgread_object()
else:
_saved_info = None
if flags & 2:
reader.read_int()
_saved_credentials = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_saved_credentials.append(_x)
else:
_saved_credentials = None
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(form_id=_form_id, bot_id=_bot_id, title=_title, description=_description, invoice=_invoice, provider_id=_provider_id, url=_url, users=_users, can_save_credentials=_can_save_credentials, password_missing=_password_missing, photo=_photo, native_provider=_native_provider, native_params=_native_params, additional_methods=_additional_methods, saved_info=_saved_info, saved_credentials=_saved_credentials)
class PaymentReceipt(TLObject):
CONSTRUCTOR_ID = 0x70c4fe03
SUBCLASS_OF_ID = 0x590093c9
def __init__(self, date: Optional[datetime], bot_id: int, provider_id: int, title: str, description: str, invoice: 'TypeInvoice', currency: str, total_amount: int, credentials_title: str, users: List['TypeUser'], photo: Optional['TypeWebDocument']=None, info: Optional['TypePaymentRequestedInfo']=None, shipping: Optional['TypeShippingOption']=None, tip_amount: Optional[int]=None):
"""
Constructor for payments.PaymentReceipt: Instance of PaymentReceipt.
"""
self.date = date
self.bot_id = bot_id
self.provider_id = provider_id
self.title = title
self.description = description
self.invoice = invoice
self.currency = currency
self.total_amount = total_amount
self.credentials_title = credentials_title
self.users = users
self.photo = photo
self.info = info
self.shipping = shipping
self.tip_amount = tip_amount
def to_dict(self):
return {
'_': 'PaymentReceipt',
'date': self.date,
'bot_id': self.bot_id,
'provider_id': self.provider_id,
'title': self.title,
'description': self.description,
'invoice': self.invoice.to_dict() if isinstance(self.invoice, TLObject) else self.invoice,
'currency': self.currency,
'total_amount': self.total_amount,
'credentials_title': self.credentials_title,
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users],
'photo': self.photo.to_dict() if isinstance(self.photo, TLObject) else self.photo,
'info': self.info.to_dict() if isinstance(self.info, TLObject) else self.info,
'shipping': self.shipping.to_dict() if isinstance(self.shipping, TLObject) else self.shipping,
'tip_amount': self.tip_amount
}
def _bytes(self):
return b''.join((
b'\x03\xfe\xc4p',
struct.pack('<I', (0 if self.photo is None or self.photo is False else 4) | (0 if self.info is None or self.info is False else 1) | (0 if self.shipping is None or self.shipping is False else 2) | (0 if self.tip_amount is None or self.tip_amount is False else 8)),
self.serialize_datetime(self.date),
struct.pack('<q', self.bot_id),
struct.pack('<q', self.provider_id),
self.serialize_bytes(self.title),
self.serialize_bytes(self.description),
b'' if self.photo is None or self.photo is False else (self.photo._bytes()),
self.invoice._bytes(),
b'' if self.info is None or self.info is False else (self.info._bytes()),
b'' if self.shipping is None or self.shipping is False else (self.shipping._bytes()),
b'' if self.tip_amount is None or self.tip_amount is False else (struct.pack('<q', self.tip_amount)),
self.serialize_bytes(self.currency),
struct.pack('<q', self.total_amount),
self.serialize_bytes(self.credentials_title),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_date = reader.tgread_date()
_bot_id = reader.read_long()
_provider_id = reader.read_long()
_title = reader.tgread_string()
_description = reader.tgread_string()
if flags & 4:
_photo = reader.tgread_object()
else:
_photo = None
_invoice = reader.tgread_object()
if flags & 1:
_info = reader.tgread_object()
else:
_info = None
if flags & 2:
_shipping = reader.tgread_object()
else:
_shipping = None
if flags & 8:
_tip_amount = reader.read_long()
else:
_tip_amount = None
_currency = reader.tgread_string()
_total_amount = reader.read_long()
_credentials_title = reader.tgread_string()
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(date=_date, bot_id=_bot_id, provider_id=_provider_id, title=_title, description=_description, invoice=_invoice, currency=_currency, total_amount=_total_amount, credentials_title=_credentials_title, users=_users, photo=_photo, info=_info, shipping=_shipping, tip_amount=_tip_amount)
class PaymentResult(TLObject):
CONSTRUCTOR_ID = 0x4e5f810d
SUBCLASS_OF_ID = 0x8ae16a9d
def __init__(self, updates: 'TypeUpdates'):
"""
Constructor for payments.PaymentResult: Instance of either PaymentResult, PaymentVerificationNeeded.
"""
self.updates = updates
def to_dict(self):
return {
'_': 'PaymentResult',
'updates': self.updates.to_dict() if isinstance(self.updates, TLObject) else self.updates
}
def _bytes(self):
return b''.join((
b'\r\x81_N',
self.updates._bytes(),
))
@classmethod
def from_reader(cls, reader):
_updates = reader.tgread_object()
return cls(updates=_updates)
class PaymentVerificationNeeded(TLObject):
CONSTRUCTOR_ID = 0xd8411139
SUBCLASS_OF_ID = 0x8ae16a9d
def __init__(self, url: str):
"""
Constructor for payments.PaymentResult: Instance of either PaymentResult, PaymentVerificationNeeded.
"""
self.url = url
def to_dict(self):
return {
'_': 'PaymentVerificationNeeded',
'url': self.url
}
def _bytes(self):
return b''.join((
b'9\x11A\xd8',
self.serialize_bytes(self.url),
))
@classmethod
def from_reader(cls, reader):
_url = reader.tgread_string()
return cls(url=_url)
class SavedInfo(TLObject):
CONSTRUCTOR_ID = 0xfb8fe43c
SUBCLASS_OF_ID = 0xad3cf146
def __init__(self, has_saved_credentials: Optional[bool]=None, saved_info: Optional['TypePaymentRequestedInfo']=None):
"""
Constructor for payments.SavedInfo: Instance of SavedInfo.
"""
self.has_saved_credentials = has_saved_credentials
self.saved_info = saved_info
def to_dict(self):
return {
'_': 'SavedInfo',
'has_saved_credentials': self.has_saved_credentials,
'saved_info': self.saved_info.to_dict() if isinstance(self.saved_info, TLObject) else self.saved_info
}
def _bytes(self):
return b''.join((
b'<\xe4\x8f\xfb',
struct.pack('<I', (0 if self.has_saved_credentials is None or self.has_saved_credentials is False else 2) | (0 if self.saved_info is None or self.saved_info is False else 1)),
b'' if self.saved_info is None or self.saved_info is False else (self.saved_info._bytes()),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_has_saved_credentials = bool(flags & 2)
if flags & 1:
_saved_info = reader.tgread_object()
else:
_saved_info = None
return cls(has_saved_credentials=_has_saved_credentials, saved_info=_saved_info)
class ValidatedRequestedInfo(TLObject):
CONSTRUCTOR_ID = 0xd1451883
SUBCLASS_OF_ID = 0x8f8044b7
def __init__(self, id: Optional[str]=None, shipping_options: Optional[List['TypeShippingOption']]=None):
"""
Constructor for payments.ValidatedRequestedInfo: Instance of ValidatedRequestedInfo.
"""
self.id = id
self.shipping_options = shipping_options
def to_dict(self):
return {
'_': 'ValidatedRequestedInfo',
'id': self.id,
'shipping_options': [] if self.shipping_options is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.shipping_options]
}
def _bytes(self):
return b''.join((
b'\x83\x18E\xd1',
struct.pack('<I', (0 if self.id is None or self.id is False else 1) | (0 if self.shipping_options is None or self.shipping_options is False else 2)),
b'' if self.id is None or self.id is False else (self.serialize_bytes(self.id)),
b'' if self.shipping_options is None or self.shipping_options is False else b''.join((b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.shipping_options)),b''.join(x._bytes() for x in self.shipping_options))),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
if flags & 1:
_id = reader.tgread_string()
else:
_id = None
if flags & 2:
reader.read_int()
_shipping_options = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_shipping_options.append(_x)
else:
_shipping_options = None
return cls(id=_id, shipping_options=_shipping_options)

View File

@@ -0,0 +1,313 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeChat, TypeGroupCall, TypeGroupCallParticipant, TypeGroupCallStreamChannel, TypePeer, TypePhoneCall, TypeUser
class ExportedGroupCallInvite(TLObject):
CONSTRUCTOR_ID = 0x204bd158
SUBCLASS_OF_ID = 0x3b3bfe8f
def __init__(self, link: str):
"""
Constructor for phone.ExportedGroupCallInvite: Instance of ExportedGroupCallInvite.
"""
self.link = link
def to_dict(self):
return {
'_': 'ExportedGroupCallInvite',
'link': self.link
}
def _bytes(self):
return b''.join((
b'X\xd1K ',
self.serialize_bytes(self.link),
))
@classmethod
def from_reader(cls, reader):
_link = reader.tgread_string()
return cls(link=_link)
class GroupCall(TLObject):
CONSTRUCTOR_ID = 0x9e727aad
SUBCLASS_OF_ID = 0x304116be
def __init__(self, call: 'TypeGroupCall', participants: List['TypeGroupCallParticipant'], participants_next_offset: str, chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for phone.GroupCall: Instance of GroupCall.
"""
self.call = call
self.participants = participants
self.participants_next_offset = participants_next_offset
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'GroupCall',
'call': self.call.to_dict() if isinstance(self.call, TLObject) else self.call,
'participants': [] if self.participants is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.participants],
'participants_next_offset': self.participants_next_offset,
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\xadzr\x9e',
self.call._bytes(),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.participants)),b''.join(x._bytes() for x in self.participants),
self.serialize_bytes(self.participants_next_offset),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
_call = reader.tgread_object()
reader.read_int()
_participants = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_participants.append(_x)
_participants_next_offset = reader.tgread_string()
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(call=_call, participants=_participants, participants_next_offset=_participants_next_offset, chats=_chats, users=_users)
class GroupCallStreamChannels(TLObject):
CONSTRUCTOR_ID = 0xd0e482b2
SUBCLASS_OF_ID = 0x9157c5e4
def __init__(self, channels: List['TypeGroupCallStreamChannel']):
"""
Constructor for phone.GroupCallStreamChannels: Instance of GroupCallStreamChannels.
"""
self.channels = channels
def to_dict(self):
return {
'_': 'GroupCallStreamChannels',
'channels': [] if self.channels is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.channels]
}
def _bytes(self):
return b''.join((
b'\xb2\x82\xe4\xd0',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.channels)),b''.join(x._bytes() for x in self.channels),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_channels = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_channels.append(_x)
return cls(channels=_channels)
class GroupCallStreamRtmpUrl(TLObject):
CONSTRUCTOR_ID = 0x2dbf3432
SUBCLASS_OF_ID = 0xd1f515cb
def __init__(self, url: str, key: str):
"""
Constructor for phone.GroupCallStreamRtmpUrl: Instance of GroupCallStreamRtmpUrl.
"""
self.url = url
self.key = key
def to_dict(self):
return {
'_': 'GroupCallStreamRtmpUrl',
'url': self.url,
'key': self.key
}
def _bytes(self):
return b''.join((
b'24\xbf-',
self.serialize_bytes(self.url),
self.serialize_bytes(self.key),
))
@classmethod
def from_reader(cls, reader):
_url = reader.tgread_string()
_key = reader.tgread_string()
return cls(url=_url, key=_key)
class GroupParticipants(TLObject):
CONSTRUCTOR_ID = 0xf47751b6
SUBCLASS_OF_ID = 0x72d304f4
def __init__(self, count: int, participants: List['TypeGroupCallParticipant'], next_offset: str, chats: List['TypeChat'], users: List['TypeUser'], version: int):
"""
Constructor for phone.GroupParticipants: Instance of GroupParticipants.
"""
self.count = count
self.participants = participants
self.next_offset = next_offset
self.chats = chats
self.users = users
self.version = version
def to_dict(self):
return {
'_': 'GroupParticipants',
'count': self.count,
'participants': [] if self.participants is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.participants],
'next_offset': self.next_offset,
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users],
'version': self.version
}
def _bytes(self):
return b''.join((
b'\xb6Qw\xf4',
struct.pack('<i', self.count),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.participants)),b''.join(x._bytes() for x in self.participants),
self.serialize_bytes(self.next_offset),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
struct.pack('<i', self.version),
))
@classmethod
def from_reader(cls, reader):
_count = reader.read_int()
reader.read_int()
_participants = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_participants.append(_x)
_next_offset = reader.tgread_string()
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
_version = reader.read_int()
return cls(count=_count, participants=_participants, next_offset=_next_offset, chats=_chats, users=_users, version=_version)
class JoinAsPeers(TLObject):
CONSTRUCTOR_ID = 0xafe5623f
SUBCLASS_OF_ID = 0xb4b770fb
def __init__(self, peers: List['TypePeer'], chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for phone.JoinAsPeers: Instance of JoinAsPeers.
"""
self.peers = peers
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'JoinAsPeers',
'peers': [] if self.peers is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.peers],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'?b\xe5\xaf',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.peers)),b''.join(x._bytes() for x in self.peers),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_peers = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_peers.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(peers=_peers, chats=_chats, users=_users)
class PhoneCall(TLObject):
CONSTRUCTOR_ID = 0xec82e140
SUBCLASS_OF_ID = 0xd48afe4f
def __init__(self, phone_call: 'TypePhoneCall', users: List['TypeUser']):
"""
Constructor for phone.PhoneCall: Instance of PhoneCall.
"""
self.phone_call = phone_call
self.users = users
def to_dict(self):
return {
'_': 'PhoneCall',
'phone_call': self.phone_call.to_dict() if isinstance(self.phone_call, TLObject) else self.phone_call,
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'@\xe1\x82\xec',
self.phone_call._bytes(),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
_phone_call = reader.tgread_object()
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(phone_call=_phone_call, users=_users)

View File

@@ -0,0 +1,135 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypePhoto, TypeUser
class Photo(TLObject):
CONSTRUCTOR_ID = 0x20212ca8
SUBCLASS_OF_ID = 0xc292bd24
def __init__(self, photo: 'TypePhoto', users: List['TypeUser']):
"""
Constructor for photos.Photo: Instance of Photo.
"""
self.photo = photo
self.users = users
def to_dict(self):
return {
'_': 'Photo',
'photo': self.photo.to_dict() if isinstance(self.photo, TLObject) else self.photo,
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\xa8,! ',
self.photo._bytes(),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
_photo = reader.tgread_object()
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(photo=_photo, users=_users)
class Photos(TLObject):
CONSTRUCTOR_ID = 0x8dca6aa5
SUBCLASS_OF_ID = 0x27cfb967
def __init__(self, photos: List['TypePhoto'], users: List['TypeUser']):
"""
Constructor for photos.Photos: Instance of either Photos, PhotosSlice.
"""
self.photos = photos
self.users = users
def to_dict(self):
return {
'_': 'Photos',
'photos': [] if self.photos is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.photos],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\xa5j\xca\x8d',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.photos)),b''.join(x._bytes() for x in self.photos),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_photos = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_photos.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(photos=_photos, users=_users)
class PhotosSlice(TLObject):
CONSTRUCTOR_ID = 0x15051f54
SUBCLASS_OF_ID = 0x27cfb967
def __init__(self, count: int, photos: List['TypePhoto'], users: List['TypeUser']):
"""
Constructor for photos.Photos: Instance of either Photos, PhotosSlice.
"""
self.count = count
self.photos = photos
self.users = users
def to_dict(self):
return {
'_': 'PhotosSlice',
'count': self.count,
'photos': [] if self.photos is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.photos],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'T\x1f\x05\x15',
struct.pack('<i', self.count),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.photos)),b''.join(x._bytes() for x in self.photos),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
_count = reader.read_int()
reader.read_int()
_photos = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_photos.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(count=_count, photos=_photos, users=_users)

View File

@@ -0,0 +1,209 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeBoost, TypeChat, TypeMyBoost, TypePrepaidGiveaway, TypeStatsPercentValue, TypeUser
class BoostsList(TLObject):
CONSTRUCTOR_ID = 0x86f8613c
SUBCLASS_OF_ID = 0x2235a8bd
def __init__(self, count: int, boosts: List['TypeBoost'], users: List['TypeUser'], next_offset: Optional[str]=None):
"""
Constructor for premium.BoostsList: Instance of BoostsList.
"""
self.count = count
self.boosts = boosts
self.users = users
self.next_offset = next_offset
def to_dict(self):
return {
'_': 'BoostsList',
'count': self.count,
'boosts': [] if self.boosts is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.boosts],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users],
'next_offset': self.next_offset
}
def _bytes(self):
return b''.join((
b'<a\xf8\x86',
struct.pack('<I', (0 if self.next_offset is None or self.next_offset is False else 1)),
struct.pack('<i', self.count),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.boosts)),b''.join(x._bytes() for x in self.boosts),
b'' if self.next_offset is None or self.next_offset is False else (self.serialize_bytes(self.next_offset)),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_count = reader.read_int()
reader.read_int()
_boosts = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_boosts.append(_x)
if flags & 1:
_next_offset = reader.tgread_string()
else:
_next_offset = None
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(count=_count, boosts=_boosts, users=_users, next_offset=_next_offset)
class BoostsStatus(TLObject):
CONSTRUCTOR_ID = 0x4959427a
SUBCLASS_OF_ID = 0xc31b1ab9
def __init__(self, level: int, current_level_boosts: int, boosts: int, boost_url: str, my_boost: Optional[bool]=None, gift_boosts: Optional[int]=None, next_level_boosts: Optional[int]=None, premium_audience: Optional['TypeStatsPercentValue']=None, prepaid_giveaways: Optional[List['TypePrepaidGiveaway']]=None, my_boost_slots: Optional[List[int]]=None):
"""
Constructor for premium.BoostsStatus: Instance of BoostsStatus.
"""
self.level = level
self.current_level_boosts = current_level_boosts
self.boosts = boosts
self.boost_url = boost_url
self.my_boost = my_boost
self.gift_boosts = gift_boosts
self.next_level_boosts = next_level_boosts
self.premium_audience = premium_audience
self.prepaid_giveaways = prepaid_giveaways
self.my_boost_slots = my_boost_slots
def to_dict(self):
return {
'_': 'BoostsStatus',
'level': self.level,
'current_level_boosts': self.current_level_boosts,
'boosts': self.boosts,
'boost_url': self.boost_url,
'my_boost': self.my_boost,
'gift_boosts': self.gift_boosts,
'next_level_boosts': self.next_level_boosts,
'premium_audience': self.premium_audience.to_dict() if isinstance(self.premium_audience, TLObject) else self.premium_audience,
'prepaid_giveaways': [] if self.prepaid_giveaways is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.prepaid_giveaways],
'my_boost_slots': [] if self.my_boost_slots is None else self.my_boost_slots[:]
}
def _bytes(self):
assert ((self.my_boost or self.my_boost is not None) and (self.my_boost_slots or self.my_boost_slots is not None)) or ((self.my_boost is None or self.my_boost is False) and (self.my_boost_slots is None or self.my_boost_slots is False)), 'my_boost, my_boost_slots parameters must all be False-y (like None) or all me True-y'
return b''.join((
b'zBYI',
struct.pack('<I', (0 if self.my_boost is None or self.my_boost is False else 4) | (0 if self.gift_boosts is None or self.gift_boosts is False else 16) | (0 if self.next_level_boosts is None or self.next_level_boosts is False else 1) | (0 if self.premium_audience is None or self.premium_audience is False else 2) | (0 if self.prepaid_giveaways is None or self.prepaid_giveaways is False else 8) | (0 if self.my_boost_slots is None or self.my_boost_slots is False else 4)),
struct.pack('<i', self.level),
struct.pack('<i', self.current_level_boosts),
struct.pack('<i', self.boosts),
b'' if self.gift_boosts is None or self.gift_boosts is False else (struct.pack('<i', self.gift_boosts)),
b'' if self.next_level_boosts is None or self.next_level_boosts is False else (struct.pack('<i', self.next_level_boosts)),
b'' if self.premium_audience is None or self.premium_audience is False else (self.premium_audience._bytes()),
self.serialize_bytes(self.boost_url),
b'' if self.prepaid_giveaways is None or self.prepaid_giveaways is False else b''.join((b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.prepaid_giveaways)),b''.join(x._bytes() for x in self.prepaid_giveaways))),
b'' if self.my_boost_slots is None or self.my_boost_slots is False else b''.join((b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.my_boost_slots)),b''.join(struct.pack('<i', x) for x in self.my_boost_slots))),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_my_boost = bool(flags & 4)
_level = reader.read_int()
_current_level_boosts = reader.read_int()
_boosts = reader.read_int()
if flags & 16:
_gift_boosts = reader.read_int()
else:
_gift_boosts = None
if flags & 1:
_next_level_boosts = reader.read_int()
else:
_next_level_boosts = None
if flags & 2:
_premium_audience = reader.tgread_object()
else:
_premium_audience = None
_boost_url = reader.tgread_string()
if flags & 8:
reader.read_int()
_prepaid_giveaways = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_prepaid_giveaways.append(_x)
else:
_prepaid_giveaways = None
if flags & 4:
reader.read_int()
_my_boost_slots = []
for _ in range(reader.read_int()):
_x = reader.read_int()
_my_boost_slots.append(_x)
else:
_my_boost_slots = None
return cls(level=_level, current_level_boosts=_current_level_boosts, boosts=_boosts, boost_url=_boost_url, my_boost=_my_boost, gift_boosts=_gift_boosts, next_level_boosts=_next_level_boosts, premium_audience=_premium_audience, prepaid_giveaways=_prepaid_giveaways, my_boost_slots=_my_boost_slots)
class MyBoosts(TLObject):
CONSTRUCTOR_ID = 0x9ae228e2
SUBCLASS_OF_ID = 0xad3512db
def __init__(self, my_boosts: List['TypeMyBoost'], chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for premium.MyBoosts: Instance of MyBoosts.
"""
self.my_boosts = my_boosts
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'MyBoosts',
'my_boosts': [] if self.my_boosts is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.my_boosts],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\xe2(\xe2\x9a',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.my_boosts)),b''.join(x._bytes() for x in self.my_boosts),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_my_boosts = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_my_boosts.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(my_boosts=_my_boosts, chats=_chats, users=_users)

View File

@@ -0,0 +1,368 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeChat, TypePostInteractionCounters, TypePublicForward, TypeStatsAbsValueAndPrev, TypeStatsDateRangeDays, TypeStatsGraph, TypeStatsGroupTopAdmin, TypeStatsGroupTopInviter, TypeStatsGroupTopPoster, TypeStatsPercentValue, TypeUser
class BroadcastStats(TLObject):
CONSTRUCTOR_ID = 0x396ca5fc
SUBCLASS_OF_ID = 0x7ff25428
def __init__(self, period: 'TypeStatsDateRangeDays', followers: 'TypeStatsAbsValueAndPrev', views_per_post: 'TypeStatsAbsValueAndPrev', shares_per_post: 'TypeStatsAbsValueAndPrev', reactions_per_post: 'TypeStatsAbsValueAndPrev', views_per_story: 'TypeStatsAbsValueAndPrev', shares_per_story: 'TypeStatsAbsValueAndPrev', reactions_per_story: 'TypeStatsAbsValueAndPrev', enabled_notifications: 'TypeStatsPercentValue', growth_graph: 'TypeStatsGraph', followers_graph: 'TypeStatsGraph', mute_graph: 'TypeStatsGraph', top_hours_graph: 'TypeStatsGraph', interactions_graph: 'TypeStatsGraph', iv_interactions_graph: 'TypeStatsGraph', views_by_source_graph: 'TypeStatsGraph', new_followers_by_source_graph: 'TypeStatsGraph', languages_graph: 'TypeStatsGraph', reactions_by_emotion_graph: 'TypeStatsGraph', story_interactions_graph: 'TypeStatsGraph', story_reactions_by_emotion_graph: 'TypeStatsGraph', recent_posts_interactions: List['TypePostInteractionCounters']):
"""
Constructor for stats.BroadcastStats: Instance of BroadcastStats.
"""
self.period = period
self.followers = followers
self.views_per_post = views_per_post
self.shares_per_post = shares_per_post
self.reactions_per_post = reactions_per_post
self.views_per_story = views_per_story
self.shares_per_story = shares_per_story
self.reactions_per_story = reactions_per_story
self.enabled_notifications = enabled_notifications
self.growth_graph = growth_graph
self.followers_graph = followers_graph
self.mute_graph = mute_graph
self.top_hours_graph = top_hours_graph
self.interactions_graph = interactions_graph
self.iv_interactions_graph = iv_interactions_graph
self.views_by_source_graph = views_by_source_graph
self.new_followers_by_source_graph = new_followers_by_source_graph
self.languages_graph = languages_graph
self.reactions_by_emotion_graph = reactions_by_emotion_graph
self.story_interactions_graph = story_interactions_graph
self.story_reactions_by_emotion_graph = story_reactions_by_emotion_graph
self.recent_posts_interactions = recent_posts_interactions
def to_dict(self):
return {
'_': 'BroadcastStats',
'period': self.period.to_dict() if isinstance(self.period, TLObject) else self.period,
'followers': self.followers.to_dict() if isinstance(self.followers, TLObject) else self.followers,
'views_per_post': self.views_per_post.to_dict() if isinstance(self.views_per_post, TLObject) else self.views_per_post,
'shares_per_post': self.shares_per_post.to_dict() if isinstance(self.shares_per_post, TLObject) else self.shares_per_post,
'reactions_per_post': self.reactions_per_post.to_dict() if isinstance(self.reactions_per_post, TLObject) else self.reactions_per_post,
'views_per_story': self.views_per_story.to_dict() if isinstance(self.views_per_story, TLObject) else self.views_per_story,
'shares_per_story': self.shares_per_story.to_dict() if isinstance(self.shares_per_story, TLObject) else self.shares_per_story,
'reactions_per_story': self.reactions_per_story.to_dict() if isinstance(self.reactions_per_story, TLObject) else self.reactions_per_story,
'enabled_notifications': self.enabled_notifications.to_dict() if isinstance(self.enabled_notifications, TLObject) else self.enabled_notifications,
'growth_graph': self.growth_graph.to_dict() if isinstance(self.growth_graph, TLObject) else self.growth_graph,
'followers_graph': self.followers_graph.to_dict() if isinstance(self.followers_graph, TLObject) else self.followers_graph,
'mute_graph': self.mute_graph.to_dict() if isinstance(self.mute_graph, TLObject) else self.mute_graph,
'top_hours_graph': self.top_hours_graph.to_dict() if isinstance(self.top_hours_graph, TLObject) else self.top_hours_graph,
'interactions_graph': self.interactions_graph.to_dict() if isinstance(self.interactions_graph, TLObject) else self.interactions_graph,
'iv_interactions_graph': self.iv_interactions_graph.to_dict() if isinstance(self.iv_interactions_graph, TLObject) else self.iv_interactions_graph,
'views_by_source_graph': self.views_by_source_graph.to_dict() if isinstance(self.views_by_source_graph, TLObject) else self.views_by_source_graph,
'new_followers_by_source_graph': self.new_followers_by_source_graph.to_dict() if isinstance(self.new_followers_by_source_graph, TLObject) else self.new_followers_by_source_graph,
'languages_graph': self.languages_graph.to_dict() if isinstance(self.languages_graph, TLObject) else self.languages_graph,
'reactions_by_emotion_graph': self.reactions_by_emotion_graph.to_dict() if isinstance(self.reactions_by_emotion_graph, TLObject) else self.reactions_by_emotion_graph,
'story_interactions_graph': self.story_interactions_graph.to_dict() if isinstance(self.story_interactions_graph, TLObject) else self.story_interactions_graph,
'story_reactions_by_emotion_graph': self.story_reactions_by_emotion_graph.to_dict() if isinstance(self.story_reactions_by_emotion_graph, TLObject) else self.story_reactions_by_emotion_graph,
'recent_posts_interactions': [] if self.recent_posts_interactions is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.recent_posts_interactions]
}
def _bytes(self):
return b''.join((
b'\xfc\xa5l9',
self.period._bytes(),
self.followers._bytes(),
self.views_per_post._bytes(),
self.shares_per_post._bytes(),
self.reactions_per_post._bytes(),
self.views_per_story._bytes(),
self.shares_per_story._bytes(),
self.reactions_per_story._bytes(),
self.enabled_notifications._bytes(),
self.growth_graph._bytes(),
self.followers_graph._bytes(),
self.mute_graph._bytes(),
self.top_hours_graph._bytes(),
self.interactions_graph._bytes(),
self.iv_interactions_graph._bytes(),
self.views_by_source_graph._bytes(),
self.new_followers_by_source_graph._bytes(),
self.languages_graph._bytes(),
self.reactions_by_emotion_graph._bytes(),
self.story_interactions_graph._bytes(),
self.story_reactions_by_emotion_graph._bytes(),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.recent_posts_interactions)),b''.join(x._bytes() for x in self.recent_posts_interactions),
))
@classmethod
def from_reader(cls, reader):
_period = reader.tgread_object()
_followers = reader.tgread_object()
_views_per_post = reader.tgread_object()
_shares_per_post = reader.tgread_object()
_reactions_per_post = reader.tgread_object()
_views_per_story = reader.tgread_object()
_shares_per_story = reader.tgread_object()
_reactions_per_story = reader.tgread_object()
_enabled_notifications = reader.tgread_object()
_growth_graph = reader.tgread_object()
_followers_graph = reader.tgread_object()
_mute_graph = reader.tgread_object()
_top_hours_graph = reader.tgread_object()
_interactions_graph = reader.tgread_object()
_iv_interactions_graph = reader.tgread_object()
_views_by_source_graph = reader.tgread_object()
_new_followers_by_source_graph = reader.tgread_object()
_languages_graph = reader.tgread_object()
_reactions_by_emotion_graph = reader.tgread_object()
_story_interactions_graph = reader.tgread_object()
_story_reactions_by_emotion_graph = reader.tgread_object()
reader.read_int()
_recent_posts_interactions = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_recent_posts_interactions.append(_x)
return cls(period=_period, followers=_followers, views_per_post=_views_per_post, shares_per_post=_shares_per_post, reactions_per_post=_reactions_per_post, views_per_story=_views_per_story, shares_per_story=_shares_per_story, reactions_per_story=_reactions_per_story, enabled_notifications=_enabled_notifications, growth_graph=_growth_graph, followers_graph=_followers_graph, mute_graph=_mute_graph, top_hours_graph=_top_hours_graph, interactions_graph=_interactions_graph, iv_interactions_graph=_iv_interactions_graph, views_by_source_graph=_views_by_source_graph, new_followers_by_source_graph=_new_followers_by_source_graph, languages_graph=_languages_graph, reactions_by_emotion_graph=_reactions_by_emotion_graph, story_interactions_graph=_story_interactions_graph, story_reactions_by_emotion_graph=_story_reactions_by_emotion_graph, recent_posts_interactions=_recent_posts_interactions)
class MegagroupStats(TLObject):
CONSTRUCTOR_ID = 0xef7ff916
SUBCLASS_OF_ID = 0x5b59be8d
def __init__(self, period: 'TypeStatsDateRangeDays', members: 'TypeStatsAbsValueAndPrev', messages: 'TypeStatsAbsValueAndPrev', viewers: 'TypeStatsAbsValueAndPrev', posters: 'TypeStatsAbsValueAndPrev', growth_graph: 'TypeStatsGraph', members_graph: 'TypeStatsGraph', new_members_by_source_graph: 'TypeStatsGraph', languages_graph: 'TypeStatsGraph', messages_graph: 'TypeStatsGraph', actions_graph: 'TypeStatsGraph', top_hours_graph: 'TypeStatsGraph', weekdays_graph: 'TypeStatsGraph', top_posters: List['TypeStatsGroupTopPoster'], top_admins: List['TypeStatsGroupTopAdmin'], top_inviters: List['TypeStatsGroupTopInviter'], users: List['TypeUser']):
"""
Constructor for stats.MegagroupStats: Instance of MegagroupStats.
"""
self.period = period
self.members = members
self.messages = messages
self.viewers = viewers
self.posters = posters
self.growth_graph = growth_graph
self.members_graph = members_graph
self.new_members_by_source_graph = new_members_by_source_graph
self.languages_graph = languages_graph
self.messages_graph = messages_graph
self.actions_graph = actions_graph
self.top_hours_graph = top_hours_graph
self.weekdays_graph = weekdays_graph
self.top_posters = top_posters
self.top_admins = top_admins
self.top_inviters = top_inviters
self.users = users
def to_dict(self):
return {
'_': 'MegagroupStats',
'period': self.period.to_dict() if isinstance(self.period, TLObject) else self.period,
'members': self.members.to_dict() if isinstance(self.members, TLObject) else self.members,
'messages': self.messages.to_dict() if isinstance(self.messages, TLObject) else self.messages,
'viewers': self.viewers.to_dict() if isinstance(self.viewers, TLObject) else self.viewers,
'posters': self.posters.to_dict() if isinstance(self.posters, TLObject) else self.posters,
'growth_graph': self.growth_graph.to_dict() if isinstance(self.growth_graph, TLObject) else self.growth_graph,
'members_graph': self.members_graph.to_dict() if isinstance(self.members_graph, TLObject) else self.members_graph,
'new_members_by_source_graph': self.new_members_by_source_graph.to_dict() if isinstance(self.new_members_by_source_graph, TLObject) else self.new_members_by_source_graph,
'languages_graph': self.languages_graph.to_dict() if isinstance(self.languages_graph, TLObject) else self.languages_graph,
'messages_graph': self.messages_graph.to_dict() if isinstance(self.messages_graph, TLObject) else self.messages_graph,
'actions_graph': self.actions_graph.to_dict() if isinstance(self.actions_graph, TLObject) else self.actions_graph,
'top_hours_graph': self.top_hours_graph.to_dict() if isinstance(self.top_hours_graph, TLObject) else self.top_hours_graph,
'weekdays_graph': self.weekdays_graph.to_dict() if isinstance(self.weekdays_graph, TLObject) else self.weekdays_graph,
'top_posters': [] if self.top_posters is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.top_posters],
'top_admins': [] if self.top_admins is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.top_admins],
'top_inviters': [] if self.top_inviters is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.top_inviters],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\x16\xf9\x7f\xef',
self.period._bytes(),
self.members._bytes(),
self.messages._bytes(),
self.viewers._bytes(),
self.posters._bytes(),
self.growth_graph._bytes(),
self.members_graph._bytes(),
self.new_members_by_source_graph._bytes(),
self.languages_graph._bytes(),
self.messages_graph._bytes(),
self.actions_graph._bytes(),
self.top_hours_graph._bytes(),
self.weekdays_graph._bytes(),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.top_posters)),b''.join(x._bytes() for x in self.top_posters),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.top_admins)),b''.join(x._bytes() for x in self.top_admins),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.top_inviters)),b''.join(x._bytes() for x in self.top_inviters),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
_period = reader.tgread_object()
_members = reader.tgread_object()
_messages = reader.tgread_object()
_viewers = reader.tgread_object()
_posters = reader.tgread_object()
_growth_graph = reader.tgread_object()
_members_graph = reader.tgread_object()
_new_members_by_source_graph = reader.tgread_object()
_languages_graph = reader.tgread_object()
_messages_graph = reader.tgread_object()
_actions_graph = reader.tgread_object()
_top_hours_graph = reader.tgread_object()
_weekdays_graph = reader.tgread_object()
reader.read_int()
_top_posters = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_top_posters.append(_x)
reader.read_int()
_top_admins = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_top_admins.append(_x)
reader.read_int()
_top_inviters = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_top_inviters.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(period=_period, members=_members, messages=_messages, viewers=_viewers, posters=_posters, growth_graph=_growth_graph, members_graph=_members_graph, new_members_by_source_graph=_new_members_by_source_graph, languages_graph=_languages_graph, messages_graph=_messages_graph, actions_graph=_actions_graph, top_hours_graph=_top_hours_graph, weekdays_graph=_weekdays_graph, top_posters=_top_posters, top_admins=_top_admins, top_inviters=_top_inviters, users=_users)
class MessageStats(TLObject):
CONSTRUCTOR_ID = 0x7fe91c14
SUBCLASS_OF_ID = 0x9604a322
def __init__(self, views_graph: 'TypeStatsGraph', reactions_by_emotion_graph: 'TypeStatsGraph'):
"""
Constructor for stats.MessageStats: Instance of MessageStats.
"""
self.views_graph = views_graph
self.reactions_by_emotion_graph = reactions_by_emotion_graph
def to_dict(self):
return {
'_': 'MessageStats',
'views_graph': self.views_graph.to_dict() if isinstance(self.views_graph, TLObject) else self.views_graph,
'reactions_by_emotion_graph': self.reactions_by_emotion_graph.to_dict() if isinstance(self.reactions_by_emotion_graph, TLObject) else self.reactions_by_emotion_graph
}
def _bytes(self):
return b''.join((
b'\x14\x1c\xe9\x7f',
self.views_graph._bytes(),
self.reactions_by_emotion_graph._bytes(),
))
@classmethod
def from_reader(cls, reader):
_views_graph = reader.tgread_object()
_reactions_by_emotion_graph = reader.tgread_object()
return cls(views_graph=_views_graph, reactions_by_emotion_graph=_reactions_by_emotion_graph)
class PublicForwards(TLObject):
CONSTRUCTOR_ID = 0x93037e20
SUBCLASS_OF_ID = 0xa7283211
def __init__(self, count: int, forwards: List['TypePublicForward'], chats: List['TypeChat'], users: List['TypeUser'], next_offset: Optional[str]=None):
"""
Constructor for stats.PublicForwards: Instance of PublicForwards.
"""
self.count = count
self.forwards = forwards
self.chats = chats
self.users = users
self.next_offset = next_offset
def to_dict(self):
return {
'_': 'PublicForwards',
'count': self.count,
'forwards': [] if self.forwards is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.forwards],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users],
'next_offset': self.next_offset
}
def _bytes(self):
return b''.join((
b' ~\x03\x93',
struct.pack('<I', (0 if self.next_offset is None or self.next_offset is False else 1)),
struct.pack('<i', self.count),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.forwards)),b''.join(x._bytes() for x in self.forwards),
b'' if self.next_offset is None or self.next_offset is False else (self.serialize_bytes(self.next_offset)),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_count = reader.read_int()
reader.read_int()
_forwards = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_forwards.append(_x)
if flags & 1:
_next_offset = reader.tgread_string()
else:
_next_offset = None
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(count=_count, forwards=_forwards, chats=_chats, users=_users, next_offset=_next_offset)
class StoryStats(TLObject):
CONSTRUCTOR_ID = 0x50cd067c
SUBCLASS_OF_ID = 0x8b4d43d4
def __init__(self, views_graph: 'TypeStatsGraph', reactions_by_emotion_graph: 'TypeStatsGraph'):
"""
Constructor for stats.StoryStats: Instance of StoryStats.
"""
self.views_graph = views_graph
self.reactions_by_emotion_graph = reactions_by_emotion_graph
def to_dict(self):
return {
'_': 'StoryStats',
'views_graph': self.views_graph.to_dict() if isinstance(self.views_graph, TLObject) else self.views_graph,
'reactions_by_emotion_graph': self.reactions_by_emotion_graph.to_dict() if isinstance(self.reactions_by_emotion_graph, TLObject) else self.reactions_by_emotion_graph
}
def _bytes(self):
return b''.join((
b'|\x06\xcdP',
self.views_graph._bytes(),
self.reactions_by_emotion_graph._bytes(),
))
@classmethod
def from_reader(cls, reader):
_views_graph = reader.tgread_object()
_reactions_by_emotion_graph = reader.tgread_object()
return cls(views_graph=_views_graph, reactions_by_emotion_graph=_reactions_by_emotion_graph)

View File

@@ -0,0 +1,35 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
class SuggestedShortName(TLObject):
CONSTRUCTOR_ID = 0x85fea03f
SUBCLASS_OF_ID = 0xc44a4b21
def __init__(self, short_name: str):
"""
Constructor for stickers.SuggestedShortName: Instance of SuggestedShortName.
"""
self.short_name = short_name
def to_dict(self):
return {
'_': 'SuggestedShortName',
'short_name': self.short_name
}
def _bytes(self):
return b''.join((
b'?\xa0\xfe\x85',
self.serialize_bytes(self.short_name),
))
@classmethod
def from_reader(cls, reader):
_short_name = reader.tgread_string()
return cls(short_name=_short_name)

View File

@@ -0,0 +1,197 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
class FileGif(TLObject):
CONSTRUCTOR_ID = 0xcae1aadf
SUBCLASS_OF_ID = 0xf3a1e6f3
def to_dict(self):
return {
'_': 'FileGif'
}
def _bytes(self):
return b''.join((
b'\xdf\xaa\xe1\xca',
))
@classmethod
def from_reader(cls, reader):
return cls()
class FileJpeg(TLObject):
CONSTRUCTOR_ID = 0x7efe0e
SUBCLASS_OF_ID = 0xf3a1e6f3
def to_dict(self):
return {
'_': 'FileJpeg'
}
def _bytes(self):
return b''.join((
b'\x0e\xfe~\x00',
))
@classmethod
def from_reader(cls, reader):
return cls()
class FileMov(TLObject):
CONSTRUCTOR_ID = 0x4b09ebbc
SUBCLASS_OF_ID = 0xf3a1e6f3
def to_dict(self):
return {
'_': 'FileMov'
}
def _bytes(self):
return b''.join((
b'\xbc\xeb\tK',
))
@classmethod
def from_reader(cls, reader):
return cls()
class FileMp3(TLObject):
CONSTRUCTOR_ID = 0x528a0677
SUBCLASS_OF_ID = 0xf3a1e6f3
def to_dict(self):
return {
'_': 'FileMp3'
}
def _bytes(self):
return b''.join((
b'w\x06\x8aR',
))
@classmethod
def from_reader(cls, reader):
return cls()
class FileMp4(TLObject):
CONSTRUCTOR_ID = 0xb3cea0e4
SUBCLASS_OF_ID = 0xf3a1e6f3
def to_dict(self):
return {
'_': 'FileMp4'
}
def _bytes(self):
return b''.join((
b'\xe4\xa0\xce\xb3',
))
@classmethod
def from_reader(cls, reader):
return cls()
class FilePartial(TLObject):
CONSTRUCTOR_ID = 0x40bc6f52
SUBCLASS_OF_ID = 0xf3a1e6f3
def to_dict(self):
return {
'_': 'FilePartial'
}
def _bytes(self):
return b''.join((
b'Ro\xbc@',
))
@classmethod
def from_reader(cls, reader):
return cls()
class FilePdf(TLObject):
CONSTRUCTOR_ID = 0xae1e508d
SUBCLASS_OF_ID = 0xf3a1e6f3
def to_dict(self):
return {
'_': 'FilePdf'
}
def _bytes(self):
return b''.join((
b'\x8dP\x1e\xae',
))
@classmethod
def from_reader(cls, reader):
return cls()
class FilePng(TLObject):
CONSTRUCTOR_ID = 0xa4f63c0
SUBCLASS_OF_ID = 0xf3a1e6f3
def to_dict(self):
return {
'_': 'FilePng'
}
def _bytes(self):
return b''.join((
b'\xc0cO\n',
))
@classmethod
def from_reader(cls, reader):
return cls()
class FileUnknown(TLObject):
CONSTRUCTOR_ID = 0xaa963b05
SUBCLASS_OF_ID = 0xf3a1e6f3
def to_dict(self):
return {
'_': 'FileUnknown'
}
def _bytes(self):
return b''.join((
b'\x05;\x96\xaa',
))
@classmethod
def from_reader(cls, reader):
return cls()
class FileWebp(TLObject):
CONSTRUCTOR_ID = 0x1081464c
SUBCLASS_OF_ID = 0xf3a1e6f3
def to_dict(self):
return {
'_': 'FileWebp'
}
def _bytes(self):
return b''.join((
b'LF\x81\x10',
))
@classmethod
def from_reader(cls, reader):
return cls()

View File

@@ -0,0 +1,399 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeChat, TypePeerStories, TypeStoriesStealthMode, TypeStoryItem, TypeStoryReaction, TypeStoryView, TypeStoryViews, TypeUser
class AllStories(TLObject):
CONSTRUCTOR_ID = 0x6efc5e81
SUBCLASS_OF_ID = 0x7e60d0cd
def __init__(self, count: int, state: str, peer_stories: List['TypePeerStories'], chats: List['TypeChat'], users: List['TypeUser'], stealth_mode: 'TypeStoriesStealthMode', has_more: Optional[bool]=None):
"""
Constructor for stories.AllStories: Instance of either AllStoriesNotModified, AllStories.
"""
self.count = count
self.state = state
self.peer_stories = peer_stories
self.chats = chats
self.users = users
self.stealth_mode = stealth_mode
self.has_more = has_more
def to_dict(self):
return {
'_': 'AllStories',
'count': self.count,
'state': self.state,
'peer_stories': [] if self.peer_stories is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.peer_stories],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users],
'stealth_mode': self.stealth_mode.to_dict() if isinstance(self.stealth_mode, TLObject) else self.stealth_mode,
'has_more': self.has_more
}
def _bytes(self):
return b''.join((
b'\x81^\xfcn',
struct.pack('<I', (0 if self.has_more is None or self.has_more is False else 1)),
struct.pack('<i', self.count),
self.serialize_bytes(self.state),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.peer_stories)),b''.join(x._bytes() for x in self.peer_stories),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
self.stealth_mode._bytes(),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_has_more = bool(flags & 1)
_count = reader.read_int()
_state = reader.tgread_string()
reader.read_int()
_peer_stories = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_peer_stories.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
_stealth_mode = reader.tgread_object()
return cls(count=_count, state=_state, peer_stories=_peer_stories, chats=_chats, users=_users, stealth_mode=_stealth_mode, has_more=_has_more)
class AllStoriesNotModified(TLObject):
CONSTRUCTOR_ID = 0x1158fe3e
SUBCLASS_OF_ID = 0x7e60d0cd
def __init__(self, state: str, stealth_mode: 'TypeStoriesStealthMode'):
"""
Constructor for stories.AllStories: Instance of either AllStoriesNotModified, AllStories.
"""
self.state = state
self.stealth_mode = stealth_mode
def to_dict(self):
return {
'_': 'AllStoriesNotModified',
'state': self.state,
'stealth_mode': self.stealth_mode.to_dict() if isinstance(self.stealth_mode, TLObject) else self.stealth_mode
}
def _bytes(self):
return b''.join((
b'>\xfeX\x11',
b'\0\0\0\0',
self.serialize_bytes(self.state),
self.stealth_mode._bytes(),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_state = reader.tgread_string()
_stealth_mode = reader.tgread_object()
return cls(state=_state, stealth_mode=_stealth_mode)
class PeerStories(TLObject):
CONSTRUCTOR_ID = 0xcae68768
SUBCLASS_OF_ID = 0x9d56cfd0
def __init__(self, stories: 'TypePeerStories', chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for stories.PeerStories: Instance of PeerStories.
"""
self.stories = stories
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'PeerStories',
'stories': self.stories.to_dict() if isinstance(self.stories, TLObject) else self.stories,
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'h\x87\xe6\xca',
self.stories._bytes(),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
_stories = reader.tgread_object()
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(stories=_stories, chats=_chats, users=_users)
class Stories(TLObject):
CONSTRUCTOR_ID = 0x5dd8c3c8
SUBCLASS_OF_ID = 0x251c0c2c
def __init__(self, count: int, stories: List['TypeStoryItem'], chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for stories.Stories: Instance of Stories.
"""
self.count = count
self.stories = stories
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'Stories',
'count': self.count,
'stories': [] if self.stories is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.stories],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\xc8\xc3\xd8]',
struct.pack('<i', self.count),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.stories)),b''.join(x._bytes() for x in self.stories),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
_count = reader.read_int()
reader.read_int()
_stories = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_stories.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(count=_count, stories=_stories, chats=_chats, users=_users)
class StoryReactionsList(TLObject):
CONSTRUCTOR_ID = 0xaa5f789c
SUBCLASS_OF_ID = 0x46f91e3
def __init__(self, count: int, reactions: List['TypeStoryReaction'], chats: List['TypeChat'], users: List['TypeUser'], next_offset: Optional[str]=None):
"""
Constructor for stories.StoryReactionsList: Instance of StoryReactionsList.
"""
self.count = count
self.reactions = reactions
self.chats = chats
self.users = users
self.next_offset = next_offset
def to_dict(self):
return {
'_': 'StoryReactionsList',
'count': self.count,
'reactions': [] if self.reactions is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.reactions],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users],
'next_offset': self.next_offset
}
def _bytes(self):
return b''.join((
b'\x9cx_\xaa',
struct.pack('<I', (0 if self.next_offset is None or self.next_offset is False else 1)),
struct.pack('<i', self.count),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.reactions)),b''.join(x._bytes() for x in self.reactions),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
b'' if self.next_offset is None or self.next_offset is False else (self.serialize_bytes(self.next_offset)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_count = reader.read_int()
reader.read_int()
_reactions = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_reactions.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
if flags & 1:
_next_offset = reader.tgread_string()
else:
_next_offset = None
return cls(count=_count, reactions=_reactions, chats=_chats, users=_users, next_offset=_next_offset)
class StoryViews(TLObject):
CONSTRUCTOR_ID = 0xde9eed1d
SUBCLASS_OF_ID = 0x4b3fc4ba
def __init__(self, views: List['TypeStoryViews'], users: List['TypeUser']):
"""
Constructor for stories.StoryViews: Instance of StoryViews.
"""
self.views = views
self.users = users
def to_dict(self):
return {
'_': 'StoryViews',
'views': [] if self.views is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.views],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'\x1d\xed\x9e\xde',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.views)),b''.join(x._bytes() for x in self.views),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_views = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_views.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(views=_views, users=_users)
class StoryViewsList(TLObject):
CONSTRUCTOR_ID = 0x59d78fc5
SUBCLASS_OF_ID = 0xb9437560
def __init__(self, count: int, views_count: int, forwards_count: int, reactions_count: int, views: List['TypeStoryView'], chats: List['TypeChat'], users: List['TypeUser'], next_offset: Optional[str]=None):
"""
Constructor for stories.StoryViewsList: Instance of StoryViewsList.
"""
self.count = count
self.views_count = views_count
self.forwards_count = forwards_count
self.reactions_count = reactions_count
self.views = views
self.chats = chats
self.users = users
self.next_offset = next_offset
def to_dict(self):
return {
'_': 'StoryViewsList',
'count': self.count,
'views_count': self.views_count,
'forwards_count': self.forwards_count,
'reactions_count': self.reactions_count,
'views': [] if self.views is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.views],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users],
'next_offset': self.next_offset
}
def _bytes(self):
return b''.join((
b'\xc5\x8f\xd7Y',
struct.pack('<I', (0 if self.next_offset is None or self.next_offset is False else 1)),
struct.pack('<i', self.count),
struct.pack('<i', self.views_count),
struct.pack('<i', self.forwards_count),
struct.pack('<i', self.reactions_count),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.views)),b''.join(x._bytes() for x in self.views),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
b'' if self.next_offset is None or self.next_offset is False else (self.serialize_bytes(self.next_offset)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_count = reader.read_int()
_views_count = reader.read_int()
_forwards_count = reader.read_int()
_reactions_count = reader.read_int()
reader.read_int()
_views = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_views.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
if flags & 1:
_next_offset = reader.tgread_string()
else:
_next_offset = None
return cls(count=_count, views_count=_views_count, forwards_count=_forwards_count, reactions_count=_reactions_count, views=_views, chats=_chats, users=_users, next_offset=_next_offset)

View File

@@ -0,0 +1,447 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeChat, TypeDialog, TypeEncryptedMessage, TypeMessage, TypeUpdate, TypeUser
from ...tl.types.updates import TypeState
class ChannelDifference(TLObject):
CONSTRUCTOR_ID = 0x2064674e
SUBCLASS_OF_ID = 0x29896f5d
def __init__(self, pts: int, new_messages: List['TypeMessage'], other_updates: List['TypeUpdate'], chats: List['TypeChat'], users: List['TypeUser'], final: Optional[bool]=None, timeout: Optional[int]=None):
"""
Constructor for updates.ChannelDifference: Instance of either ChannelDifferenceEmpty, ChannelDifferenceTooLong, ChannelDifference.
"""
self.pts = pts
self.new_messages = new_messages
self.other_updates = other_updates
self.chats = chats
self.users = users
self.final = final
self.timeout = timeout
def to_dict(self):
return {
'_': 'ChannelDifference',
'pts': self.pts,
'new_messages': [] if self.new_messages is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.new_messages],
'other_updates': [] if self.other_updates is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.other_updates],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users],
'final': self.final,
'timeout': self.timeout
}
def _bytes(self):
return b''.join((
b'Ngd ',
struct.pack('<I', (0 if self.final is None or self.final is False else 1) | (0 if self.timeout is None or self.timeout is False else 2)),
struct.pack('<i', self.pts),
b'' if self.timeout is None or self.timeout is False else (struct.pack('<i', self.timeout)),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.new_messages)),b''.join(x._bytes() for x in self.new_messages),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.other_updates)),b''.join(x._bytes() for x in self.other_updates),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_final = bool(flags & 1)
_pts = reader.read_int()
if flags & 2:
_timeout = reader.read_int()
else:
_timeout = None
reader.read_int()
_new_messages = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_new_messages.append(_x)
reader.read_int()
_other_updates = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_other_updates.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(pts=_pts, new_messages=_new_messages, other_updates=_other_updates, chats=_chats, users=_users, final=_final, timeout=_timeout)
class ChannelDifferenceEmpty(TLObject):
CONSTRUCTOR_ID = 0x3e11affb
SUBCLASS_OF_ID = 0x29896f5d
def __init__(self, pts: int, final: Optional[bool]=None, timeout: Optional[int]=None):
"""
Constructor for updates.ChannelDifference: Instance of either ChannelDifferenceEmpty, ChannelDifferenceTooLong, ChannelDifference.
"""
self.pts = pts
self.final = final
self.timeout = timeout
def to_dict(self):
return {
'_': 'ChannelDifferenceEmpty',
'pts': self.pts,
'final': self.final,
'timeout': self.timeout
}
def _bytes(self):
return b''.join((
b'\xfb\xaf\x11>',
struct.pack('<I', (0 if self.final is None or self.final is False else 1) | (0 if self.timeout is None or self.timeout is False else 2)),
struct.pack('<i', self.pts),
b'' if self.timeout is None or self.timeout is False else (struct.pack('<i', self.timeout)),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_final = bool(flags & 1)
_pts = reader.read_int()
if flags & 2:
_timeout = reader.read_int()
else:
_timeout = None
return cls(pts=_pts, final=_final, timeout=_timeout)
class ChannelDifferenceTooLong(TLObject):
CONSTRUCTOR_ID = 0xa4bcc6fe
SUBCLASS_OF_ID = 0x29896f5d
def __init__(self, dialog: 'TypeDialog', messages: List['TypeMessage'], chats: List['TypeChat'], users: List['TypeUser'], final: Optional[bool]=None, timeout: Optional[int]=None):
"""
Constructor for updates.ChannelDifference: Instance of either ChannelDifferenceEmpty, ChannelDifferenceTooLong, ChannelDifference.
"""
self.dialog = dialog
self.messages = messages
self.chats = chats
self.users = users
self.final = final
self.timeout = timeout
def to_dict(self):
return {
'_': 'ChannelDifferenceTooLong',
'dialog': self.dialog.to_dict() if isinstance(self.dialog, TLObject) else self.dialog,
'messages': [] if self.messages is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.messages],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users],
'final': self.final,
'timeout': self.timeout
}
def _bytes(self):
return b''.join((
b'\xfe\xc6\xbc\xa4',
struct.pack('<I', (0 if self.final is None or self.final is False else 1) | (0 if self.timeout is None or self.timeout is False else 2)),
b'' if self.timeout is None or self.timeout is False else (struct.pack('<i', self.timeout)),
self.dialog._bytes(),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.messages)),b''.join(x._bytes() for x in self.messages),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
flags = reader.read_int()
_final = bool(flags & 1)
if flags & 2:
_timeout = reader.read_int()
else:
_timeout = None
_dialog = reader.tgread_object()
reader.read_int()
_messages = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_messages.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(dialog=_dialog, messages=_messages, chats=_chats, users=_users, final=_final, timeout=_timeout)
class Difference(TLObject):
CONSTRUCTOR_ID = 0xf49ca0
SUBCLASS_OF_ID = 0x20482874
def __init__(self, new_messages: List['TypeMessage'], new_encrypted_messages: List['TypeEncryptedMessage'], other_updates: List['TypeUpdate'], chats: List['TypeChat'], users: List['TypeUser'], state: 'TypeState'):
"""
Constructor for updates.Difference: Instance of either DifferenceEmpty, Difference, DifferenceSlice, DifferenceTooLong.
"""
self.new_messages = new_messages
self.new_encrypted_messages = new_encrypted_messages
self.other_updates = other_updates
self.chats = chats
self.users = users
self.state = state
def to_dict(self):
return {
'_': 'Difference',
'new_messages': [] if self.new_messages is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.new_messages],
'new_encrypted_messages': [] if self.new_encrypted_messages is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.new_encrypted_messages],
'other_updates': [] if self.other_updates is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.other_updates],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users],
'state': self.state.to_dict() if isinstance(self.state, TLObject) else self.state
}
def _bytes(self):
return b''.join((
b'\xa0\x9c\xf4\x00',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.new_messages)),b''.join(x._bytes() for x in self.new_messages),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.new_encrypted_messages)),b''.join(x._bytes() for x in self.new_encrypted_messages),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.other_updates)),b''.join(x._bytes() for x in self.other_updates),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
self.state._bytes(),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_new_messages = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_new_messages.append(_x)
reader.read_int()
_new_encrypted_messages = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_new_encrypted_messages.append(_x)
reader.read_int()
_other_updates = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_other_updates.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
_state = reader.tgread_object()
return cls(new_messages=_new_messages, new_encrypted_messages=_new_encrypted_messages, other_updates=_other_updates, chats=_chats, users=_users, state=_state)
class DifferenceEmpty(TLObject):
CONSTRUCTOR_ID = 0x5d75a138
SUBCLASS_OF_ID = 0x20482874
def __init__(self, date: Optional[datetime], seq: int):
"""
Constructor for updates.Difference: Instance of either DifferenceEmpty, Difference, DifferenceSlice, DifferenceTooLong.
"""
self.date = date
self.seq = seq
def to_dict(self):
return {
'_': 'DifferenceEmpty',
'date': self.date,
'seq': self.seq
}
def _bytes(self):
return b''.join((
b'8\xa1u]',
self.serialize_datetime(self.date),
struct.pack('<i', self.seq),
))
@classmethod
def from_reader(cls, reader):
_date = reader.tgread_date()
_seq = reader.read_int()
return cls(date=_date, seq=_seq)
class DifferenceSlice(TLObject):
CONSTRUCTOR_ID = 0xa8fb1981
SUBCLASS_OF_ID = 0x20482874
def __init__(self, new_messages: List['TypeMessage'], new_encrypted_messages: List['TypeEncryptedMessage'], other_updates: List['TypeUpdate'], chats: List['TypeChat'], users: List['TypeUser'], intermediate_state: 'TypeState'):
"""
Constructor for updates.Difference: Instance of either DifferenceEmpty, Difference, DifferenceSlice, DifferenceTooLong.
"""
self.new_messages = new_messages
self.new_encrypted_messages = new_encrypted_messages
self.other_updates = other_updates
self.chats = chats
self.users = users
self.intermediate_state = intermediate_state
def to_dict(self):
return {
'_': 'DifferenceSlice',
'new_messages': [] if self.new_messages is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.new_messages],
'new_encrypted_messages': [] if self.new_encrypted_messages is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.new_encrypted_messages],
'other_updates': [] if self.other_updates is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.other_updates],
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users],
'intermediate_state': self.intermediate_state.to_dict() if isinstance(self.intermediate_state, TLObject) else self.intermediate_state
}
def _bytes(self):
return b''.join((
b'\x81\x19\xfb\xa8',
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.new_messages)),b''.join(x._bytes() for x in self.new_messages),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.new_encrypted_messages)),b''.join(x._bytes() for x in self.new_encrypted_messages),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.other_updates)),b''.join(x._bytes() for x in self.other_updates),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
self.intermediate_state._bytes(),
))
@classmethod
def from_reader(cls, reader):
reader.read_int()
_new_messages = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_new_messages.append(_x)
reader.read_int()
_new_encrypted_messages = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_new_encrypted_messages.append(_x)
reader.read_int()
_other_updates = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_other_updates.append(_x)
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
_intermediate_state = reader.tgread_object()
return cls(new_messages=_new_messages, new_encrypted_messages=_new_encrypted_messages, other_updates=_other_updates, chats=_chats, users=_users, intermediate_state=_intermediate_state)
class DifferenceTooLong(TLObject):
CONSTRUCTOR_ID = 0x4afe8f6d
SUBCLASS_OF_ID = 0x20482874
def __init__(self, pts: int):
"""
Constructor for updates.Difference: Instance of either DifferenceEmpty, Difference, DifferenceSlice, DifferenceTooLong.
"""
self.pts = pts
def to_dict(self):
return {
'_': 'DifferenceTooLong',
'pts': self.pts
}
def _bytes(self):
return b''.join((
b'm\x8f\xfeJ',
struct.pack('<i', self.pts),
))
@classmethod
def from_reader(cls, reader):
_pts = reader.read_int()
return cls(pts=_pts)
class State(TLObject):
CONSTRUCTOR_ID = 0xa56c2a3e
SUBCLASS_OF_ID = 0x23df1a01
def __init__(self, pts: int, qts: int, date: Optional[datetime], seq: int, unread_count: int):
"""
Constructor for updates.State: Instance of State.
"""
self.pts = pts
self.qts = qts
self.date = date
self.seq = seq
self.unread_count = unread_count
def to_dict(self):
return {
'_': 'State',
'pts': self.pts,
'qts': self.qts,
'date': self.date,
'seq': self.seq,
'unread_count': self.unread_count
}
def _bytes(self):
return b''.join((
b'>*l\xa5',
struct.pack('<i', self.pts),
struct.pack('<i', self.qts),
self.serialize_datetime(self.date),
struct.pack('<i', self.seq),
struct.pack('<i', self.unread_count),
))
@classmethod
def from_reader(cls, reader):
_pts = reader.read_int()
_qts = reader.read_int()
_date = reader.tgread_date()
_seq = reader.read_int()
_unread_count = reader.read_int()
return cls(pts=_pts, qts=_qts, date=_date, seq=_seq, unread_count=_unread_count)

View File

@@ -0,0 +1,196 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types.storage import TypeFileType
from ...tl.types import TypeFileHash
class CdnFile(TLObject):
CONSTRUCTOR_ID = 0xa99fca4f
SUBCLASS_OF_ID = 0xf5ccf928
def __init__(self, bytes: bytes):
"""
Constructor for upload.CdnFile: Instance of either CdnFileReuploadNeeded, CdnFile.
"""
self.bytes = bytes
def to_dict(self):
return {
'_': 'CdnFile',
'bytes': self.bytes
}
def _bytes(self):
return b''.join((
b'O\xca\x9f\xa9',
self.serialize_bytes(self.bytes),
))
@classmethod
def from_reader(cls, reader):
_bytes = reader.tgread_bytes()
return cls(bytes=_bytes)
class CdnFileReuploadNeeded(TLObject):
CONSTRUCTOR_ID = 0xeea8e46e
SUBCLASS_OF_ID = 0xf5ccf928
def __init__(self, request_token: bytes):
"""
Constructor for upload.CdnFile: Instance of either CdnFileReuploadNeeded, CdnFile.
"""
self.request_token = request_token
def to_dict(self):
return {
'_': 'CdnFileReuploadNeeded',
'request_token': self.request_token
}
def _bytes(self):
return b''.join((
b'n\xe4\xa8\xee',
self.serialize_bytes(self.request_token),
))
@classmethod
def from_reader(cls, reader):
_request_token = reader.tgread_bytes()
return cls(request_token=_request_token)
class File(TLObject):
CONSTRUCTOR_ID = 0x96a18d5
SUBCLASS_OF_ID = 0x6c9bd728
def __init__(self, type: 'TypeFileType', mtime: int, bytes: bytes):
"""
Constructor for upload.File: Instance of either File, FileCdnRedirect.
"""
self.type = type
self.mtime = mtime
self.bytes = bytes
def to_dict(self):
return {
'_': 'File',
'type': self.type.to_dict() if isinstance(self.type, TLObject) else self.type,
'mtime': self.mtime,
'bytes': self.bytes
}
def _bytes(self):
return b''.join((
b'\xd5\x18j\t',
self.type._bytes(),
struct.pack('<i', self.mtime),
self.serialize_bytes(self.bytes),
))
@classmethod
def from_reader(cls, reader):
_type = reader.tgread_object()
_mtime = reader.read_int()
_bytes = reader.tgread_bytes()
return cls(type=_type, mtime=_mtime, bytes=_bytes)
class FileCdnRedirect(TLObject):
CONSTRUCTOR_ID = 0xf18cda44
SUBCLASS_OF_ID = 0x6c9bd728
def __init__(self, dc_id: int, file_token: bytes, encryption_key: bytes, encryption_iv: bytes, file_hashes: List['TypeFileHash']):
"""
Constructor for upload.File: Instance of either File, FileCdnRedirect.
"""
self.dc_id = dc_id
self.file_token = file_token
self.encryption_key = encryption_key
self.encryption_iv = encryption_iv
self.file_hashes = file_hashes
def to_dict(self):
return {
'_': 'FileCdnRedirect',
'dc_id': self.dc_id,
'file_token': self.file_token,
'encryption_key': self.encryption_key,
'encryption_iv': self.encryption_iv,
'file_hashes': [] if self.file_hashes is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.file_hashes]
}
def _bytes(self):
return b''.join((
b'D\xda\x8c\xf1',
struct.pack('<i', self.dc_id),
self.serialize_bytes(self.file_token),
self.serialize_bytes(self.encryption_key),
self.serialize_bytes(self.encryption_iv),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.file_hashes)),b''.join(x._bytes() for x in self.file_hashes),
))
@classmethod
def from_reader(cls, reader):
_dc_id = reader.read_int()
_file_token = reader.tgread_bytes()
_encryption_key = reader.tgread_bytes()
_encryption_iv = reader.tgread_bytes()
reader.read_int()
_file_hashes = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_file_hashes.append(_x)
return cls(dc_id=_dc_id, file_token=_file_token, encryption_key=_encryption_key, encryption_iv=_encryption_iv, file_hashes=_file_hashes)
class WebFile(TLObject):
CONSTRUCTOR_ID = 0x21e753bc
SUBCLASS_OF_ID = 0x68f17f51
def __init__(self, size: int, mime_type: str, file_type: 'TypeFileType', mtime: int, bytes: bytes):
"""
Constructor for upload.WebFile: Instance of WebFile.
"""
self.size = size
self.mime_type = mime_type
self.file_type = file_type
self.mtime = mtime
self.bytes = bytes
def to_dict(self):
return {
'_': 'WebFile',
'size': self.size,
'mime_type': self.mime_type,
'file_type': self.file_type.to_dict() if isinstance(self.file_type, TLObject) else self.file_type,
'mtime': self.mtime,
'bytes': self.bytes
}
def _bytes(self):
return b''.join((
b'\xbcS\xe7!',
struct.pack('<i', self.size),
self.serialize_bytes(self.mime_type),
self.file_type._bytes(),
struct.pack('<i', self.mtime),
self.serialize_bytes(self.bytes),
))
@classmethod
def from_reader(cls, reader):
_size = reader.read_int()
_mime_type = reader.tgread_string()
_file_type = reader.tgread_object()
_mtime = reader.read_int()
_bytes = reader.tgread_bytes()
return cls(size=_size, mime_type=_mime_type, file_type=_file_type, mtime=_mtime, bytes=_bytes)

View File

@@ -0,0 +1,56 @@
"""File generated by TLObjects' generator. All changes will be ERASED"""
from ...tl.tlobject import TLObject
from typing import Optional, List, Union, TYPE_CHECKING
import os
import struct
from datetime import datetime
if TYPE_CHECKING:
from ...tl.types import TypeChat, TypeUser, TypeUserFull
class UserFull(TLObject):
CONSTRUCTOR_ID = 0x3b6d152e
SUBCLASS_OF_ID = 0x83df9df5
def __init__(self, full_user: 'TypeUserFull', chats: List['TypeChat'], users: List['TypeUser']):
"""
Constructor for users.UserFull: Instance of UserFull.
"""
self.full_user = full_user
self.chats = chats
self.users = users
def to_dict(self):
return {
'_': 'UserFull',
'full_user': self.full_user.to_dict() if isinstance(self.full_user, TLObject) else self.full_user,
'chats': [] if self.chats is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.chats],
'users': [] if self.users is None else [x.to_dict() if isinstance(x, TLObject) else x for x in self.users]
}
def _bytes(self):
return b''.join((
b'.\x15m;',
self.full_user._bytes(),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.chats)),b''.join(x._bytes() for x in self.chats),
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.users)),b''.join(x._bytes() for x in self.users),
))
@classmethod
def from_reader(cls, reader):
_full_user = reader.tgread_object()
reader.read_int()
_chats = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_chats.append(_x)
reader.read_int()
_users = []
for _ in range(reader.read_int()):
_x = reader.tgread_object()
_users.append(_x)
return cls(full_user=_full_user, chats=_chats, users=_users)