Skip to content

Shard

Shard is responsible for managing a single WebSocket connection to Discord's Gateway API. Its key responsibilities include:

  1. Establishing and maintaining a WebSocket connection
  2. Handling incoming messages:
    • Decompressing ZLIB-compressed messages
    • Decoding JSON payloads
    • Invoking callbacks for processed messages
  3. Sending outgoing messages, including heartbeats
  4. Managing the heartbeat mechanism:
    • Sending periodic heartbeats to keep the connection alive
    • Tracking heartbeat acknowledgements
    • Initiating reconnection if heartbeats are not acknowledged
  5. Reconnecting through one reconnect loop that resumes the session when it can, identifies when it cannot, backs off between attempts, and only reconnects on its own when shouldReconnect is set
  6. 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

Shard.token  :: Secret
Shard.intents  :: number
Shard.shardId  :: number
Shard.shardCount  :: number
Shard.shouldReconnect  :: boolean
Shard.largeThreshold  :: number?
Shard.zlibBuffer  :: Accumulator
Shard.onSocketConnected  :: Emitter<()>
Shard.onSocketReconnected  :: Emitter<number?>
Shard.onSocketDisconnected  :: Emitter<number?, boolean?>
Shard.onSocketHeartbeat  :: Emitter<number?>
Shard.onSocketDispatch  :: Payload<unknown>
Shard.onSocketRawMessage  :: Payload<unknown>
Shard.onSocketReady  :: Emitter<()>
Shard.heartbeatAcknowledged  :: boolean?
Shard.heartbeatClockTime  :: number?
Shard.heartbeatInterval  :: number?
Shard.heartbeatThread  :: thread?
Shard.heartbeatJitter  :: () -> number

Returns the jitter in [0, 1) that scales heartbeatInterval into the wait before the first heartbeat. Defaults to math.random; tests replace it to pin the wait.

Shard.heartbeatPing  :: number?
Shard.lastSequence  :: number?
Shard.logger  :: Logger
Shard.socketActive  :: boolean
Shard.socketReconnecting  :: boolean
Shard.socketDisconnecting  :: boolean
Shard.socketIdentified  :: boolean
Shard.sessionId  :: string?
Shard.sessionGateway  :: string?
Shard.socketVersion  :: number?
Shard.socketUrl  :: string?
Shard.socketInstance  :: any?
Shard.socketThread  :: thread?
Shard.gatewaySendTimestamps  :: { number }

Rolling log of os.clock() timestamps for every non-heartbeat send, used to enforce Discord's 120-events-per-60s gateway send rate limit.

Shard.stayDisconnected  :: boolean

true while the shard stays down until an explicit connectAsync or reconnectAsync: after disconnectAsync or forceClose, a failed connectAsync, a fatal close code, a reconnect loop that threw, or an automatic reconnect while shouldReconnect is off.

Shard.sessionOutcome  :: SessionOutcome?

What the gateway answered on the current socket (READY, RESUMED, op 7 or op 9); read by the reconnect loop.

Shard.closeCode  :: number?

Close code the server sent when it last closed the shard's socket.

Shard.lastIdentifyTimestamp  :: number?

Unix time in seconds of the last IDENTIFY, used to keep reconnects under Discord's daily IDENTIFY limit.

Shard.socketGeneration  :: number

Counts sockets opened; an automatic reconnect raised by a socket that has since been replaced is dropped.

Shard : heartbeatAsync ( requested )  -> ()

Sends a heartbeat to the Discord Gateway API. When the previous heartbeat was never acknowledged and no reconnect is running, the socket is treated as zombified: an automatic reconnect is raised instead.

Parameters

requested: boolean?
Shard : identifyAsync ( )  -> ()

Identifies the current shard with the Discord Gateway, and records when it did so the reconnect loop can pace the next IDENTIFY.

Shard : sendResumeAsync ( )  -> ()

Sends op 6 Resume for the current session, carrying the last sequence seen so Discord replays what was missed.

Shard : forceClose ( code )  -> ()

Synchronously closes the shard's socket, ends its session and stops its threads, and keeps the shard down until connectAsync or reconnectAsync is called. Safe to call from a signal handler or any context where yielding is not permitted.

Parameters

code: number?
Shard : disconnectAsync ( code )  -> ()

Disconnects the Shard from the Discord Gateway and keeps it down until connectAsync or reconnectAsync is called.

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?
Shard : connectAsync ( socketUrl ,  socketVersion )  -> ()

Connects the shard to a Discord Gateway with a fresh session; the shard identifies as soon as Hello arrives.

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.

Resolves Err when the shard already has an open socket or the connection fails; a failed connection leaves the shard down. While a reconnect is running, it leaves the connection to that reconnect.

Parameters

socketUrl: string
socketVersion: number
Shard : resumeAsync ( )  -> ()

Reconnects the shard and resumes its session; the reconnect loop identifies instead when no session is left.

Shard : reconnectAsync ( )  -> ()

Closes the WebSocket connection and reconnects the shard, resuming the session when one exists. Retries with backoff until it succeeds, a fatal close code arrives, or the shard is closed. An explicit call always reconnects, whatever shouldReconnect says.

Shard : sendAsync ( data ,  ignoreRateLimit ,  isStillWanted )  -> ()

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.

Pass isStillWanted to cancel a send that is still waiting: it is called after any rate-limit wait, just before the socket send, and a false result drops the send (logged at debug) and resolves Ok.

Parameters

data: string
ignoreRateLimit: boolean?
isStillWanted: (() -> boolean)?
Shard : reinstantiateAsync ( )  -> ()

Ends the session and reconnects the shard with a fresh IDENTIFY on the original gateway URL.

Any events between the disconnection and the new session will not be recovered. If this is what you intend to avoid, use Shard:reconnectAsync instead.

Shard : heartbeatIn ( milliseconds )  -> ()

Sends a heartbeat after milliseconds milliseconds, looping and continuing to heartbeat until the socket it started on is closed or replaced, or the shard is told to stay disconnected.

Parameters

milliseconds: number
Shard . new ( settings )  -> Shard

Will instantiate a new Shard class.

Parameters

settings: Secret<string>

Returns

Shard