Skip to content
This repository has been archived by the owner on Jul 20, 2023. It is now read-only.

refactor!: dispatcher rewrite #27

Closed
wants to merge 16 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ dispatcher = discatcore.Dispatcher()
intents = 3243773
gateway = discatcore.GatewayClient(http, dispatcher, intents=intents.value)

@dispatcher.new_event("ready").callback
async def ready(event: discord_typings.ReadyData):
print(event)
@dispatcher.listen_to(discatcore.gateway.ReadyEvent)
async def ready(event):
print(event.data)

async def main():
url: str | None = None
Expand Down
2 changes: 2 additions & 0 deletions discatcore/gateway/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
"""

from .client import *
from .events import *
from .ratelimiter import *

__all__ = ()
__all__ += client.__all__
__all__ += events.__all__
__all__ += ratelimiter.__all__
28 changes: 15 additions & 13 deletions discatcore/gateway/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@

from ..errors import GatewayReconnect
from ..http import HTTPClient
from ..utils import json
from ..utils.dispatcher import Dispatcher
from ..utils.json import dumps, loads
from . import events
from .ratelimiter import Ratelimiter
from .types import BaseTypedWSMessage, is_binary, is_text

Expand Down Expand Up @@ -183,7 +184,7 @@ async def send(self, data: Mapping[str, t.Any]) -> None:
return

await self.ratelimiter.acquire()
await self._ws.send_json(data, dumps=dumps)
await self._ws.send_json(data, dumps=json.dumps)
_log.debug("Sent JSON payload %s to the Gateway.", data)

async def receive(self) -> t.Optional[bool]:
Expand Down Expand Up @@ -214,7 +215,7 @@ async def receive(self) -> t.Optional[bool]:
else:
received_msg = t.cast(str, typed_msg.data)

self.recent_payload = t.cast(dt.GatewayEvent, loads(received_msg))
self.recent_payload = t.cast(dt.GatewayEvent, json.loads(received_msg))
_log.debug("Received payload from the Gateway: %s", self.recent_payload)
self.sequence = self.recent_payload.get("s")
return True
Expand Down Expand Up @@ -279,32 +280,33 @@ async def connection_loop(self) -> None:

if res and self.recent_payload is not None:
op = int(self.recent_payload["op"])
if op == DISPATCH and self.recent_payload.get("t") is not None:
event_name = str(self.recent_payload.get("t")).lower()
data = self.recent_payload.get("d")
if op == DISPATCH and (event_name := self.recent_payload.get("t")) is not None:
data = t.cast(json.JSONObject, self.recent_payload.get("d"))

if event_name == "ready":
self._dispatcher.consume(event_name, self, data)
await self._dispatcher.dispatch(
events.DispatchEvent(t.cast(t.Mapping[str, t.Any], data))
)

if event_name == "READY":
ready_data = t.cast(dt.ReadyData, data)
self.session_id = ready_data["session_id"]
self.resume_url = ready_data["resume_gateway_url"]

args = (data,)
if data is None:
args = ()
self._dispatcher.dispatch(event_name, *args)
await self._dispatcher.dispatch(events.ReadyEvent(ready_data))

# these should be rare, but it's better to be safe than sorry
elif op == HEARTBEAT:
await self.heartbeat()

elif op == RECONNECT:
self._dispatcher.dispatch("reconnect")
await self._dispatcher.dispatch(events.ReconnectEvent())
await self.close(code=1012)
return

elif op == INVALID_SESSION:
self.can_resume = bool(self.recent_payload.get("d"))
self._dispatcher.dispatch("invalid_session", self.can_resume)
await self._dispatcher.dispatch(events.InvalidSessionEvent(self.can_resume))
await self.close(code=1012)
return

Expand Down
48 changes: 48 additions & 0 deletions discatcore/gateway/events.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# SPDX-License-Identifier: MIT
from __future__ import annotations

import typing as t

import attr
import discord_typings as dt

from ..utils.event import Event

__all__ = (
"GatewayEvent",
"DispatchEvent",
"InvalidSessionEvent",
"ReadyEvent",
"ReconnectEvent",
"ResumedEvent",
)


@attr.define
class GatewayEvent(Event):
pass


@attr.define
class DispatchEvent(GatewayEvent):
data: t.Mapping[str, t.Any]


@attr.define
class ReadyEvent(GatewayEvent):
data: dt.ReadyData


@attr.define
class ResumedEvent(GatewayEvent):
pass


@attr.define
class ReconnectEvent(GatewayEvent):
pass


@attr.define
class InvalidSessionEvent(GatewayEvent):
resumable: bool
Loading