Event Dispatching
ðĒðĢðĢðĢ
The gateway's purpose is to enable real-time communication and dispatching of events between Discord and clients, so naturally the events received from the gateway needs to be dispatched within the bot application to be handled.
In DiscordKit, there are 2 steps involved before the event gets to the event dispatches exposed by the Client
: a custom event dispatcher (EventDispatch.swift
) and a wrapper (NCWrapper.swift
) over NotificationCenter
which provides a simple, less verbose and more swifty approach to dispatching and listening for events.
Let's take a look at how events travel from the gateway socket to an event listener!
Gateway
The gateway is a WebSocket, and payloads are encoded in JSON or ETF (unsupported for now). They can optionally be compressed (enabled by default in DiscordKit) with zlib-stream
. All the low-level communication with the gateway is handled by RobustWebSocket.swift
in the DiscordKitCore package, including identification, reconnection, heartbeats, and decoding and encoding of payloads. I won't bore you with the low-level details of the gateway communication protocol, it's literally worth a page on its own. RobustWebSocket
funnels all the decoded events (which are still quite hard to work with) through a simple event dispatcher, EventDispatch.swift
. From there, it's up to the listeners of gateway events to handle them. That brings us to the...
Low Level Event Dispatcher
The Client
object registers a listener on the event dispatcher of its instance of RobustWebSocket
and handles a small subset of events that might be dispatched.
To be continued...
Last updated