Connection
Coordinates a full Discord voice connection. Owns four sub-components:
webSocket- WebSocket lifecycle and heartbeatingudp- UDP socket, keepalive, and RTP audio send/receivertp- RTP encryption and sequence/timestamp/nonce countersdave- 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 :: stringMethods
Connection:sendAsync(data: string | buffer)Connection:connectAsync()Connection:forceClose(code: number?)Connection:disconnectAsync(code: number?)Connection:destroy()Connection:joinAsync(timeoutSeconds: number?)Connection:awaitMediaReadyAsync(timeoutSeconds: number?)Connection:requestVoiceAsync()Connection:leaveAsync()Connection:reconnectAsync()Connection:setSpeakingAsync(speakingFlags: number)Connection:sendOpusAsync(audioFrame: buffer)Properties
Section titled “Properties”webSocket
Section titled “webSocket”jitters
Section titled “jitters”{ [number]: voiceJitter.Jitter } }
guildId
Section titled “guildId”channelId
Section titled “channelId”userId
Section titled “userId”sessionId
Section titled “sessionId”The voice session id from the bot's VOICE_STATE_UPDATE for this channel, empty until it arrives.
endpoint
Section titled “endpoint”onConnected
Section titled “onConnected”onDisconnected
Section titled “onDisconnected”onReady
Section titled “onReady”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.
onHeartbeat
Section titled “onHeartbeat”onRawMessage
Section titled “onRawMessage”onSpeaking
Section titled “onSpeaking”onClientConnect
Section titled “onClientConnect”onClientDisconnect
Section titled “onClientDisconnect”onDaveEpochTransition
Section titled “onDaveEpochTransition”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.
onMediaReady
Section titled “onMediaReady”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.
onRawAudioFrame
Section titled “onRawAudioFrame”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.
onAudioFrame
Section titled “onAudioFrame”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.
decodeAudio
Section titled “decodeAudio”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.
logger
Section titled “logger”status
Section titled “status”Where the connection is in its lifecycle: idle, signalling, connecting, ready, resuming, disconnected
or closed.
generation
Section titled “generation”Bumped by every connect and by closing; a socket or op 4 that finishes for an older generation is discarded.
closeReason
Section titled “closeReason”Why the connection closed, nil until it has.
closeDetail
Section titled “closeDetail”A sentence saying why the connection closed, empty until it has.
onClosed
Section titled “onClosed”Fires once when the connection closes for good, with the reason and the close code when there is one.
onResumed
Section titled “onResumed”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.
onWake
Section titled “onWake”Wakes the supervisor and joinAsync waiters after a fact is recorded, a timer expires or the status changes.
recoveryAttempts
Section titled “recoveryAttempts”Resume and rejoin attempts since the connection was last stable for 60 seconds.
lastFailure
Section titled “lastFailure”Why the latest join, connect or rejoin attempt failed.
Methods
Section titled “Methods”sendAsync
Section titled “sendAsync”Connection : sendAsync ( data ) -> ()
Sends a raw message to the voice gateway WebSocket.
Parameters
| data: string | buffer |
connectAsync
Section titled “connectAsync”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.
forceClose
Section titled “forceClose”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? |
disconnectAsync
Section titled “disconnectAsync”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? |
destroy
Section titled “destroy”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.
joinAsync
Section titled “joinAsync”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? |
awaitMediaReadyAsync
Section titled “awaitMediaReadyAsync”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: <closeDetail> when
the connection closes first. Call it after joinAsync.
Parameters
| timeoutSeconds: number? |
requestVoiceAsync
Section titled “requestVoiceAsync”Connection : requestVoiceAsync ( ) -> ()
The old name of joinAsync, kept for existing callers.
leaveAsync
Section titled “leaveAsync”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.
reconnectAsync
Section titled “reconnectAsync”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.
setSpeakingAsync
Section titled “setSpeakingAsync”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 |
sendOpusAsync
Section titled “sendOpusAsync”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 |
Functions
Section titled “Functions”Connection . new ( settings ) -> Connection
Builds a connection for one guild's voice channel; joinAsync joins it. The settings:
shard: the gateway shard that carriesguildId, which sends op 4 and receives the voice events;guildIdandchannelId: 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<guildId>, 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 |