Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support JSON/dict payloads for sending and receiving. #170

Open
i0bs opened this issue Aug 4, 2022 · 0 comments
Open

Support JSON/dict payloads for sending and receiving. #170

i0bs opened this issue Aug 4, 2022 · 0 comments

Comments

@i0bs
Copy link

i0bs commented Aug 4, 2022

Right now, a developer must manually serialise and deserialise packets from or to a serialised JSON str of s. This leads towards writing unnecessary boilerplate such as this. I would very much appreciate the additional layer of abstraction being requested here if I could simply have send_message() taken dict as an acceptable type for its needed argument, and a way to specify receive_message(content_type=dict).

Instead, I have to resort to these utility methods. Courtesy of the retux repository.

    async def _send(self, payload: _GatewayPayload):
        """
        Sends a payload to the Gateway.
        Parameters
        ----------
        payload : `_GatewayPayload`
            The payload to send.
        """

        try:
            # Please note that asdict() is an attrs-specific method. dumps() is from the json dep.
            json = dumps(asdict(payload))
            resp = await self._conn.send_message(json)  # noqa
        except ConnectionClosed:
            logger.warning("The connection to Discord's Gateway has closed.")
            await self._conn.aclose()
            await self.reconnect()

    async def _receive(self) -> _GatewayPayload:
        """
        Receives the next incoming payload from the Gateway.
        Returns
        -------
        `_GatewayPayload`
            A class of the payload data.
        """

        try:
            resp = await self._conn.get_message()
            json = loads(resp)
            # structure_attrs_fromdict() is from the cattrs dep but
            # essentially acts as _GatewayPayload(**json)
            return structure_attrs_fromdict(json, _GatewayPayload)
        except ConnectionClosed:
            logger.warning("The connection to Discord's Gateway has closed.")
            self._closed = True
            await self.reconnect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant