Skip to content

Connection

Coordinates a full Discord voice connection. Owns four sub-components:

  • webSocket - WebSocket lifecycle and heartbeating
  • udp - UDP socket, keepalive, and RTP audio send/receive
  • rtp - RTP encryption and sequence/timestamp/nonce counters
  • dave - DAVE E2EE MLS session and per-user key rotation

joinAsync starts a supervisor thread that owns every lifecycle decision: it sends op 4, waits for Discord's VOICE_STATE_UPDATE and VOICE_SERVER_UPDATE, connects, follows moves and server changes, resumes or rejoins after drops, and closes for good on a kick, a leave, a fatal close code or exhausted attempts, firing onClosed. Gateway events, socket closes and timers only record facts and wake it.

The gateway needs the GuildVoiceStates intent; without it Discord never sends the bot its own voice state, so a join fails at its timeout with VOICE_SERVER_UPDATE arrived but no VOICE_STATE_UPDATE; the gateway needs the GuildVoiceStates intent. Classes' channel:joinAsync checks the intent and fails at once instead.

Consumer-facing events: onReady, onResumed, onClosed, onSpeaking, onClientConnect, onClientDisconnect, onDaveEpochTransition, onMediaReady, onRawAudioFrame, onAudioFrame.

With DAVE, a ready connection may not carry audio yet: dave.mediaReady says whether it can, onMediaReady fires when it starts to, and awaitMediaReadyAsync waits for it.

Summary

Properties

Connection.webSocket :: voiceWebsocket.WebSocketTransportConnection.udp :: voiceUdp.UdpTransportConnection.rtp :: voiceRtpCrypto.RtpCryptoConnection.dave :: voiceDaveManager.DaveManagerConnection.jitters :: { [number]: voiceJitter.Jitter }Connection.shard :: websocket.ShardConnection.guildId :: stringConnection.channelId :: stringConnection.userId :: stringConnection.sessionId :: stringConnection.token :: secret.Secret<string>Connection.endpoint :: stringConnection.onConnected :: emitter.Emitter<()>Connection.onDisconnected :: emitter.Emitter<number?, boolean?>Connection.onReady :: emitter.Emitter<()>Connection.onHeartbeat :: emitter.Emitter<number?>Connection.onRawMessage :: emitter.Emitter<apiTypes.Payload<unknown>>Connection.onSpeaking :: emitter.Emitter<{ userId: string, ssrc: number, speaking: number }>Connection.onClientConnect :: emitter.Emitter<{ userId: string }>Connection.onClientDisconnect :: emitter.Emitter<{ userId: string }>Connection.onDaveEpochTransition :: emitter.Emitter<number>Connection.onMediaReady :: emitter.Emitter<()>Connection.onRawAudioFrame :: emitter.Emitter<{ userId: string?, ssrc: number, frame: buffer }>Connection.onAudioFrame :: emitter.Emitter<{ userId: string?, ssrc: number, frame: buffer }>Connection.decodeAudio :: booleanConnection.logger :: logger.LoggerConnection.status :: StatusConnection.generation :: numberConnection.closeReason :: CloseReason?Connection.closeDetail :: stringConnection.onClosed :: emitter.Emitter<CloseReason, number?>Connection.onResumed :: emitter.Emitter<()>Connection.onWake :: emitter.Emitter<()>Connection.recoveryAttempts :: numberConnection.lastFailure :: string
Connection.webSocket  :: WebSocketTransport
Connection.udp  :: UdpTransport
Connection.rtp  :: RtpCrypto
Connection.dave  :: DaveManager
Connection.jitters  :: {
{ [number]: voiceJitter.Jitter } }
Connection.shard  :: Shard
Connection.guildId  :: string
Connection.channelId  :: string
Connection.userId  :: string
Connection.sessionId  :: string

The voice session id from the bot's VOICE_STATE_UPDATE for this channel, empty until it arrives.

Connection.token  :: Secret<string>
Connection.endpoint  :: string
Connection.onConnected  :: Emitter<()>
Connection.onDisconnected  :: Emitter<number?, boolean?>
Connection.onReady  :: Emitter<()>

Fires once for each new session (the first join, a rejoin, a move or a server change) after status becomes ready; a resume fires onResumed instead. Every transition into ready fires one of the two.

Connection.onHeartbeat  :: Emitter<number?>
Connection.onRawMessage  :: Payload<unknown>
Connection.onClientConnect  :: Emitter<{ userId: string }>
Connection.onClientDisconnect  :: Emitter<{ userId: string }>
Connection.onDaveEpochTransition  :: Emitter<number>

Fires when a DAVE transition executes (op 22, or at once for transition 0) with the number of MLS group members, the bot included. After a group reset with nobody else in the channel that is 1. dave.mediaReady already has the transition's value when it fires.

Connection.onMediaReady  :: Emitter<()>

Fires when audio can start to flow: at Session Description without DAVE, and with DAVE once the bot holds the group's key (the transition that added it executed). Fires again after a group reset or reconnect once audio can flow again; dave.mediaReady has the current value.

Connection.onRawAudioFrame  :: Emitter<{ userId: string?, ssrc: number, frame: buffer }>

Fires with the Opus payload, the RTP header removed and every encryption layer (DAVE and the RTP cipher) already undone, once for each packet the jitter buffer plays, in sequence order and at its pace; lost and late packets are skipped. Wire-level ciphertext is never exposed.

