detritus

Detritus Client Socket

A pure-TypeScript, low-level wrapper for Discord's Gateway and Voice connections.

[email protected] · MIT · github.com/detritusjs/client-socket

On this page

Overview

detritus-client-socket handles the websocket side of Discord: identifying, heartbeating, resuming, compression, and the voice gateway with its UDP transport. It hands you raw packets and leaves caching and structures to you (or to detritus-client, which is built on it).

ExportWhat it is
Gateway.SocketA connection to the main gateway. Emits every dispatch as a raw packet.
Media.SocketA connection to a voice server's gateway, created by voiceConnect().
MediaUdp.SocketThe UDP transport that sends and receives encrypted audio and video.
MediaMixer.AudioMixerMixes decoded PCM from several users into one stream.
ConstantsOpcodes, intents, close codes, activity types and more.

Installation

npm install detritus-client-socket@beta

The version this guide covers is published under npm's beta tag. latest is still the old 0.8.3.

Optional packages add features:

PackageWhat it enables
@snazzah/davey (^0.2.0)Required for voice. Discord has required end-to-end encryption (DAVE) since March 1st, 2026. Versions before 0.2.0 won't work.
sodium-native or libsodium-wrappersA faster aead_xchacha20_poly1305_rtpsize. Both voice encryption modes already run on Node's own crypto, so this is optional. aead_aes256_gcm_rtpsize is still picked whenever the voice server offers it, pass forceMode to use the sodium one.
erlpackThe etf encoding, which is smaller and faster to decode than JSON.
bufferutilFaster masking of the frames ws sends, ws picks it up automatically.

Connecting to the gateway

Create a Gateway.Socket with your token and options, then connect() to a gateway URL.

import { Constants, Gateway } from 'detritus-client-socket';

const socket = new Gateway.Socket(process.env.TOKEN!, {
  intents: ['GUILDS', 'GUILD_MESSAGES', 'MESSAGE_CONTENT'],
  presence: {
    activity: {name: 'something cool', type: Constants.GatewayActivityTypes.WATCHING},
    status: Constants.GatewayPresenceStatuses.DND,
  },
});

socket.on('ready', () => console.log('ready'));
socket.on('packet', (packet) => {
  if (packet.t === Constants.GatewayDispatchEvents.MESSAGE_CREATE) {
    console.log(`${packet.d.author.username}: ${packet.d.content}`);
  }
});
socket.on('close', ({code, reason}) => console.log('closed', code, reason));
socket.on('warn', console.error);

socket.connect('wss://gateway.discord.gg/');
const { Constants, Gateway } = require('detritus-client-socket');

const socket = new Gateway.Socket(process.env.TOKEN, {
  intents: ['GUILDS', 'GUILD_MESSAGES', 'MESSAGE_CONTENT'],
  presence: {
    activity: {name: 'something cool', type: Constants.GatewayActivityTypes.WATCHING},
    status: Constants.GatewayPresenceStatuses.DND,
  },
});

socket.on('ready', () => console.log('ready'));
socket.on('packet', (packet) => {
  if (packet.t === Constants.GatewayDispatchEvents.MESSAGE_CREATE) {
    console.log(`${packet.d.author.username}: ${packet.d.content}`);
  }
});
socket.on('close', ({code, reason}) => console.log('closed', code, reason));
socket.on('warn', console.error);

socket.connect('wss://gateway.discord.gg/');

The socket reconnects and resumes on its own (autoReconnect, on by default). Call socket.kill() to close it for good.

The close code decides whether the next connection resumes or identifies. socket.disconnect() closes with 1000 by default, which drops the session (session id, sequence and resume url) and doesn't reconnect on its own. Calling socket.connect() after it identifies from scratch, and Discord sends a new READY followed by a GUILD_CREATE for every guild. Codes 1000, 4007 and 4009 drop the session. 4004, 4010, 4011, 4012, 4013 and 4014 kill the socket. Any other code keeps the session, so the next connection resumes and only replays the events that were missed.

// restart the shard with a new session
socket.disconnect(1000, 'restarting');
socket.connect();

Socket options

OptionWhat it does
intents'ALL', 'ALL_UNPRIVILEGED' (the default), a bitfield, or a list of Constants.GatewayIntents names or numbers.
compresstrue, or a Constants.CompressTypes value: zlib-stream or zstd-stream.
encoding'json' or 'etf' (needs erlpack).
shardId, shardCountWhich shard this socket is.
largeThresholdMember count above which guilds arrive without their offline members.
presenceThe presence sent with the identify payload.
disabledEventsOnly stored. It is kept for detritus-client, which does the filtering. A bare socket still emits every packet.
reconnectDelay, reconnectMaxHow long to wait between reconnects and how many to try in a row before the socket is killed (default 5000 and 5). The wait doubles with each try, up to 60 seconds. Infinity never gives up.
voiceReconnectDelay, voiceReconnectMaxThe same for each voice connection, separate from the main gateway's (default 5000 and 5). After voiceReconnectMax tries the connection asks Discord for a new voice server, and after that many more it is killed.
onIdentifyCheckCalled before identifying. Return false to hold off and call socket.identify() yourself later, for example to share the identify ratelimit across processes.

Sending gateway commands

The socket has methods for the gateway's client-to-server opcodes:

// change the bot's status
socket.setPresence({status: 'idle', activity: {name: 'the logs', type: 3}});

