Instruction:
How would you implement a function in Python 3 that
converts all the methods in the given types into synchronous.

Response:
def syncify(*types):
    """
    Converts all the methods in the given types (class definitions)
    into synchronous, which return either the coroutine or the result
    based on whether ``asyncio's`` event loop is running.
    """
    # Our asynchronous generators all are `RequestIter`, which already
    # provide a synchronous iterator variant, so we don't need to worry
    # about asyncgenfunction's here.
    for t in types:
        for name in dir(t):
            if not name.startswith('_') or name == '__call__':
                if inspect.iscoroutinefunction(getattr(t, name)):
                    _syncify_wrap(t, name)


Instruction:
Explain what the following Python 3 code does
async def get(self):
        if not self._deque:
            self._ready.clear()
            await self._ready.wait()

        buffer = io.BytesIO()
        batch = []
        size = 0

        # Fill a new batch to return while the size is small enough,
        # as long as we don't exceed the maximum length of messages.
        while self._deque and len(batch) <= MessageContainer.MAXIMUM_LENGTH:
            state = self._deque.popleft()
            size += len(state.data) + TLMessage.SIZE_OVERHEAD

            if size <= MessageContainer.MAXIMUM_SIZE:
                state.msg_id = self._state.write_data_as_message(
                    buffer, state.data, isinstance(state.request, TLRequest),
                    after_id=state.after.msg_id if state.after else None
                )
                batch.append(state)
                self._log.debug('Assigned msg_id = %d to %s (%x)',
                                state.msg_id, state.request.__class__.__name__,
                                id(state.request))
                continue

            if batch:
                # Put the item back since it can't be sent in this batch
                self._deque.appendleft(state)
                break

            # If a single message exceeds the maximum size, then the
            # message payload cannot be sent. Telegram would forcibly
            # close the connection; message would never be confirmed.
            #
            # We don't put the item back because it can never be sent.
            # If we did, we would loop again and reach this same path.
            # Setting the exception twice results in `InvalidStateError`
            # and this method should never return with error, which we
            # really want to avoid.
            self._log.warning(
                'Message payload for %s is too long (%d) and cannot be sent',
                state.request.__class__.__name__, len(state.data)
            )
            state.future.set_exception(
                ValueError('Request payload is too big'))

            size = 0
            continue

        if not batch:
            return None, None

        if len(batch) > 1:
            # Inlined code to pack several messages into a container
            data = struct.pack(
                '<Ii', MessageContainer.CONSTRUCTOR_ID, len(batch)
            ) + buffer.getvalue()
            buffer = io.BytesIO()
            container_id = self._state.write_data_as_message(
                buffer, data, content_related=False
            )
            for s in batch:
                s.container_id = container_id

        data = buffer.getvalue()
        return batch, data

Response: Get the next available item from the queue.


Instruction:
Can you implement a function in Python 3 that
establishes a connection with the server.

Response:
async def connect(self, timeout=None, ssl=None):
        """
        Establishes a connection with the server.
        """
        await self._connect(timeout=timeout, ssl=ssl)
        self._connected = True

        self._send_task = self._loop.create_task(self._send_loop())
        self._recv_task = self._loop.create_task(self._recv_loop())


Instruction:
Write a Python 3 function for
disconnecting from the server and clears pending outgoing and incoming messages.

Response:
async def disconnect(self):
        """
        Disconnects from the server, and clears
        pending outgoing and incoming messages.
        """
        self._connected = False

        await helpers._cancel(
            self._log,
            send_task=self._send_task,
            recv_task=self._recv_task
        )

        if self._writer:
            self._writer.close()
            if sys.version_info >= (3, 7):
                await self._writer.wait_closed()


Instruction:
Write a Python 3 function for
sending a packet through this connection mode.

Response:
def send(self, data):
        """
        Sends a packet of data through this connection mode.

        This method returns a coroutine.
        """
        if not self._connected:
            raise ConnectionError('Not connected')

        return self._send_queue.put(data)


Instruction:
Create a Python 3 function to
receive a packet of data through this connection mode. This method returns a coroutine which will return the value of the first available item in the receive queue.

Response:
async def recv(self):
        """
        Receives a packet of data through this connection mode.

        This method returns a coroutine.
        """
        while self._connected:
            result = await self._recv_queue.get()
            if result:  # None = sentinel value = keep trying
                return result

        raise ConnectionError('Not connected')


Instruction:
How would you explain what the following Python 3 function does
async def _send_loop(self):
        try:
            while self._connected:
                self._send(await self._send_queue.get())
                await self._writer.drain()
        except asyncio.CancelledError:
            pass
        except Exception as e:
            if isinstance(e, IOError):
                self._log.info('The server closed the connection while sending')
            else:
                self._log.exception('Unexpected exception in the send loop')

            await self.disconnect()

Response: This loop is constantly popping items off the send queue and sending them to the server.


Instruction:
Can you tell what is the following Python 3 function doing
async def _recv_loop(self):
        while self._connected:
            try:
                data = await self._recv()
            except asyncio.CancelledError:
                break
            except Exception as e:
                if isinstance(e, (IOError, asyncio.IncompleteReadError)):
                    msg = 'The server closed the connection'
                    self._log.info(msg)
                elif isinstance(e, InvalidChecksumError):
                    msg = 'The server response had an invalid checksum'
                    self._log.info(msg)
                else:
                    msg = 'Unexpected exception in the receive loop'
                    self._log.exception(msg)

                await self.disconnect()

                # Add a sentinel value to unstuck recv
                if self._recv_queue.empty():
                    self._recv_queue.put_nowait(None)

                break

            try:
                await self._recv_queue.put(data)
            except asyncio.CancelledError:
                break

Response: This loop is constantly putting items on the receive queue as they re read.


Instruction:
Here you have a function in Python 3, explain what it does
def _init_conn(self):
        if self._codec.tag:
            self._writer.write(self._codec.tag)

Response: Initialize the connection to Telegram.


Instruction:
How would you implement a function in Python 3 that
returns gzipped bytes if the gzipped data is smaller than the original byte array.

Response:
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


Instruction:
Here you have a function in Python 3, explain what it does
def sorted_args(self):
        return sorted(self.args,
                      key=lambda x: x.is_flag or x.can_be_inferred)

Response:
Returns the arguments properly sorted and ready to plug - in
           into a Python s method header.


Instruction:
Can you implement a function in Python 3 that
asserts that the connection is open and returns a cursor

Response:
def _cursor(self):
        """Asserts that the connection is open and returns a cursor"""
        if self._conn is None:
            self._conn = sqlite3.connect(self.filename,
                                         check_same_thread=False)
        return self._conn.cursor()


Instruction:
Explain what the following Python 3 code does
def _execute(self, stmt, *values):
        c = self._cursor()
        try:
            return c.execute(stmt, values).fetchone()
        finally:
            c.close()

Response: Executes a statement and returns the first row of the result set.


Instruction:
Given the following Python 3 function, write the documentation
def close(self):
        if self.filename != ':memory:':
            if self._conn is not None:
                self._conn.commit()
                self._conn.close()
                self._conn = None

Response: Closes the connection unless we re working in - memory


Instruction:
Write a Python 3 function that can
delete the current session file

Response:
def delete(self):
        """Deletes the current session file"""
        if self.filename == ':memory:':
            return True
        try:
            os.remove(self.filename)
            return True
        except OSError:
            return False


Instruction:
Create a Python 3 function to
list all the users who have ever connected using this client and never logged out

Response:
def list_sessions(cls):
        """Lists all the sessions of the users who have ever connected
           using this client and never logged out
        """
        return [os.path.splitext(os.path.basename(f))[0]
                for f in os.listdir('.') if f.endswith(EXTENSION)]


Instruction:
Given the following Python 3 function, write the documentation
def process_entities(self, tlo):
        if not self.save_entities:
            return

        rows = self._entities_to_rows(tlo)
        if not rows:
            return

        c = self._cursor()
        try:
            c.executemany(
                'insert or replace into entities values (?,?,?,?,?)', rows)
        finally:
            c.close()

Response: Processes all the found entities on the given TLObject. Returns True if new input entities were added.


Instruction:
Implement a function in Python 3 to
parse the input CSV file with columns method usability and errors and yields MethodInfo instances as a result.

Response:
def parse_methods(csv_file, errors_dict):
    """
    Parses the input CSV file with columns (method, usability, errors)
    and yields `MethodInfo` instances as a result.
    """
    with csv_file.open(newline='') as f:
        f = csv.reader(f)
        next(f, None)  # header
        for line, (method, usability, errors) in enumerate(f, start=2):
            try:
                errors = [errors_dict[x] for x in errors.split()]
            except KeyError:
                raise ValueError('Method {} references unknown errors {}'
                                 .format(method, errors)) from None

            yield MethodInfo(method, usability, errors)


Instruction:
Create a Python 3 function for
disconnecting from Telegram. If the event loop is already running, this method returns a coroutine that you should await on your own code; otherwise the loop is ran until said coroutine completes.

Response:
def disconnect(self):
        """
        Disconnects from Telegram.

        If the event loop is already running, this method returns a
        coroutine that you should await on your own code; otherwise
        the loop is ran until said coroutine completes.
        """
        if self._loop.is_running():
            return self._disconnect_coro()
        else:
            self._loop.run_until_complete(self._disconnect_coro())


Instruction:
Can you tell what is the following Python 3 function doing
async def _disconnect(self):
        await self._sender.disconnect()
        await helpers._cancel(self._log[__name__],
                              updates_handle=self._updates_handle)

Response: Disconnects from the client and cancels all pending updates.


Instruction:
Write a Python 3 script for
switching the current connection to the new data center.

Response:
async def _switch_dc(self, new_dc):
        """
        Permanently switches the current connection to the new data center.
        """
        self._log[__name__].info('Reconnecting to new data center %s', new_dc)
        dc = await self._get_dc(new_dc)

        self.session.set_dc(dc.id, dc.ip_address, dc.port)
        # auth_key's are associated with a server, which has now changed
        # so it's not valid anymore. Set to None to force recreating it.
        self._sender.auth_key.key = None
        self.session.auth_key = None
        self.session.save()
        await self._disconnect()
        return await self.connect()


Instruction:
Here you have a function in Python 3, explain what it does
def _auth_key_callback(self, auth_key):
        self.session.auth_key = auth_key
        self.session.save()

Response: Callback from the sender whenever we need to generate a new authorization key.


Instruction:
Can you implement a function in Python 3 that
gets the Data Center ( DC ) associated to dc_id

Response:
async def _get_dc(self, dc_id, cdn=False):
        """Gets the Data Center (DC) associated to 'dc_id'"""
        cls = self.__class__
        if not cls._config:
            cls._config = await self(functions.help.GetConfigRequest())

        if cdn and not self._cdn_config:
            cls._cdn_config = await self(functions.help.GetCdnConfigRequest())
            for pk in cls._cdn_config.public_keys:
                rsa.add_key(pk.public_key)

        return next(
            dc for dc in cls._config.dc_options
            if dc.id == dc_id
            and bool(dc.ipv6) == self._use_ipv6 and bool(dc.cdn) == cdn
        )


Instruction:
How would you explain what the following Python 3 function does
async def _create_exported_sender(self, dc_id):
        # Thanks badoualy/kotlogram on /telegram/api/DefaultTelegramClient.kt
        # for clearly showing how to export the authorization
        dc = await self._get_dc(dc_id)
        # Can't reuse self._sender._connection as it has its own seqno.
        #
        # If one were to do that, Telegram would reset the connection
        # with no further clues.
        sender = MTProtoSender(None, self._loop, loggers=self._log)
        await sender.connect(self._connection(
            dc.ip_address,
            dc.port,
            dc.id,
            loop=self._loop,
            loggers=self._log,
            proxy=self._proxy
        ))
        self._log[__name__].info('Exporting authorization for data center %s',
                                 dc)
        auth = await self(functions.auth.ExportAuthorizationRequest(dc_id))
        req = self._init_with(functions.auth.ImportAuthorizationRequest(
            id=auth.id, bytes=auth.bytes
        ))
        await sender.send(req)
        return sender

Response: Creates a new exported MTProtoSender for the given dc_id and returns it.


Instruction:
Can you generate the documentation for the following Python 3 function
async def _borrow_exported_sender(self, dc_id):
        async with self._borrow_sender_lock:
            n, sender = self._borrowed_senders.get(dc_id, (0, None))
            if not sender:
                sender = await self._create_exported_sender(dc_id)
                sender.dc_id = dc_id
            elif not n:
                dc = await self._get_dc(dc_id)
                await sender.connect(self._connection(
                    dc.ip_address,
                    dc.port,
                    dc.id,
                    loop=self._loop,
                    loggers=self._log,
                    proxy=self._proxy
                ))

            self._borrowed_senders[dc_id] = (n + 1, sender)

        return sender

Response: Borrows a connected MTProtoSender for the given dc_id. Returns a new instance of the appropriate class.


Instruction:
Implement a Python 3 function for
returning a borrowed exported sender.

Response:
async def _return_exported_sender(self, sender):
        """
        Returns a borrowed exported sender. If all borrows have
        been returned, the sender is cleanly disconnected.
        """
        async with self._borrow_sender_lock:
            dc_id = sender.dc_id
            n, _ = self._borrowed_senders[dc_id]
            n -= 1
            self._borrowed_senders[dc_id] = (n, sender)
            if not n:
                self._log[__name__].info(
                    'Disconnecting borrowed sender for DC %d', dc_id)
                await sender.disconnect()


Instruction:
Explain what the following Python 3 code does
async def _get_cdn_client(self, cdn_redirect):
        # TODO Implement
        raise NotImplementedError
        session = self._exported_sessions.get(cdn_redirect.dc_id)
        if not session:
            dc = await self._get_dc(cdn_redirect.dc_id, cdn=True)
            session = self.session.clone()
            await session.set_dc(dc.id, dc.ip_address, dc.port)
            self._exported_sessions[cdn_redirect.dc_id] = session

        self._log[__name__].info('Creating new CDN client')
        client = TelegramBareClient(
            session, self.api_id, self.api_hash,
            proxy=self._sender.connection.conn.proxy,
            timeout=self._sender.connection.get_timeout()
        )

        # This will make use of the new RSA keys for this specific CDN.
        #
        # We won't be calling GetConfigRequest because it's only called
        # when needed by ._get_dc, and also it's static so it's likely
        # set already. Avoid invoking non-CDN methods by not syncing updates.
        client.connect(_sync_updates=False)
        return client

Response: Get a new CDN client.


Instruction:
How would you implement a function in Python 3 that
turns the given iterable into chunks of the specified size.

Response:
def chunks(iterable, size=100):
    """
    Turns the given iterable into chunks of the specified size,
    which is 100 by default since that's what Telegram uses the most.
    """
    it = iter(iterable)
    size -= 1
    for head in it:
        yield itertools.chain([head], itertools.islice(it, size))


Instruction:
Write a Python 3 function for
getting the display name for the given entity. Returns an empty string if the given entity is not a user or chat or channel.

Response:
def get_display_name(entity):
    """
    Gets the display name for the given entity, if it's an :tl:`User`,
    :tl:`Chat` or :tl:`Channel`. Returns an empty string otherwise.
    """
    if isinstance(entity, types.User):
        if entity.last_name and entity.first_name:
            return '{} {}'.format(entity.first_name, entity.last_name)
        elif entity.first_name:
            return entity.first_name
        elif entity.last_name:
            return entity.last_name
        else:
            return ''

    elif isinstance(entity, (types.Chat, types.Channel)):
        return entity.title

    return ''


Instruction:
How would you explain what the following Python 3 function does
def get_extension(media):

    # Photos are always compressed as .jpg by Telegram
    if isinstance(media, (types.UserProfilePhoto,
                          types.ChatPhoto, types.MessageMediaPhoto)):
        return '.jpg'

    # Documents will come with a mime type
    if isinstance(media, types.MessageMediaDocument):
        media = media.document
    if isinstance(media, (
            types.Document, types.WebDocument, types.WebDocumentNoProxy)):
        if media.mime_type == 'application/octet-stream':
            # Octet stream are just bytes, which have no default extension
            return ''
        else:
            return guess_extension(media.mime_type) or ''

    return ''

Response: Gets the corresponding extension for any Telegram media.


Instruction:
Implement a Python 3 function for
getting the input peer for the given entity.

Response:
def get_input_peer(entity, allow_self=True, check_hash=True):
    """
    Gets the input peer for the given "entity" (user, chat or channel).

    A ``TypeError`` is raised if the given entity isn't a supported type
    or if ``check_hash is True`` but the entity's ``access_hash is None``.

    Note that ``check_hash`` **is ignored** if an input peer is already
    passed since in that case we assume the user knows what they're doing.
    This is key to getting entities by explicitly passing ``hash = 0``.
    """
    try:
        if entity.SUBCLASS_OF_ID == 0xc91c90b6:  # crc32(b'InputPeer')
            return entity
    except AttributeError:
        # e.g. custom.Dialog (can't cyclic import).
        if allow_self and hasattr(entity, 'input_entity'):
            return entity.input_entity
        elif hasattr(entity, 'entity'):
            return get_input_peer(entity.entity)
        else:
            _raise_cast_fail(entity, 'InputPeer')

    if isinstance(entity, types.User):
        if entity.is_self and allow_self:
            return types.InputPeerSelf()
        elif entity.access_hash is not None or not check_hash:
            return types.InputPeerUser(entity.id, entity.access_hash)
        else:
            raise TypeError('User without access_hash cannot be input')

    if isinstance(entity, (types.Chat, types.ChatEmpty, types.ChatForbidden)):
        return types.InputPeerChat(entity.id)

    if isinstance(entity, (types.Channel, types.ChannelForbidden)):
        if entity.access_hash is not None or not check_hash:
            return types.InputPeerChannel(entity.id, entity.access_hash)
        else:
            raise TypeError('Channel without access_hash cannot be input')

    if isinstance(entity, types.InputUser):
        return types.InputPeerUser(entity.user_id, entity.access_hash)

    if isinstance(entity, types.InputChannel):
        return types.InputPeerChannel(entity.channel_id, entity.access_hash)

    if isinstance(entity, types.InputUserSelf):
        return types.InputPeerSelf()

    if isinstance(entity, types.UserEmpty):
        return types.InputPeerEmpty()

    if isinstance(entity, types.UserFull):
        return get_input_peer(entity.user)

    if isinstance(entity, types.ChatFull):
        return types.InputPeerChat(entity.id)

    if isinstance(entity, types.PeerChat):
        return types.InputPeerChat(entity.chat_id)

    _raise_cast_fail(entity, 'InputPeer')


Instruction:
How would you explain what the following Python 3 function does
def get_input_channel(entity):
    try:
        if entity.SUBCLASS_OF_ID == 0x40f202fd:  # crc32(b'InputChannel')
            return entity
    except AttributeError:
        _raise_cast_fail(entity, 'InputChannel')

    if isinstance(entity, (types.Channel, types.ChannelForbidden)):
        return types.InputChannel(entity.id, entity.access_hash or 0)

    if isinstance(entity, types.InputPeerChannel):
        return types.InputChannel(entity.channel_id, entity.access_hash)

    _raise_cast_fail(entity, 'InputChannel')

Response: Similar to get_input_peer but for InputChannel s.


Instruction:
Given the following Python 3 function, write the documentation
def get_input_photo(photo):
    try:
        if photo.SUBCLASS_OF_ID == 0x846363e0:  # crc32(b'InputPhoto'):
            return photo
    except AttributeError:
        _raise_cast_fail(photo, 'InputPhoto')

    if isinstance(photo, types.photos.Photo):
        photo = photo.photo

    if isinstance(photo, types.Photo):
        return types.InputPhoto(id=photo.id, access_hash=photo.access_hash,
                                file_reference=photo.file_reference)

    if isinstance(photo, types.PhotoEmpty):
        return types.InputPhotoEmpty()

    if isinstance(photo, types.messages.ChatFull):
        photo = photo.full_chat
    if isinstance(photo, types.ChannelFull):
        return get_input_photo(photo.chat_photo)
    elif isinstance(photo, types.UserFull):
        return get_input_photo(photo.profile_photo)
    elif isinstance(photo, (types.Channel, types.Chat, types.User)):
        return get_input_photo(photo.photo)

    if isinstance(photo, (types.UserEmpty, types.ChatEmpty,
                          types.ChatForbidden, types.ChannelForbidden)):
        return types.InputPhotoEmpty()

    _raise_cast_fail(photo, 'InputPhoto')

Response: Similar to get_input_peer but for photos


Instruction:
How would you explain what the following Python 3 function does
def get_input_chat_photo(photo):
    try:
        if photo.SUBCLASS_OF_ID == 0xd4eb2d74:  # crc32(b'InputChatPhoto')
            return photo
        elif photo.SUBCLASS_OF_ID == 0xe7655f1f:  # crc32(b'InputFile'):
            return types.InputChatUploadedPhoto(photo)
    except AttributeError:
        _raise_cast_fail(photo, 'InputChatPhoto')

    photo = get_input_photo(photo)
    if isinstance(photo, types.InputPhoto):
        return types.InputChatPhoto(photo)
    elif isinstance(photo, types.InputPhotoEmpty):
        return types.InputChatPhotoEmpty()

    _raise_cast_fail(photo, 'InputChatPhoto')

Response: Similar to get_input_peer but for chat photos


Instruction:
Can you tell what is the following Python 3 function doing
def get_input_geo(geo):
    try:
        if geo.SUBCLASS_OF_ID == 0x430d225:  # crc32(b'InputGeoPoint'):
            return geo
    except AttributeError:
        _raise_cast_fail(geo, 'InputGeoPoint')

    if isinstance(geo, types.GeoPoint):
        return types.InputGeoPoint(lat=geo.lat, long=geo.long)

    if isinstance(geo, types.GeoPointEmpty):
        return types.InputGeoPointEmpty()

    if isinstance(geo, types.MessageMediaGeo):
        return get_input_geo(geo.geo)

    if isinstance(geo, types.Message):
        return get_input_geo(geo.media)

    _raise_cast_fail(geo, 'InputGeoPoint')

Response: Similar to get_input_peer but for GeoPoints


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_input_media(
        media, *,
        is_photo=False, attributes=None, force_document=False,
        voice_note=False, video_note=False, supports_streaming=False
):
    """
    Similar to :meth:`get_input_peer`, but for media.

    If the media is :tl:`InputFile` and ``is_photo`` is known to be ``True``,
    it will be treated as an :tl:`InputMediaUploadedPhoto`. Else, the rest
    of parameters will indicate how to treat it.
    """
    try:
        if media.SUBCLASS_OF_ID == 0xfaf846f4:  # crc32(b'InputMedia')
            return media
        elif media.SUBCLASS_OF_ID == 0x846363e0:  # crc32(b'InputPhoto')
            return types.InputMediaPhoto(media)
        elif media.SUBCLASS_OF_ID == 0xf33fdb68:  # crc32(b'InputDocument')
            return types.InputMediaDocument(media)
    except AttributeError:
        _raise_cast_fail(media, 'InputMedia')

    if isinstance(media, types.MessageMediaPhoto):
        return types.InputMediaPhoto(
            id=get_input_photo(media.photo),
            ttl_seconds=media.ttl_seconds
        )

    if isinstance(media, (types.Photo, types.photos.Photo, types.PhotoEmpty)):
        return types.InputMediaPhoto(
            id=get_input_photo(media)
        )

    if isinstance(media, types.MessageMediaDocument):
        return types.InputMediaDocument(
            id=get_input_document(media.document),
            ttl_seconds=media.ttl_seconds
        )

    if isinstance(media, (types.Document, types.DocumentEmpty)):
        return types.InputMediaDocument(
            id=get_input_document(media)
        )

    if isinstance(media, (types.InputFile, types.InputFileBig)):
        if is_photo:
            return types.InputMediaUploadedPhoto(file=media)
        else:
            attrs, mime = get_attributes(
                media,
                attributes=attributes,
                force_document=force_document,
                voice_note=voice_note,
                video_note=video_note,
                supports_streaming=supports_streaming
            )
            return types.InputMediaUploadedDocument(
                file=media, mime_type=mime, attributes=attrs)

    if isinstance(media, types.MessageMediaGame):
        return types.InputMediaGame(id=media.game.id)

    if isinstance(media, types.MessageMediaContact):
        return types.InputMediaContact(
            phone_number=media.phone_number,
            first_name=media.first_name,
            last_name=media.last_name,
            vcard=''
        )

    if isinstance(media, types.MessageMediaGeo):
        return types.InputMediaGeoPoint(geo_point=get_input_geo(media.geo))

    if isinstance(media, types.MessageMediaVenue):
        return types.InputMediaVenue(
            geo_point=get_input_geo(media.geo),
            title=media.title,
            address=media.address,
            provider=media.provider,
            venue_id=media.venue_id,
            venue_type=''
        )

    if isinstance(media, (
            types.MessageMediaEmpty, types.MessageMediaUnsupported,
            types.ChatPhotoEmpty, types.UserProfilePhotoEmpty,
            types.ChatPhoto, types.UserProfilePhoto,
            types.FileLocationToBeDeprecated)):
        return types.InputMediaEmpty()

    if isinstance(media, types.Message):
        return get_input_media(media.media, is_photo=is_photo)

    _raise_cast_fail(media, 'InputMedia')

Response: Returns a new InputMedia object for the given media.


Instruction:
Here you have a function in Python 3, explain what it does
def get_input_message(message):
    try:
        if isinstance(message, int):  # This case is really common too
            return types.InputMessageID(message)
        elif message.SUBCLASS_OF_ID == 0x54b6bcc5:  # crc32(b'InputMessage'):
            return message
        elif message.SUBCLASS_OF_ID == 0x790009e3:  # crc32(b'Message'):
            return types.InputMessageID(message.id)
    except AttributeError:
        pass

    _raise_cast_fail(message, 'InputMedia')

Response: Similar to get_input_peer but for input messages.


Instruction:
Here you have a function in Python 3, explain what it does
def get_message_id(message):
    if message is None:
        return None

    if isinstance(message, int):
        return message

    try:
        if message.SUBCLASS_OF_ID == 0x790009e3:
            # hex(crc32(b'Message')) = 0x790009e3
            return message.id
    except AttributeError:
        pass

    raise TypeError('Invalid message type: {}'.format(type(message)))

Response: Similar to get_input_peer but for message IDs.


Instruction:
Can you implement a function in Python 3 that
gets a list of attributes for the given file and mime type.

Response:
def get_attributes(file, *, attributes=None, mime_type=None,
                   force_document=False, voice_note=False, video_note=False,
                   supports_streaming=False):
    """
    Get a list of attributes for the given file and
    the mime type as a tuple ([attribute], mime_type).
    """
    # Note: ``file.name`` works for :tl:`InputFile` and some `IOBase` streams
    name = file if isinstance(file, str) else getattr(file, 'name', 'unnamed')
    if mime_type is None:
        mime_type = mimetypes.guess_type(name)[0]

    attr_dict = {types.DocumentAttributeFilename:
        types.DocumentAttributeFilename(os.path.basename(name))}

    if is_audio(file):
        m = _get_metadata(file)
        if m:
            attr_dict[types.DocumentAttributeAudio] = \
                types.DocumentAttributeAudio(
                    voice=voice_note,
                    title=m.get('title') if m.has('title') else None,
                    performer=m.get('author') if m.has('author') else None,
                    duration=int(m.get('duration').seconds
                                 if m.has('duration') else 0)
                )

    if not force_document and is_video(file):
        m = _get_metadata(file)
        if m:
            doc = types.DocumentAttributeVideo(
                round_message=video_note,
                w=m.get('width') if m.has('width') else 0,
                h=m.get('height') if m.has('height') else 0,
                duration=int(m.get('duration').seconds
                             if m.has('duration') else 0),
                supports_streaming=supports_streaming
            )
        else:
            doc = types.DocumentAttributeVideo(
                0, 1, 1, round_message=video_note,
                supports_streaming=supports_streaming)

        attr_dict[types.DocumentAttributeVideo] = doc

    if voice_note:
        if types.DocumentAttributeAudio in attr_dict:
            attr_dict[types.DocumentAttributeAudio].voice = True
        else:
            attr_dict[types.DocumentAttributeAudio] = \
                types.DocumentAttributeAudio(0, voice=True)

    # Now override the attributes if any. As we have a dict of
    # {cls: instance}, we can override any class with the list
    # of attributes provided by the user easily.
    if attributes:
        for a in attributes:
            attr_dict[type(a)] = a

    # Ensure we have a mime type, any; but it cannot be None
    # 'The "octet-stream" subtype is used to indicate that a body
    # contains arbitrary binary data.'
    if not mime_type:
        mime_type = 'application/octet-stream'

    return list(attr_dict.values()), mime_type


Instruction:
Can you create a Python 3 function that
sanitizes the given parse mode into an object with the appropriate parse and unparse callable properties.

Response:
def sanitize_parse_mode(mode):
    """
    Converts the given parse mode into an object with
    ``parse`` and ``unparse`` callable properties.
    """
    if not mode:
        return None

    if callable(mode):
        class CustomMode:
            @staticmethod
            def unparse(text, entities):
                raise NotImplementedError

        CustomMode.parse = mode
        return CustomMode
    elif (all(hasattr(mode, x) for x in ('parse', 'unparse'))
          and all(callable(x) for x in (mode.parse, mode.unparse))):
        return mode
    elif isinstance(mode, str):
        try:
            return {
                'md': markdown,
                'markdown': markdown,
                'htm': html,
                'html': html
            }[mode.lower()]
        except KeyError:
            raise ValueError('Unknown parse mode {}'.format(mode))
    else:
        raise TypeError('Invalid parse mode type {}'.format(mode))


