import asyncio import struct from .gzippacked import GzipPacked from .. import TLObject from ..functions import InvokeAfterMsgRequest 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. Then Telegram will, at some point, respond with the result for this msg. Thus it makes sense that requests and their result are bound to a sent `TLMessage`, and this result can be represented as a `Future` that will eventually be set with either a result, error or cancelled. """ def __init__(self, msg_id, seq_no, obj, out=False, after_id=0): self.obj = obj self.container_msg_id = None self.future = asyncio.Future() # After which message ID this one should run. We do this so # InvokeAfterMsgRequest is transparent to the user and we can # easily invoke after while confirming the original request. # TODO Currently we don't update this if another message ID changes self.after_id = after_id # There are two use-cases for the TLMessage, outgoing and incoming. # Outgoing messages are meant to be serialized and sent across the # network so it makes sense to pack them as early as possible and # avoid this computation if it needs to be resent, and also shows # serializing-errors as early as possible (foreground task). # # We assume obj won't change so caching the bytes is safe to do. # Caching bytes lets us get the size in a fast way, necessary for # knowing whether a container can be sent (<1MB) or not (too big). # # Incoming messages don't really need this body, but we save the # msg_id and seq_no inside the body for consistency and raise if # one tries to bytes()-ify the entire message (len == 12). if not out: self._body = struct.pack('