// ask for members, they arrive as GUILD_MEMBERS_CHUNK packets
socket.requestGuildMembers(guildId, {query: 'ca', limit: 10});

// join, move or leave a voice channel (leave with a null channel id)
socket.voiceStateUpdate(guildId, channelId, {selfDeaf: true});

Anything else can be sent raw with socket.send(op, data), using Constants.GatewayOpCodes.

send() takes a callback as its third argument, and the callback runs once, when the packet was written or dropped. It gets no error once the packet was written. A send() made while the socket is disconnected isn't dropped. It waits in the queue and goes out after the next ready. If the packet was dropped, because the socket was killed or the session ended without a resume before the packet's turn came, it gets an error saying why. A dropped packet isn't sent again after a reconnect.

socket.send(Constants.GatewayOpCodes.PRESENCE_UPDATE, presence, (error) => {
  if (error) {
    console.warn('Presence not sent:', error.message);
  }
});

Voice

voiceConnect() sends the voice state update and resolves with a Media.Socket as soon as Discord answers with our voice state or the voice server, whichever comes first. The voice websocket isn't open yet at that point. Its transportReady event fires with the MediaUdp.Socket once audio can flow, and the media.transportReady getter says whether it still can (it stays true through a reconnect that resumes, and goes false when the voice session starts over). In an end-to-end encrypted call, frames are dropped until media.dave.canEncrypt, when the call's sending key arrives.

import { Constants, Gateway, Media } from 'detritus-client-socket';

const socket = new Gateway.Socket(process.env.TOKEN!, {compress: true});

let current: null | Media.Socket = null;
socket.on('ready', async () => {
  const media = await socket.voiceConnect(guildId, channelId, {receive: true});
  if (!media) {
    throw new Error('Failed to join the voice channel');
  }
  if (media === current) {
    // `ready` also fires after a resume, this media socket is already set up
    return;
  }
  current = media;
  media.on('warn', console.error);

  let isSetup = false;
  media.on('transportReady', (transport) => {
    media.sendSpeaking({voice: true});
    // a silence frame tells Discord to start sending us audio
    transport.sendAudioSilenceFrame();
    if (isSetup) {
      // fires again after reconnects, but the transport is reused
      return;
    }
    isSetup = true;

    // repeat one user's audio back into the channel
    transport.on('packet', (packet) => {
      if (packet.userId === repeatUserId && packet.rtp) {
        transport.sendAudioFrame(packet.data, {
          sequence: packet.rtp.header.sequence,
          timestamp: packet.rtp.header.timestamp,
        });
      }
    });
  });
});

socket.connect('wss://gateway.discord.gg/');
const { Constants, Gateway } = require('detritus-client-socket');

const socket = new Gateway.Socket(process.env.TOKEN, {compress: true});

let current = null;
socket.on('ready', async () => {
  const media = await socket.voiceConnect(guildId, channelId, {receive: true});
  if (!media) {
    throw new Error('Failed to join the voice channel');
  }
  if (media === current) {
    // `ready` also fires after a resume, this media socket is already set up
    return;
  }
  current = media;
  media.on('warn', console.error);

  let isSetup = false;
  media.on('transportReady', (transport) => {
    media.sendSpeaking({voice: true});
    // a silence frame tells Discord to start sending us audio
    transport.sendAudioSilenceFrame();
    if (isSetup) {
      // fires again after reconnects, but the transport is reused
      return;
    }
    isSetup = true;

    // repeat one user's audio back into the channel
    transport.on('packet', (packet) => {
      if (packet.userId === repeatUserId && packet.rtp) {
        transport.sendAudioFrame(packet.data, {
          sequence: packet.rtp.header.sequence,
          timestamp: packet.rtp.header.timestamp,
        });
      }
    });
  });
});

socket.connect('wss://gateway.discord.gg/');

Voice uses gateway v8 with the aead_aes256_gcm_rtpsize encryption mode. Received packets are already decrypted (and DAVE-decrypted); packet.data is Opus.

Mixing audio

MediaMixer.AudioMixer takes decoded PCM from several users and emits one mixed 20ms frame at a time, in Discord's format (48kHz, stereo). Decode each user's Opus with their own decoder, push the PCM in, and encode the mix back out.

import { OpusEncoder } from '@discordjs/opus';
import { MediaMixer } from 'detritus-client-socket';

const mixer = new MediaMixer.AudioMixer();
const encoder = new OpusEncoder(mixer.format.sampleRate, mixer.format.channels);

// for every received packet: mixer.push(userId, decoder.decode(packet.data), packet.rtp.header.timestamp)
mixer.on('data', (frame: Buffer) => {
  transport.sendAudioFrame(encoder.encode(frame));
});
// nothing is mixed or emitted until the mixer is started
mixer.start();
const { OpusEncoder } = require('@discordjs/opus');
const { MediaMixer } = require('detritus-client-socket');

const mixer = new MediaMixer.AudioMixer();
const encoder = new OpusEncoder(mixer.format.sampleRate, mixer.format.channels);

// for every received packet: mixer.push(userId, decoder.decode(packet.data), packet.rtp.header.timestamp)
mixer.on('data', (frame) => {
  transport.sendAudioFrame(encoder.encode(frame));
});
// nothing is mixed or emitted until the mixer is started
mixer.start();

The full version, with per-user decoders and silence handling, is in examples/ts/voice-mix-repeat.ts in the repository.

Namespaces

Grouped exports, reached as properties of the package.