Instruction:
Given the following Python 3 function, write the documentation
def get_input_location(location):
    try:
        if location.SUBCLASS_OF_ID == 0x1523d462:
            return None, location  # crc32(b'InputFileLocation'):
    except AttributeError:
        _raise_cast_fail(location, 'InputFileLocation')

    if isinstance(location, types.Message):
        location = location.media

    if isinstance(location, types.MessageMediaDocument):
        location = location.document
    elif isinstance(location, types.MessageMediaPhoto):
        location = location.photo

    if isinstance(location, types.Document):
        return (location.dc_id, types.InputDocumentFileLocation(
            id=location.id,
            access_hash=location.access_hash,
            file_reference=location.file_reference,
            thumb_size=''  # Presumably to download one of its thumbnails
        ))
    elif isinstance(location, types.Photo):
        return (location.dc_id, types.InputPhotoFileLocation(
            id=location.id,
            access_hash=location.access_hash,
            file_reference=location.file_reference,
            thumb_size=location.sizes[-1].type
        ))

    if isinstance(location, types.FileLocationToBeDeprecated):
        raise TypeError('Unavailable location cannot be used as input')

    _raise_cast_fail(location, 'InputFileLocation')

Response: Returns a tuple of dc_id and location for input messages.


Instruction:
Can you write a function in Python 3 where it
gets the extension for the given file.

Response:
def _get_extension(file):
    """
    Gets the extension for the given file, which can be either a
    str or an ``open()``'ed file (which has a ``.name`` attribute).
    """
    if isinstance(file, str):
        return os.path.splitext(file)[-1]
    elif isinstance(file, bytes):
        kind = imghdr.what(io.BytesIO(file))
        return ('.' + kind) if kind else ''
    elif isinstance(file, io.IOBase) and file.seekable():
        kind = imghdr.what(file)
        return ('.' + kind) if kind is not None else ''
    elif getattr(file, 'name', None):
        # Note: ``file.name`` works for :tl:`InputFile` and some `IOBase`
        return _get_extension(file.name)
    else:
        return ''


Instruction:
Can you write a function in Python 3 where it
returns True if the file extension looks like an image file to Telegram.

Response:
def is_image(file):
    """
    Returns ``True`` if the file extension looks like an image file to Telegram.
    """
    match = re.match(r'\.(png|jpe?g)', _get_extension(file), re.IGNORECASE)
    if match:
        return True
    else:
        return isinstance(resolve_bot_file_id(file), types.Photo)


Instruction:
How would you explain what the following Python 3 function does
def parse_phone(phone):
    if isinstance(phone, int):
        return str(phone)
    else:
        phone = re.sub(r'[+()\s-]', '', str(phone))
        if phone.isdigit():
            return phone

Response: Parses the given phone number or returns None if it s invalid.


Instruction:
Write a Python 3 function that can
parse the given username or channel access hash given a string username or URL. Returns a tuple consisting of the stripped lowercase username whether it is a joinchat or hash. Returns None if the given username or link is not valid.

Response:
def parse_username(username):
    """
    Parses the given username or channel access hash, given
    a string, username or URL. Returns a tuple consisting of
    both the stripped, lowercase username and whether it is
    a joinchat/ hash (in which case is not lowercase'd).

    Returns ``(None, False)`` if the ``username`` or link is not valid.
    """
    username = username.strip()
    m = USERNAME_RE.match(username) or TG_JOIN_RE.match(username)
    if m:
        username = username[m.end():]
        is_invite = bool(m.group(1))
        if is_invite:
            return username, True
        else:
            username = username.rstrip('/')

    if VALID_USERNAME_RE.match(username):
        return username.lower(), False
    else:
        return None, False


Instruction:
Can you implement a function in Python 3 that
gets the inner text that s surrounded by the given entities.

Response:
def get_inner_text(text, entities):
    """
    Gets the inner text that's surrounded by the given entities.
    For instance: text = 'hey!', entity = MessageEntityBold(2, 2) -> 'y!'.

    :param text:     the original text.
    :param entities: the entity or entities that must be matched.
    :return: a single result or a list of the text surrounded by the entities.
    """
    text = add_surrogate(text)
    result = []
    for e in entities:
        start = e.offset
        end = e.offset + e.length
        result.append(del_surrogate(text[start:end]))

    return result


Instruction:
Implement a function in Python 3 to
return the ID of the given peer.

Response:
def get_peer_id(peer, add_mark=True):
    """
    Finds the ID of the given peer, and converts it to the "bot api" format
    so it the peer can be identified back. User ID is left unmodified,
    chat ID is negated, and channel ID is prefixed with -100.

    The original ID and the peer type class can be returned with
    a call to :meth:`resolve_id(marked_id)`.
    """
    # First we assert it's a Peer TLObject, or early return for integers
    if isinstance(peer, int):
        return peer if add_mark else resolve_id(peer)[0]

    # Tell the user to use their client to resolve InputPeerSelf if we got one
    if isinstance(peer, types.InputPeerSelf):
        _raise_cast_fail(peer, 'int (you might want to use client.get_peer_id)')

    try:
        peer = get_peer(peer)
    except TypeError:
        _raise_cast_fail(peer, 'int')

    if isinstance(peer, types.PeerUser):
        return peer.user_id
    elif isinstance(peer, types.PeerChat):
        # Check in case the user mixed things up to avoid blowing up
        if not (0 < peer.chat_id <= 0x7fffffff):
            peer.chat_id = resolve_id(peer.chat_id)[0]

        return -peer.chat_id if add_mark else peer.chat_id
    else:  # if isinstance(peer, types.PeerChannel):
        # Check in case the user mixed things up to avoid blowing up
        if not (0 < peer.channel_id <= 0x7fffffff):
            peer.channel_id = resolve_id(peer.channel_id)[0]

        if not add_mark:
            return peer.channel_id

        # Concat -100 through math tricks, .to_supergroup() on
        # Madeline IDs will be strictly positive -> log works.
        return -(peer.channel_id + pow(
            10, math.floor(math.log10(peer.channel_id) + 3)))


Instruction:
Write a Python 3 function for
giving a marked ID returns the original ID and its peer type.

Response:
def resolve_id(marked_id):
    """Given a marked ID, returns the original ID and its :tl:`Peer` type."""
    if marked_id >= 0:
        return marked_id, types.PeerUser

    # There have been report of chat IDs being 10000xyz, which means their
    # marked version is -10000xyz, which in turn looks like a channel but
    # it becomes 00xyz (= xyz). Hence, we must assert that there are only
    # two zeroes.
    m = re.match(r'-100([^0]\d*)', str(marked_id))
    if m:
        return int(m.group(1)), types.PeerChannel

    return -marked_id, types.PeerChat


Instruction:
Make a summary of the following Python 3 code
def _rle_decode(data):
    if not data:
        return data

    new = b''
    last = b''
    for cur in data:
        if last == b'\0':
            new += last * cur
            last = b''
        else:
            new += last
            last = bytes([cur])

    return new + last

Response: Decode a run - length - encoded byte string into a single byte string.


Instruction:
Write a Python 3 function that can
decode a Telegram base64 - encoded string into its bytes .

Response:
def _decode_telegram_base64(string):
    """
    Decodes an url-safe base64-encoded string into its bytes
    by first adding the stripped necessary padding characters.

    This is the way Telegram shares binary data as strings,
    such as Bot API-style file IDs or invite links.

    Returns ``None`` if the input string was not valid.
    """
    try:
        return base64.urlsafe_b64decode(string + '=' * (len(string) % 4))
    except (binascii.Error, ValueError, TypeError):
        return None


Instruction:
Can you tell what is the following Python 3 function doing
def _encode_telegram_base64(string):
    try:
        return base64.urlsafe_b64encode(string).rstrip(b'=').decode('ascii')
    except (binascii.Error, ValueError, TypeError):
        return None

Response: Decodes a Telegram base64 string.


Instruction:
Write a Python 3 function that can
give a Bot API - style file_id returns the media it represents.

Response:
def resolve_bot_file_id(file_id):
    """
    Given a Bot API-style `file_id`, returns the media it represents.
    If the `file_id` is not valid, ``None`` is returned instead.

    Note that the `file_id` does not have information such as image
    dimensions or file size, so these will be zero if present.

    For thumbnails, the photo ID and hash will always be zero.
    """
    data = _rle_decode(_decode_telegram_base64(file_id))
    if not data or data[-1] == b'\x02':
        return None

    data = data[:-1]
    if len(data) == 24:
        file_type, dc_id, media_id, access_hash = struct.unpack('<iiqq', data)

        if not (1 <= dc_id <= 5):
            # Valid `file_id`'s must have valid DC IDs. Since this method is
            # called when sending a file and the user may have entered a path
            # they believe is correct but the file doesn't exist, this method
            # may detect a path as "valid" bot `file_id` even when it's not.
            # By checking the `dc_id`, we greatly reduce the chances of this
            # happening.
            return None

        attributes = []
        if file_type == 3 or file_type == 9:
            attributes.append(types.DocumentAttributeAudio(
                duration=0,
                voice=file_type == 3
            ))
        elif file_type == 4 or file_type == 13:
            attributes.append(types.DocumentAttributeVideo(
                duration=0,
                w=0,
                h=0,
                round_message=file_type == 13
            ))
        # elif file_type == 5:  # other, cannot know which
        elif file_type == 8:
            attributes.append(types.DocumentAttributeSticker(
                alt='',
                stickerset=types.InputStickerSetEmpty()
            ))
        elif file_type == 10:
            attributes.append(types.DocumentAttributeAnimated())

        return types.Document(
            id=media_id,
            access_hash=access_hash,
            date=None,
            mime_type='',
            size=0,
            thumbs=None,
            dc_id=dc_id,
            attributes=attributes,
            file_reference=b''
        )
    elif len(data) == 44:
        (file_type, dc_id, media_id, access_hash,
            volume_id, secret, local_id) = struct.unpack('<iiqqqqi', data)

        if not (1 <= dc_id <= 5):
            return None

        # Thumbnails (small) always have ID 0; otherwise size 'x'
        photo_size = 's' if media_id or access_hash else 'x'
        return types.Photo(
            id=media_id,
            access_hash=access_hash,
            file_reference=b'',
            date=None,
            sizes=[types.PhotoSize(
                type=photo_size,
                location=types.FileLocationToBeDeprecated(
                    volume_id=volume_id,
                    local_id=local_id
                ),
                w=0,
                h=0,
                size=0
            )],
            dc_id=dc_id,
            has_stickers=None
        )


Instruction:
Make a summary of the following Python 3 code
def pack_bot_file_id(file):
    if isinstance(file, types.MessageMediaDocument):
        file = file.document
    elif isinstance(file, types.MessageMediaPhoto):
        file = file.photo

    if isinstance(file, types.Document):
        file_type = 5
        for attribute in file.attributes:
            if isinstance(attribute, types.DocumentAttributeAudio):
                file_type = 3 if attribute.voice else 9
            elif isinstance(attribute, types.DocumentAttributeVideo):
                file_type = 13 if attribute.round_message else 4
            elif isinstance(attribute, types.DocumentAttributeSticker):
                file_type = 8
            elif isinstance(attribute, types.DocumentAttributeAnimated):
                file_type = 10
            else:
                continue
            break

        return _encode_telegram_base64(_rle_encode(struct.pack(
            '<iiqqb', file_type, file.dc_id, file.id, file.access_hash, 2)))

    elif isinstance(file, types.Photo):
        size = next((x for x in reversed(file.sizes) if isinstance(
            x, (types.PhotoSize, types.PhotoCachedSize))), None)

        if not size:
            return None

        size = size.location
        return _encode_telegram_base64(_rle_encode(struct.pack(
            '<iiqqqqib', 2, file.dc_id, file.id, file.access_hash,
            size.volume_id, 0, size.local_id, 2  # 0 = old `secret`
        )))
    else:
        return None

Response: Packs a bot file id into a base64 string.


Instruction:
Can you create a Python 3 function that
resolves the given invite link.

Response:
def resolve_invite_link(link):
    """
    Resolves the given invite link. Returns a tuple of
    ``(link creator user id, global chat id, random int)``.

    Note that for broadcast channels, the link creator
    user ID will be zero to protect their identity.
    Normal chats and megagroup channels will have such ID.

    Note that the chat ID may not be accurate for chats
    with a link that were upgraded to megagroup, since
    the link can remain the same, but the chat ID will
    be correct once a new link is generated.
    """
    link_hash, is_link = parse_username(link)
    if not is_link:
        # Perhaps the user passed the link hash directly
        link_hash = link

    try:
        return struct.unpack('>LLQ', _decode_telegram_base64(link_hash))
    except (struct.error, TypeError):
        return None, None, None


Instruction:
How would you explain what the following Python 3 function does
def resolve_inline_message_id(inline_msg_id):
    try:
        dc_id, message_id, pid, access_hash = \
            struct.unpack('<iiiq', _decode_telegram_base64(inline_msg_id))
        peer = types.PeerChannel(-pid) if pid < 0 else types.PeerUser(pid)
        return message_id, peer, dc_id, access_hash
    except (struct.error, TypeError):
        return None, None, None, None

Response: Resolves an inline message ID.


Instruction:
Write a Python 3 function for
converting a stripped photo to a JPG file.