Connection.onAudioFrame  :: Emitter<{ userId: string?, ssrc: number, frame: buffer }>

Fires with decoded stereo s16le 48 kHz PCM for one jitter slot (20 ms for 20 ms senders), loss concealment included. It stops about 100 ms after the speaker stops, and does not fire while decodeAudio is false.

Connection.decodeAudio  :: boolean

Whether received audio is decoded to PCM; true by default. While it is false the jitter buffers skip Opus decoding, loss concealment included, and onAudioFrame never fires, while onRawAudioFrame still does. A bot that only needs raw frames or speaking time sets it to save the decoding work. Each jitter slot reads it, so a change takes effect at once, and a decoder that sat idle is replaced before decoding resumes.

Connection.logger  :: Logger
Connection.status  :: Status

Where the connection is in its lifecycle: idle, signalling, connecting, ready, resuming, disconnected or closed.

Connection.generation  :: number

Bumped by every connect and by closing; a socket or op 4 that finishes for an older generation is discarded.

Connection.closeReason  :: CloseReason?

Why the connection closed, nil until it has.

Connection.closeDetail  :: string

A sentence saying why the connection closed, empty until it has.

Connection.onClosed  :: Emitter<CloseReason, number?>

Fires once when the connection closes for good, with the reason and the close code when there is one.

Connection.onResumed  :: Emitter<()>

Fires when a dropped voice session is resumed. onReady fires instead when a new session becomes ready (the first join, a rejoin, a move or a server change), once per connect.

Connection.onWake  :: Emitter<()>

Wakes the supervisor and joinAsync waiters after a fact is recorded, a timer expires or the status changes.

Connection.recoveryAttempts  :: number

Resume and rejoin attempts since the connection was last stable for 60 seconds.

Connection.lastFailure  :: string

Why the latest join, connect or rejoin attempt failed.

Connection : sendAsync ( data )  -> ()

Sends a raw message to the voice gateway WebSocket.

Parameters

data: string | buffer
Connection : connectAsync ( )  -> ()

Opens the voice WebSocket to endpoint. This is a low-level call: joinAsync connects on its own. Fails when a socket is already open or opening. Session state is preserved when resuming.

Connection : forceClose ( code )  -> ()

Closes the voice WebSocket at once. The supervisor treats this as a drop and recovers per the close code (1000 rejoins). To end the connection, use leaveAsync or destroy.

Parameters

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

Closes the connection for good, closing the socket with code (1000 by default), and asks Discord to take the bot out of the channel without waiting for the answer.

Parameters

code: number?
Connection : destroy ( )  -> ()

Closes the connection for good and asks Discord to take the bot out of the channel without waiting for the answer. Synchronous, so it is safe in a signal handler.

Connection : joinAsync ( timeoutSeconds )  -> ()

Joins the channel and resolves once the connection is ready. The first call starts the supervisor, which sends op 4 and gives up after timeoutSeconds (15 by default), closing the connection with joinTimedOut. A later call sends nothing, waits for the connection to be ready, and its own timeout fails only that call. Fails at once on a closed connection.

Parameters

timeoutSeconds: number?
Connection : awaitMediaReadyAsync ( timeoutSeconds )  -> ()

Resolves once audio can flow (dave.mediaReady), at once if it already can. Fails with timed out waiting for DAVE media readiness after timeoutSeconds (no limit when nil), or with voice connection closed: &lt;closeDetail&gt; when the connection closes first. Call it after joinAsync.

Parameters

timeoutSeconds: number?
Connection : requestVoiceAsync ( )  -> ()

The old name of joinAsync, kept for existing callers.

Connection : leaveAsync ( )  -> ()

Asks Discord to take the bot out of the channel (op 4 with a null channel), then closes the connection with left. A no-op on a closed connection.

Connection : reconnectAsync ( )  -> ()

Drops the current voice socket and rejoins, resolving once the connection is ready again. Fails when the connection was never joined or closes instead.

Connection : setSpeakingAsync ( speakingFlags )  -> ()

Sets the bot's speaking state. Pass a bitmask of speaking flags (Microphone = 1, Soundshare = 2, Priority = 4). Fails with cannot set speaking: SSRC not assigned before the voice server has assigned one, so op 5 never goes out without an ssrc, and fails when the send fails.

Parameters

speakingFlags: number
Connection : sendOpusAsync ( audioFrame )  -> ()

Encrypts and sends a raw Opus audio frame over UDP. With DAVE, until dave.mediaReady, Opus silence goes out in its place, so no audio leaves without end-to-end encryption.

Parameters

audioFrame: buffer
Connection . new ( settings )  -> Connection

Builds a connection for one guild's voice channel; joinAsync joins it. The settings:

  • shard: the gateway shard that carries guildId, which sends op 4 and receives the voice events;
  • guildId and channelId: the channel to join;
  • userId: the bot's user id, which picks the bot's own VOICE_STATE_UPDATE out of the guild's;
  • logLevel: the level of the connection's logger, VoiceConnection&lt;guildId&gt;, which its transports share.

Classes' channel:joinAsync() builds and joins one, and resolves with it.

Parameters

settings: {
shard: websocket.Shard,
guildId: string,
channelId: string,
userId: string,
logLevel: logger.LogLevel,
}

Returns

Connection