Shard
Shard is responsible for managing a single WebSocket connection to Discord’s Gateway API. Its key responsibilities include:
- Establishing and maintaining a WebSocket connection
- Handling incoming messages:
- Decompressing ZLIB-compressed messages
- Decoding JSON payloads
- Invoking callbacks for processed messages
- Sending outgoing messages, including heartbeats
- Managing the heartbeat mechanism:
- Sending periodic heartbeats to keep the connection alive
- Tracking heartbeat acknowledgements
- Initiating reconnection if heartbeats are not acknowledged
- Handling reconnection logic when the connection becomes unstable or “zombified”
- Providing an interface for other parts of the application to interact with the WebSocket connection
The Shard module is crucial for maintaining real-time communication with Discord’s Gateway, ensuring the bot stays connected and can send and receive updates efficiently.
Summary
Properties
Shard.token :: SecretShard.intents :: numberShard.shardId :: numberShard.shardCount :: numberShard.shouldReconnect :: booleanShard.largeThreshold :: number?Shard.zlibBuffer :: AccumulatorShard.onSocketConnected :: Emitter<()>Shard.onSocketReconnected :: Emitter<number?>Shard.onSocketDisconnected :: Emitter<number?, boolean?>Shard.onSocketHeartbeat :: Emitter<number?>Shard.onSocketDispatch :: Emitter<apiTypes.Payload<unknown>>Shard.onSocketRawMessage :: Emitter<apiTypes.Payload<unknown>>Shard.onSocketReady :: Emitter<()>Shard.onSocketRateLimited :: Emitter<{ opcode: number, retryAfter: number, guildId: string? }>Shard.heartbeatAcknowledged :: boolean?Shard.heartbeatClockTime :: number?Shard.heartbeatInterval :: number?Shard.heartbeatThread :: thread?Shard.heartbeatPing :: number?Shard.lastSequence :: number?Shard.logger :: LoggerShard.socketActive :: booleanShard.socketReconnecting :: booleanShard.socketDisconnecting :: booleanShard.socketIdentified :: booleanShard.sessionId :: string?Shard.sessionGateway :: string?Shard.socketVersion :: number?Shard.socketUrl :: string?Shard.socketInstance :: any?Shard.socketThread :: thread?Shard.gatewaySendTimestamps :: { number }Methods
Shard:_handleMessage(message: string)Shard:heartbeatAsync(requested: boolean?)Shard:identifyAsync()Shard:forceClose(code: number?)Shard:disconnectAsync(code: number?)Shard:connectAsync(socketUrl: string, socketVersion: number)Shard:resumeAsync()Shard:reconnectAsync()Shard:sendAsync(data: string, ignoreRateLimit: boolean?)Shard:reinstantiateAsync(noFail: boolean?)Shard:heartbeatIn(milliseconds: number)Properties
Section titled “Properties”intents
Section titled “intents”shardId
Section titled “shardId”shardCount
Section titled “shardCount”shouldReconnect
Section titled “shouldReconnect”largeThreshold
Section titled “largeThreshold”zlibBuffer
Section titled “zlibBuffer”onSocketConnected
Section titled “onSocketConnected”onSocketReconnected
Section titled “onSocketReconnected”onSocketDisconnected
Section titled “onSocketDisconnected”onSocketHeartbeat
Section titled “onSocketHeartbeat”onSocketDispatch
Section titled “onSocketDispatch”onSocketRawMessage
Section titled “onSocketRawMessage”onSocketReady
Section titled “onSocketReady”onSocketRateLimited
Section titled “onSocketRateLimited”heartbeatAcknowledged
Section titled “heartbeatAcknowledged”heartbeatClockTime
Section titled “heartbeatClockTime”heartbeatInterval
Section titled “heartbeatInterval”heartbeatThread
Section titled “heartbeatThread”heartbeatPing
Section titled “heartbeatPing”lastSequence
Section titled “lastSequence”logger
Section titled “logger”socketActive
Section titled “socketActive”socketReconnecting
Section titled “socketReconnecting”socketDisconnecting
Section titled “socketDisconnecting”socketIdentified
Section titled “socketIdentified”sessionId
Section titled “sessionId”sessionGateway
Section titled “sessionGateway”socketVersion
Section titled “socketVersion”socketUrl
Section titled “socketUrl”socketInstance
Section titled “socketInstance”socketThread
Section titled “socketThread”gatewaySendTimestamps
Section titled “gatewaySendTimestamps”Rolling log of os.clock() timestamps for every non-heartbeat send, used to enforce Discord’s 120-events-per-60s gateway send rate limit.
Methods
Section titled “Methods”_handleMessage
Section titled “_handleMessage”Shard : _handleMessage ( message ) -> ()
Function responsible for handling incoming messages from the WebSocket connection.
It performs the following steps:
- Decompresses the incoming message if it’s ZLIB-compressed i. It’s worth noting that payloads may not be complete, meaning we should add data to the buffer until we have a complete message
- Decodes the JSON payload
- Invokes the appropriate callback based on the received event type
Roughly based on the following documentation: https://discord.com/developers/docs/topics/gateway#zlibstream
Parameters
| message: string |
heartbeatAsync
Section titled “heartbeatAsync”Shard : heartbeatAsync ( requested ) -> ()
Sends a heartbeat to the Discord Gateway API.
Parameters
| requested: boolean? |
identifyAsync
Section titled “identifyAsync”Shard : identifyAsync ( ) -> ()
Identifies the current shard with the Discord Gateway.
forceClose
Section titled “forceClose”Shard : forceClose ( code ) -> ()
Synchronously closes the shard’s socket and kills all associated threads. Safe to call from a signal handler or any context where yielding is not permitted.
Parameters
| code: number? |
disconnectAsync
Section titled “disconnectAsync”Shard : disconnectAsync ( code ) -> ()
Disconnects the Shard from the Discord Gateway.
Optionally, a WebSocket close code can be provided, websocket close code spec can be found here: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent/code
Parameters
| code: number? |
connectAsync
Section titled “connectAsync”Shard : connectAsync ( socketUrl , socketVersion ) -> ()
Connects the shard to a Discord Gateway.
Expects both a Socket URL, and Socket Version to be provided. It will prepend the socket version to the socket URL, and then connect to the socket.
Also responsible for spawning the thread that will be responsible for receiving messages from the socket.
resumeAsync
Section titled “resumeAsync”Shard : resumeAsync ( ) -> ()
Resumes a shard session if for some reason the session has either become zombified, or the session has been invalidated by Discord.
reconnectAsync
Section titled “reconnectAsync”Shard : reconnectAsync ( ) -> ()
Closes the websocket connection and reconnects the shard. This is not a re-instantiation of the shard, but a re-connection of the shard.
sendAsync
Section titled “sendAsync”Shard : sendAsync ( data , ignoreRateLimit ) -> ()
Sends a message through the WebSocket to Discords Gateway.
NOTE: Messages are expected to be JSON encoded strings.
Pass ignoreRateLimit = true to bypass the 120-events-per-60s send rate limit tracking.
This should only be used for op 1 (Heartbeat) sends, which Discord explicitly exempts.
reinstantiateAsync
Section titled “reinstantiateAsync”Shard : reinstantiateAsync ( noFail ) -> ()
Disconnects the Shard, and re-instantiats it.
Re-instantiation is the reconnection of the shard to the original socket passed, and not the session URL/ID that was passed.
Any events between the initial disconnection and reconnection will not be recovered. If this is
what you intend to do, use Shard:reconnectAsync instead.
Parameters
| noFail: boolean? |
heartbeatIn
Section titled “heartbeatIn”Shard : heartbeatIn ( milliseconds ) -> ()
Sends a heartbeat after milliseconds milliseconds, looping and continuing to heartbeat
until the shard is disconnected.
Parameters
| milliseconds: number |
Functions
Section titled “Functions”Shard . new ( settings ) -> Shard
Will instantiate a new Shard class.