Response:
def stripped_photo_to_jpg(stripped):
    """
    Adds the JPG header and footer to a stripped image.

    Ported from https://github.com/telegramdesktop/tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225
    """
    if len(stripped) < 3 or stripped[0] != 1:
        return stripped

    header = bytearray(b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00(\x1c\x1e#\x1e\x19(#!#-+(0<dA<77<{X]Id\x91\x80\x99\x96\x8f\x80\x8c\x8a\xa0\xb4\xe6\xc3\xa0\xaa\xda\xad\x8a\x8c\xc8\xff\xcb\xda\xee\xf5\xff\xff\xff\x9b\xc1\xff\xff\xff\xfa\xff\xe6\xfd\xff\xf8\xff\xdb\x00C\x01+--<5<vAAv\xf8\xa5\x8c\xa5\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xff\xc0\x00\x11\x08\x00\x00\x00\x00\x03\x01"\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x1f\x00\x00\x01\x05\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\xff\xc4\x00\xb5\x10\x00\x02\x01\x03\x03\x02\x04\x03\x05\x05\x04\x04\x00\x00\x01}\x01\x02\x03\x00\x04\x11\x05\x12!1A\x06\x13Qa\x07"q\x142\x81\x91\xa1\x08#B\xb1\xc1\x15R\xd1\xf0$3br\x82\t\n\x16\x17\x18\x19\x1a%&\'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\x83\x84\x85\x86\x87\x88\x89\x8a\x92\x93\x94\x95\x96\x97\x98\x99\x9a\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xff\xc4\x00\x1f\x01\x00\x03\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\xff\xc4\x00\xb5\x11\x00\x02\x01\x02\x04\x04\x03\x04\x07\x05\x04\x04\x00\x01\x02w\x00\x01\x02\x03\x11\x04\x05!1\x06\x12AQ\x07aq\x13"2\x81\x08\x14B\x91\xa1\xb1\xc1\t#3R\xf0\x15br\xd1\n\x16$4\xe1%\xf1\x17\x18\x19\x1a&\'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x92\x93\x94\x95\x96\x97\x98\x99\x9a\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xff\xda\x00\x0c\x03\x01\x00\x02\x11\x03\x11\x00?\x00')
    footer = b"\xff\xd9"
    header[164] = stripped[1]
    header[166] = stripped[2]
    return bytes(header) + stripped[3:] + footer


Instruction:
Can you tell what is the following Python 3 function doing
async def send(self, request):
        body = bytes(request)
        msg_id = self._state._get_new_msg_id()
        await self._connection.send(
            struct.pack('<qqi', 0, msg_id, len(body)) + body
        )

        body = await self._connection.recv()
        if len(body) < 8:
            raise InvalidBufferError(body)

        with BinaryReader(body) as reader:
            auth_key_id = reader.read_long()
            assert auth_key_id == 0, 'Bad auth_key_id'

            msg_id = reader.read_long()
            assert msg_id != 0,  'Bad msg_id'
            # ^ We should make sure that the read ``msg_id`` is greater
            # than our own ``msg_id``. However, under some circumstances
            # (bad system clock/working behind proxies) this seems to not
            # be the case, which would cause endless assertion errors.

            length = reader.read_int()
            assert length > 0,  'Bad length'
            # We could read length bytes and use those in a new reader to read
            # the next TLObject without including the padding, but since the
            # reader isn't used for anything else after this, it's unnecessary.
            return reader.tgread_object()

Response: Sends and receives the result for the given request.


Instruction:
Make a summary of the following Python 3 code
def _rel(self, path):
        return os.path.relpath(
            str(path), self._parent).replace(os.path.sep, '/')

Response:
Get the relative path for the given path from the current
            file.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write_head(self, title, css_path, default_css):
        self.title = title
        self.write(
            '''<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>{title}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link id="style" href="{rel_css}/docs.dark.css" rel="stylesheet">
    <script>
    document.getElementById("style").href = "{rel_css}/docs."
        + (localStorage.getItem("theme") || "{def_css}")
        + ".css";
    </script>
    <link href="https://fonts.googleapis.com/css?family=Nunito|Source+Code+Pro"
          rel="stylesheet">
</head>
<body>
<div id="main_div">''',
            title=title,
            rel_css=self._rel(css_path),
            def_css=default_css
        )

Response: Writes the head part for the generated document with the given title and CSS.


Instruction:
Write a Python 3 function for
setting the menu separator.

Response:
def set_menu_separator(self, img):
        """Sets the menu separator.
           Must be called before adding entries to the menu
        """
        if img:
            self.menu_separator_tag = '<img src="{}" alt="/" />'.format(
                self._rel(img))
        else:
            self.menu_separator_tag = None


Instruction:
Create a Python 3 function for
adding a menu entry. Will create it if it doesn t exist yet.

Response:
def add_menu(self, name, link=None):
        """Adds a menu entry, will create it if it doesn't exist yet"""
        if self.menu_began:
            if self.menu_separator_tag:
                self.write(self.menu_separator_tag)
        else:
            # First time, create the menu tag
            self.write('
')
            self.menu_began = True

        self.write('
')
        if link:
            self.write('', self._rel(link))

        # Write the real menu entry text
        self.write(name)

        if link:
            self.write('')
        self.write('
')


Instruction:
Write a Python 3 function that can
write a title header in the document body

Response:
def write_title(self, title, level=1, id=None):
        """Writes a title header in the document body,
           with an optional depth level
        """
        if id:
            self.write('<h{lv} id="{id}">{title}</h{lv}>',
                       title=title, lv=level, id=id)
        else:
            self.write('<h{lv}>{title}</h{lv}>',
                       title=title, lv=level)


Instruction:
Here you have a function in Python 3, explain what it does
def write_code(self, tlobject):
        self.write('
---{}---\n',
                   'functions' if tlobject.is_function else 'types')

        # Write the function or type and its ID
        if tlobject.namespace:
            self.write(tlobject.namespace)
            self.write('.')

        self.write('{}#{:08x}', tlobject.name, tlobject.id)

        # Write all the arguments (or do nothing if there's none)
        for arg in tlobject.args:
            self.write(' ')
            add_link = not arg.generic_definition and not arg.is_generic

            # "Opening" modifiers
            if arg.generic_definition:
                self.write('{')

            # Argument name
            self.write(arg.name)
            self.write(':')

            # "Opening" modifiers
            if arg.is_flag:
                self.write('flags.{}?', arg.flag_index)

            if arg.is_generic:
                self.write('!')

            if arg.is_vector:
                self.write('Vector<',
                           self.type_to_path('vector'))

            # Argument type
            if arg.type:
                if add_link:
                    self.write('', self.type_to_path(arg.type))
                self.write(arg.type)
                if add_link:
                    self.write('')
            else:
                self.write('#')

            # "Closing" modifiers
            if arg.is_vector:
                self.write('>')

            if arg.generic_definition:
                self.write('}')

        # Now write the resulting type (result from a function/type)
        self.write(' = ')
        generic_name = next((arg.name for arg in tlobject.args
                             if arg.generic_definition), None)

        if tlobject.result == generic_name:
            # Generic results cannot have any link
            self.write(tlobject.result)
        else:
            if re.search('^vector<', tlobject.result, re.IGNORECASE):
                # Notice that we don't simply make up the "Vector" part,
                # because some requests (as of now, only FutureSalts),
                # use a lower type name for it (see #81)
                vector, inner = tlobject.result.split('<')
                inner = inner.strip('>')
                self.write('{}<',
                           self.type_to_path(vector), vector)

                self.write('{}>',
                           self.type_to_path(inner), inner)
            else:
                self.write('{}',
                           self.type_to_path(tlobject.result), tlobject.result)

        self.write('
')

Response:
Writes the code for the given tlobject properly with hyperlinks
           .


Instruction:
Can you generate a brief explanation for the following Python 3 code
def begin_table(self, column_count):
        self.table_columns = column_count
        self.table_columns_left = 0
        self.write('<table>')

Response: Starts a table with the given column_count required to automatically generate the right amount of columns when adding items to the rows


Instruction:
Given the following Python 3 function, write the documentation
def write_copy_button(self, text, text_to_copy):
        self.write_copy_script = True
        self.write('<button onclick="cp(\'{}\');">{}</button>'
                   .format(text_to_copy, text))

Response:
Writes a button with text which can be used
           to copy text_to_copy to clipboard when it s clicked.


Instruction:
Make a summary of the following Python 3 code
def end_body(self):
        if self.write_copy_script:
            self.write(
                '<textarea id="c" class="invisible"></textarea>'
                ''
            )

        self.write('
{}', self._script)

Response: Ends the whole document. This should be called the last.


Instruction:
Write a Python 3 function for
wrapping around handle. write.

Response:
def write(self, s, *args, **kwargs):
        """Wrapper around handle.write"""
        if args or kwargs:
            self.handle.write(s.format(*args, **kwargs))
        else:
            self.handle.write(s)


Instruction:
How would you explain what the following Python 3 function does
def iter_participants(
            self, entity, limit=None, *, search='',
            filter=None, aggressive=False
    ):
        """
        Iterator over the participants belonging to the specified chat.

        Args:
            entity (`entity`):
                The entity from which to retrieve the participants list.

            limit (`int`):
                Limits amount of participants fetched.

            search (`str`, optional):
                Look for participants with this string in name/username.

                If ``aggressive is True``, the symbols from this string will
                be used.

            filter (:tl:`ChannelParticipantsFilter`, optional):
                The filter to be used, if you want e.g. only admins
                Note that you might not have permissions for some filter.
                This has no effect for normal chats or users.

                .. note::

                    The filter :tl:`ChannelParticipantsBanned` will return
                    *restricted* users. If you want *banned* users you should
                    use :tl:`ChannelParticipantsKicked` instead.

            aggressive (`bool`, optional):
                Aggressively looks for all participants in the chat.

                This is useful for channels since 20 July 2018,
                Telegram added a server-side limit where only the
                first 200 members can be retrieved. With this flag
                set, more than 200 will be often be retrieved.

                This has no effect if a ``filter`` is given.

        Yields:
            The :tl:`User` objects returned by :tl:`GetParticipantsRequest`
            with an additional ``.participant`` attribute which is the
            matched :tl:`ChannelParticipant` type for channels/megagroups
            or :tl:`ChatParticipants` for normal chats.
        """
        return _ParticipantsIter(
            self,
            limit,
            entity=entity,
            filter=filter,
            search=search,
            aggressive=aggressive
        )

Response: Returns an iterator over the participants in the specified chat.


Instruction:
How would you explain what the following Python 3 function does
def action(self, entity, action, *, delay=4, auto_cancel=True):
        if isinstance(action, str):
            try:
                action = _ChatAction._str_mapping[action.lower()]
            except KeyError:
                raise ValueError('No such action "{}"'.format(action)) from None
        elif not isinstance(action, types.TLObject) or action.SUBCLASS_OF_ID != 0x20b2cc21:
            # 0x20b2cc21 = crc32(b'SendMessageAction')
            if isinstance(action, type):
                raise ValueError('You must pass an instance, not the class')
            else:
                raise ValueError('Cannot use {} as action'.format(action))

        if isinstance(action, types.SendMessageCancelAction):
            # ``SetTypingRequest.resolve`` will get input peer of ``entity``.
            return self(functions.messages.SetTypingRequest(
                entity, types.SendMessageCancelAction()))

        return _ChatAction(
            self, entity, action, delay=delay, auto_cancel=auto_cancel)

Response: This function returns a context - manager object that represents a chat action.


Instruction:
Here you have a function in Python 3, explain what it does
async def prepare_decrypter(client, cdn_client, cdn_redirect):
        cdn_aes = AESModeCTR(
            key=cdn_redirect.encryption_key,
            # 12 first bytes of the IV..4 bytes of the offset (0, big endian)
            iv=cdn_redirect.encryption_iv[:12] + bytes(4)
        )

        # We assume that cdn_redirect.cdn_file_hashes are ordered by offset,
        # and that there will be enough of these to retrieve the whole file.
        decrypter = CdnDecrypter(
            cdn_client, cdn_redirect.file_token,
            cdn_aes, cdn_redirect.cdn_file_hashes
        )

        cdn_file = await cdn_client(GetCdnFileRequest(
            file_token=cdn_redirect.file_token,
            offset=cdn_redirect.cdn_file_hashes[0].offset,
            limit=cdn_redirect.cdn_file_hashes[0].limit
        ))
        if isinstance(cdn_file, CdnFileReuploadNeeded):
            # We need to use the original client here
            await client(ReuploadCdnFileRequest(
                file_token=cdn_redirect.file_token,
                request_token=cdn_file.request_token
            ))

            # We want to always return a valid upload.CdnFile
            cdn_file = decrypter.get_file()
        else:
            cdn_file.bytes = decrypter.cdn_aes.encrypt(cdn_file.bytes)
            cdn_hash = decrypter.cdn_file_hashes.pop(0)
            decrypter.check(cdn_file.bytes, cdn_hash)

        return decrypter, cdn_file

Response: Prepare a new CDN decrypter.


Instruction:
Can you implement a function in Python 3 that
calls GetCdnFileRequest and decrypts its bytes.

Response:
def get_file(self):
        """
        Calls GetCdnFileRequest and decrypts its bytes.
        Also ensures that the file hasn't been tampered.

        :return: the CdnFile result.
        """
        if self.cdn_file_hashes:
            cdn_hash = self.cdn_file_hashes.pop(0)
            cdn_file = self.client(GetCdnFileRequest(
                self.file_token, cdn_hash.offset, cdn_hash.limit
            ))
            cdn_file.bytes = self.cdn_aes.encrypt(cdn_file.bytes)
            self.check(cdn_file.bytes, cdn_hash)
        else:
            cdn_file = CdnFile(bytes(0))

        return cdn_file


Instruction:
Here you have a function in Python 3, explain what it does
def parse(html):
    if not html:
        return html, []

    parser = HTMLToTelegramParser()
    parser.feed(_add_surrogate(html))
    text = helpers.strip_text(parser.text, parser.entities)
    return _del_surrogate(text), parser.entities

Response: Parses the given HTML message and returns its stripped representation and a list of the MessageEntity s that were found.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def unparse(text, entities):
    if not text or not entities:
        return text

    text = _add_surrogate(text)
    html = []
    last_offset = 0
    for entity in entities:
        if entity.offset > last_offset:
            html.append(escape(text[last_offset:entity.offset]))
        elif entity.offset < last_offset:
            continue

        skip_entity = False
        entity_text = escape(text[entity.offset:entity.offset + entity.length])
        entity_type = type(entity)

        if entity_type == MessageEntityBold:
            html.append('{}'.format(entity_text))
        elif entity_type == MessageEntityItalic:
            html.append('{}'.format(entity_text))
        elif entity_type == MessageEntityCode:
            html.append('{}'.format(entity_text))
        elif entity_type == MessageEntityPre:
            if entity.language:
                html.append(
                    "
\n"
                    "    \n"
                    "        {}\n"
                    "    \n"
                    "
".format(entity.language, entity_text))
            else:
                html.append('
{}
'
                            .format(entity_text))
        elif entity_type == MessageEntityEmail:
            html.append('{0}'.format(entity_text))
        elif entity_type == MessageEntityUrl:
            html.append('{0}'.format(entity_text))
        elif entity_type == MessageEntityTextUrl:
            html.append('{}'
                        .format(escape(entity.url), entity_text))
        elif entity_type == MessageEntityMentionName:
            html.append('{}'
                        .format(entity.user_id, entity_text))
        else:
            skip_entity = True
        last_offset = entity.offset + (0 if skip_entity else entity.length)
    html.append(text[last_offset:])
    return _del_surrogate(''.join(html))

Response: This function performs the reverse operation to. parse effectively returning a HTML representation of the text and its MessageEntity s.


Instruction:
Can you generate the documentation for the following Python 3 function
def data(self):
        if isinstance(self.button, types.KeyboardButtonCallback):
            return self.button.data

Response: The bytes data for this button.


Instruction:
Make a summary of the following Python 3 code
def inline_query(self):
        if isinstance(self.button, types.KeyboardButtonSwitchInline):
            return self.button.query

Response: The query str for inline buttons.


Instruction:
Here you have a function in Python 3, explain what it does
def url(self):
        if isinstance(self.button, types.KeyboardButtonUrl):
            return self.button.url

Response: The url str for this button.


Instruction:
Here you have a function in Python 3, explain what it does
async def click(self):
        if isinstance(self.button, types.KeyboardButton):
            return await self._client.send_message(
                self._chat, self.button.text, reply_to=self._msg_id)
        elif isinstance(self.button, types.KeyboardButtonCallback):
            req = functions.messages.GetBotCallbackAnswerRequest(
                peer=self._chat, msg_id=self._msg_id, data=self.button.data
            )
            try:
                return await self._client(req)
            except BotTimeout:
                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):
            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 BotTimeout:
                return None

Response: Clicks the specified keyboard button.


Instruction:
How would you code a function in Python 3 to
resolve the event builders.

Response:
async def resolve(self, client):
        """Helper method to allow event builders to be resolved before usage"""
        if self.resolved:
            return

        if not self._resolve_lock:
            self._resolve_lock = asyncio.Lock(loop=client.loop)

        async with self._resolve_lock:
            if not self.resolved:
                await self._resolve(client)
                self.resolved = True


Instruction:
Can you generate a brief explanation for the following Python 3 code
def filter(self, event):
        if not self.resolved:
            return None

        if self.chats is not None:
            # Note: the `event.chat_id` property checks if it's `None` for us
            inside = event.chat_id in self.chats
            if inside == self.blacklist_chats:
                # If this chat matches but it's a blacklist ignore.
                # If it doesn't match but it's a whitelist ignore.
                return None

        if not self.func or self.func(event):
            return event

Response: Filter out events that are not in the set of chats.


Instruction:
Can you write a function in Python 3 where it
returns the entity and input entity pair for the given entity ID.

Response:
def _get_entity_pair(self, entity_id):
        """
        Returns ``(entity, input_entity)`` for the given entity ID.
        """
        entity = self._entities.get(entity_id)
        try:
            input_entity = utils.get_input_peer(entity)
        except TypeError:
            try:
                input_entity = self._client._entity_cache[entity_id]
            except KeyError:
                input_entity = None

        return entity, input_entity


Instruction:
Explain what the following Python 3 code does
def _load_entities(self):
        if not self._chat_peer:
            return True  # Nothing to load (e.g. MessageDeleted)

        self._chat, self._input_chat = self._get_entity_pair(self.chat_id)
        return self._input_chat is not None

Response: Load all the entities from cache and return True if all of them are loaded False otherwise.


Instruction:
Make a summary of the following Python 3 code
async def _get_difference(self, channel_id, pts_date):
        # Fetch since the last known pts/date before this update arrived,
        # in order to fetch this update at full, including its entities.
        self.client._log[__name__].debug('Getting difference for entities')
        if channel_id:
            try:
                where = await self.client.get_input_entity(channel_id)
            except ValueError:
                return

            result = await self.client(functions.updates.GetChannelDifferenceRequest(
                channel=where,
                filter=types.ChannelMessagesFilterEmpty(),
                pts=pts_date,  # just pts
                limit=100,
                force=True
            ))
        else:
            result = await self.client(functions.updates.GetDifferenceRequest(
                pts=pts_date[0],
                date=pts_date[1],
                qts=0
            ))

        if isinstance(result, (types.updates.Difference,
                               types.updates.DifferenceSlice,
                               types.updates.ChannelDifference,
                               types.updates.ChannelDifferenceTooLong)):
            self.original_update._entities.update({
                utils.get_peer_id(x): x for x in
                itertools.chain(result.users, result.chats)
            })

        if not self._load_entities():
            self.client._log[__name__].info(
                'Could not find all entities for update.pts = %s',
                getattr(self.original_update, 'pts', None)
            )

Response: Get the difference for this channel_id and pts_date.


Instruction:
Create a Python 3 function for
returning the chat if it s not already cached.

Response:
async def get_chat(self):
        """
        Returns `chat`, but will make an API call to find the
        chat unless it's already cached.
        """
        # 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


Instruction:
Can you tell what is the following Python 3 function doing
async def get_input_chat(self):
        if self.input_chat is None and self.chat_id:
            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

Response: Returns the input chat if it s not already cached.


Instruction:
Here you have a function in Python 3, explain what it does
def is_group(self):
        if self._broadcast is None and self.chat:
            self._broadcast = getattr(self.chat, 'broadcast', None)

        return (
            isinstance(self._chat_peer, (types.PeerChat, types.PeerChannel))
            and not self._broadcast
        )

Response: True if the message was sent on a group or megagroup.


Instruction:
Explain what the following Python 3 code does
def generate_random_long(signed=True):
    return int.from_bytes(os.urandom(8), signed=signed, byteorder='little')

Response: Generates a random long integer which is optionally signed


Instruction:
Make a summary of the following Python 3 code
def ensure_parent_dir_exists(file_path):
    parent = os.path.dirname(file_path)
    if parent:
        os.makedirs(parent, exist_ok=True)

Response: Ensures that the parent directory exists


Instruction:
Write a Python 3 script to
strip whitespace from the given text modifying the provided entities.

Response:
def strip_text(text, entities):
    """
    Strips whitespace from the given text modifying the provided entities.

    This assumes that there are no overlapping entities, that their length
    is greater or equal to one, and that their length is not out of bounds.
    """
    if not entities:
        return text.strip()

    while text and text[-1].isspace():
        e = entities[-1]
        if e.offset + e.length == len(text):
            if e.length == 1:
                del entities[-1]
                if not entities:
                    return text.strip()
            else:
                e.length -= 1
        text = text[:-1]

    while text and text[0].isspace():
        for i in reversed(range(len(entities))):
            e = entities[i]
            if e.offset != 0:
                e.offset -= 1
                continue

            if e.length == 1:
                del entities[0]
                if not entities:
                    return text.lstrip()
            else:
                e.length -= 1

        text = text[1:]

    return text


Instruction:
Make a summary of the following Python 3 code
async def _cancel(log, **tasks):
    for name, task in tasks.items():
        if not task:
            continue

        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            pass
        except Exception:
            log.exception('Unhandled exception from %s after cancel', name)

Response: Helper to cancel one or more tasks gracefully logging exceptions.


Instruction:
Write a Python 3 script for
helping to cut boilerplate on async context managers that offer synchronous variants.

Response:
def _sync_enter(self):
    """
    Helps to cut boilerplate on async context
    managers that offer synchronous variants.
    """
    if hasattr(self, 'loop'):
        loop = self.loop
    else:
        loop = self._client.loop

    if loop.is_running():
        raise RuntimeError(
            'You must use "async with" if the event loop '
            'is running (i.e. you are inside an "async def")'
        )

    return loop.run_until_complete(self.__aenter__())


Instruction:
Can you tell what is the following Python 3 function doing
def generate_key_data_from_nonce(server_nonce, new_nonce):
    server_nonce = server_nonce.to_bytes(16, 'little', signed=True)
    new_nonce = new_nonce.to_bytes(32, 'little', signed=True)
    hash1 = sha1(new_nonce + server_nonce).digest()
    hash2 = sha1(server_nonce + new_nonce).digest()
    hash3 = sha1(new_nonce + new_nonce).digest()

    key = hash1 + hash2[:12]
    iv = hash2[12:20] + hash3 + new_nonce[:4]
    return key, iv

Response: Generates the key data corresponding to the given nonce


Instruction:
Here you have a function in Python 3, explain what it does
def write(self, string, *args, **kwargs):
        if self.on_new_line:
            self.on_new_line = False  # We're not on a new line anymore
            # If the string was not empty, indent; Else probably a new line
            if string.strip():
                self.indent()

        if args or kwargs:
            self.out_stream.write(string.format(*args, **kwargs))
        else:
            self.out_stream.write(string)

Response:
Writes a string into the source code with indentation applied if required
            is True


Instruction:
How would you explain what the following Python 3 function does
def writeln(self, string='', *args, **kwargs):
        self.write(string + '\n', *args, **kwargs)
        self.on_new_line = True

        # If we're writing a block, increment indent for the next time
        if string and string[-1] == ':':
            self.current_indent += 1

        # Clear state after the user adds a new line
        self.auto_added_line = False

Response: Writes a string into the source code _and_ appends a new line


Instruction:
Implement a function in Python 3 to
end an indentation block leaving an empty line afterwards

Response:
def end_block(self):
        """Ends an indentation block, leaving an empty line afterwards"""
        self.current_indent -= 1

        # If we did not add a new line automatically yet, now it's the time!
        if not self.auto_added_line:
            self.writeln()
            self.auto_added_line = True


Instruction:
Can you write a function in Python 3 where it
writes the source code corresponding to the given TLObject.

Response:
def _write_source_code(tlobject, kind, builder, type_constructors):
    """
    Writes the source code corresponding to the given TLObject
    by making use of the ``builder`` `SourceBuilder`.

    Additional information such as file path depth and
    the ``Type: [Constructors]`` must be given for proper
    importing and documentation strings.
    """
    _write_class_init(tlobject, kind, type_constructors, builder)
    _write_resolve(tlobject, builder)
    _write_to_dict(tlobject, builder)
    _write_to_bytes(tlobject, builder)
    _write_from_reader(tlobject, builder)
    _write_read_result(tlobject, builder)


Instruction:
Can you tell what is the following Python 3 function doing
def _write_arg_to_bytes(builder, arg, args, name=None):
    if arg.generic_definition:
        return  # Do nothing, this only specifies a later type

    if name is None:
        name = 'self.{}'.format(arg.name)

    # The argument may be a flag, only write if it's not None AND
    # if it's not a True type.
    # True types are not actually sent, but instead only used to
    # determine the flags.
    if arg.is_flag:
        if arg.type == 'true':
            return  # Exit, since True type is never written
        elif arg.is_vector:
            # Vector flags are special since they consist of 3 values,
            # so we need an extra join here. Note that empty vector flags
            # should NOT be sent either!
            builder.write("b'' if {0} is None or {0} is False "
                          "else b''.join((", name)
        else:
            builder.write("b'' if {0} is None or {0} is False "
                          "else (", name)

    if arg.is_vector:
        if arg.use_vector_id:
            # vector code, unsigned 0x1cb5c415 as little endian
            builder.write(r"b'\x15\xc4\xb5\x1c',")

        builder.write("struct.pack('<i', len({})),", name)

        # Cannot unpack the values for the outer tuple through *[(
        # since that's a Python >3.5 feature, so add another join.
        builder.write("b''.join(")

        # Temporary disable .is_vector, not to enter this if again
        # Also disable .is_flag since it's not needed per element
        old_flag = arg.is_flag
        arg.is_vector = arg.is_flag = False
        _write_arg_to_bytes(builder, arg, args, name='x')
        arg.is_vector = True
        arg.is_flag = old_flag

        builder.write(' for x in {})', name)

    elif arg.flag_indicator:
        # Calculate the flags with those items which are not None
        if not any(f.is_flag for f in args):
            # There's a flag indicator, but no flag arguments so it's 0
            builder.write(r"b'\0\0\0\0'")
        else:
            builder.write("struct.pack('<I', ")
            builder.write(
                ' | '.join('(0 if {0} is None or {0} is False else {1})'
                           .format('self.{}'.format(flag.name),
                                   1 << flag.flag_index)
                           for flag in args if flag.is_flag)
            )
            builder.write(')')

    elif 'int' == arg.type:
        # struct.pack is around 4 times faster than int.to_bytes
        builder.write("struct.pack('<i', {})", name)

    elif 'long' == arg.type:
        builder.write("struct.pack('<q', {})", name)

    elif 'int128' == arg.type:
        builder.write("{}.to_bytes(16, 'little', signed=True)", name)

    elif 'int256' == arg.type:
        builder.write("{}.to_bytes(32, 'little', signed=True)", name)

    elif 'double' == arg.type:
        builder.write("struct.pack('<d', {})", name)

    elif 'string' == arg.type:
        builder.write('self.serialize_bytes({})', name)

    elif 'Bool' == arg.type:
        # 0x997275b5 if boolean else 0xbc799737
        builder.write(r"b'\xb5ur\x99' if {} else b'7\x97y\xbc'", name)

    elif 'true' == arg.type:
        pass  # These are actually NOT written! Only used for flags

    elif 'bytes' == arg.type:
        builder.write('self.serialize_bytes({})', name)

    elif 'date' == arg.type:  # Custom format
        builder.write('self.serialize_datetime({})', name)

    else:
        # Else it may be a custom type
        builder.write('bytes({})', name)

        # If the type is not boxed (i.e. starts with lowercase) we should
        # not serialize the constructor ID (so remove its first 4 bytes).
        boxed = arg.type[arg.type.find('.') + 1].isupper()
        if not boxed:
            builder.write('[4:]')

    if arg.is_flag:
        builder.write(')')
        if arg.is_vector:
            builder.write(')')  # We were using a tuple

    return True

Response: Writes the argument to the bytes representation of the given TLObject.


Instruction:
Given the following Python 3 function, write the documentation
def _write_arg_read_code(builder, arg, args, name):

    if arg.generic_definition:
        return  # Do nothing, this only specifies a later type

    # The argument may be a flag, only write that flag was given!
    was_flag = False
    if arg.is_flag:
        # Treat 'true' flags as a special case, since they're true if
        # they're set, and nothing else needs to actually be read.
        if 'true' == arg.type:
            builder.writeln('{} = bool(flags & {})',
                            name, 1 << arg.flag_index)
            return

        was_flag = True
        builder.writeln('if flags & {}:', 1 << arg.flag_index)
        # Temporary disable .is_flag not to enter this if
        # again when calling the method recursively
        arg.is_flag = False

    if arg.is_vector:
        if arg.use_vector_id:
            # We have to read the vector's constructor ID
            builder.writeln("reader.read_int()")

        builder.writeln('{} = []', name)
        builder.writeln('for _ in range(reader.read_int()):')
        # Temporary disable .is_vector, not to enter this if again
        arg.is_vector = False
        _write_arg_read_code(builder, arg, args, name='_x')
        builder.writeln('{}.append(_x)', name)
        arg.is_vector = True

    elif arg.flag_indicator:
        # Read the flags, which will indicate what items we should read next
        builder.writeln('flags = reader.read_int()')
        builder.writeln()

    elif 'int' == arg.type:
        builder.writeln('{} = reader.read_int()', name)

    elif 'long' == arg.type:
        builder.writeln('{} = reader.read_long()', name)

    elif 'int128' == arg.type:
        builder.writeln('{} = reader.read_large_int(bits=128)', name)

    elif 'int256' == arg.type:
        builder.writeln('{} = reader.read_large_int(bits=256)', name)

    elif 'double' == arg.type:
        builder.writeln('{} = reader.read_double()', name)

    elif 'string' == arg.type:
        builder.writeln('{} = reader.tgread_string()', name)

    elif 'Bool' == arg.type:
        builder.writeln('{} = reader.tgread_bool()', name)

    elif 'true' == arg.type:
        # Arbitrary not-None value, don't actually read "true" flags
        builder.writeln('{} = True', name)

    elif 'bytes' == arg.type:
        builder.writeln('{} = reader.tgread_bytes()', name)

    elif 'date' == arg.type:  # Custom format
        builder.writeln('{} = reader.tgread_date()', name)

    else:
        # Else it may be a custom type
        if not arg.skip_constructor_id:
            builder.writeln('{} = reader.tgread_object()', name)
        else:
            # Import the correct type inline to avoid cyclic imports.
            # There may be better solutions so that we can just access
            # all the types before the files have been parsed, but I
            # don't know of any.
            sep_index = arg.type.find('.')
            if sep_index == -1:
                ns, t = '.', arg.type
            else:
                ns, t = '.' + arg.type[:sep_index], arg.type[sep_index+1:]
            class_name = snake_to_camel_case(t)

            # There would be no need to import the type if we're in the
            # file with the same namespace, but since it does no harm
            # and we don't have information about such thing in the
            # method we just ignore that case.
            builder.writeln('from {} import {}', ns, class_name)
            builder.writeln('{} = {}.from_reader(reader)',
                            name, class_name)

    # End vector and flag blocks if required (if we opened them before)
    if arg.is_vector:
        builder.end_block()

    if was_flag:
        builder.current_indent -= 1
        builder.writeln('else:')
        builder.writeln('{} = None', name)
        builder.current_indent -= 1
        # Restore .is_flag
        arg.is_flag = True

Response: Writes the read code for the given argument.


Instruction:
Write a Python 3 script for
converting a Telegram s RPC Error to a Python error.

Response:
def rpc_message_to_error(rpc_error, request):
    """
    Converts a Telegram's RPC Error to a Python error.

    :param rpc_error: the RpcError instance.
    :param request: the request that caused this error.
    :return: the RPCError as a Python exception that represents this error.
    """
    # Try to get the error by direct look-up, otherwise regex
    cls = rpc_errors_dict.get(rpc_error.error_message, None)
    if cls:
        return cls(request)

    for msg_regex, cls in rpc_errors_re:
        m = re.match(msg_regex, rpc_error.error_message)
        if m:
            capture = int(m.group(1)) if m.groups() else None
            return cls(request, capture=capture)

    # Some errors are negative:
    # * -500 for "No workers running",
    # * -503 for "Timeout"
    #
    # We treat them as if they were positive, so -500 will be treated
    # as a `ServerError`, etc.
    cls = base_errors.get(abs(rpc_error.error_code))
    if cls:
        return cls(request, rpc_error.error_message)

    return RPCError(request, rpc_error.error_message, rpc_error.error_code)


Instruction:
Implement a function in Python 3 to
return True if the button belongs to an inline keyboard.

Response:
def _is_inline(button):
        """
        Returns ``True`` if the button belongs to an inline keyboard.
        """
        return isinstance(button, (
            types.KeyboardButtonCallback,
            types.KeyboardButtonSwitchInline,
            types.KeyboardButtonUrl
        ))


Instruction:
How would you explain what the following Python 3 function does
def inline(text, data=None):
        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)

Response: Create a new inline button.


Instruction:
Create a Python 3 function to
create a new button to switch to inline query.

Response:
def switch_inline(text, query='', same_peer=False):
        """
        Creates a new 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.
        """
        return types.KeyboardButtonSwitchInline(text, query, same_peer)


Instruction:
Write a Python 3 function that can
create a new keyboard button with the given text.

Response:
def text(cls, text, *, resize=None, single_use=None, selective=None):
        """
        Creates a new 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.
        """
        return cls(types.KeyboardButton(text),
                   resize=resize, single_use=single_use, selective=selective)


Instruction:
Make a summary of the following Python 3 code
def request_location(cls, text, *,
                         resize=None, single_use=None, selective=None):
        """
        Creates a new button that will request
        the user's location upon being clicked.

        ``resize``, ``single_use`` and ``selective`` are documented in `text`.
        """
        return cls(types.KeyboardButtonRequestGeoLocation(text),
                   resize=resize, single_use=single_use, selective=selective)

Response: Creates a new button that will request the user s location upon being clicked.


Instruction:
Write a Python 3 script to
create a new button that will request the user s phone number upon being clicked.

Response:
def request_phone(cls, text, *,
                      resize=None, single_use=None, selective=None):
        """
        Creates a new button that will request
        the user's phone number upon being clicked.

        ``resize``, ``single_use`` and ``selective`` are documented in `text`.
        """
        return cls(types.KeyboardButtonRequestPhone(text),
                   resize=resize, single_use=single_use, selective=selective)


Instruction:
Given the following Python 3 function, write the documentation
def sprint(string, *args, **kwargs):
    try:
        print(string, *args, **kwargs)
    except UnicodeEncodeError:
        string = string.encode('utf-8', errors='ignore')\
                       .decode('ascii', errors='ignore')
        print(string, *args, **kwargs)

Response: Safe Print (handle UnicodeEncodeErrors on some terminals)


Instruction:
Explain what the following Python 3 code does
def print_title(title):
    sprint('\n')
    sprint('=={}=='.format('=' * len(title)))
    sprint('= {} ='.format(title))
    sprint('=={}=='.format('=' * len(title)))

Response: Helper function to print titles to the console more nicely


Instruction:
Make a summary of the following Python 3 code
async def async_input(prompt):
    print(prompt, end='', flush=True)
    return (await loop.run_in_executor(None, sys.stdin.readline)).rstrip()

Response: A coroutine function that returns a string from stdin.