Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Voice

A bot can join voice channels, play audio into them and hear what is said there. Voice lives in the djs-voice crate, which the voice feature plugs into the client:

djs-rs = { version = "0.1.0-alpha.2", features = ["voice"] }

It builds libopus from source and links it in, so building needs CMake and a C compiler. Playing anything but Ogg/Opus and raw PCM needs FFmpeg installed.

This chapter’s program is voice_call.rs: a small music bot playing the files of a music/ directory.

The client

    // GUILD_VOICE_STATES: the bot learns its own voice state (joining needs it) and, cached,
    // where everyone else is.
    let client = Client::builder(token)
        .intents(
            Intents::GUILDS
                | Intents::GUILD_VOICE_STATES
                | Intents::GUILD_MESSAGES
                | Intents::MESSAGE_CONTENT,
        )
        .cache(
            CacheConfig::builder()
                .voice_states(Limit::Unlimited)
                .build(),
        )
        .build();
    let voice = client.voice().clone();

client.voice() is the client’s VoiceManager: one per bot, with one Call per server. The manager sends the gateway’s voice requests through the right shard and follows the voice events by itself; a bot only joins and plays. The client needs the GUILD_VOICE_STATES intent, without which a join never completes; the cache of voice states tells the program which channel a user is in.

(discord.js: @discordjs/voice with joinVoiceChannel and guild.voiceAdapterCreator.)

Joining

/// `!join`: the author's voice channel, from the cache's voice states.
async fn join(
    ctx: &Context,
    voice: &VoiceManager,
    msg: &djs_rs::model::message::Message,
    guild_id: GuildId,
) -> Result<(), HandlerError> {
    let channel_id = ctx
        .cache()
        .and_then(|cache| cache.voice_states(guild_id).get(msg.author.id))
        .and_then(|state| state.channel_id)
        .ok_or("join a voice channel first")?;
    // Not deafened, to hear who speaks.
    let options = JoinOptions::new().self_deaf(false);
    let call = voice.join_with(guild_id, channel_id, options).await?;

    let mut events = call.events();
    tokio::spawn(async move {
        while let Some(event) = events.next().await {
            match event {
                CallEvent::SpeakingStarted(user) => println!("{user} speaks"),
                CallEvent::Disconnected(reason) => {
                    println!("left the call: {reason}");
                    break;
                }
                _ => {}
            }
        }
    });
    msg.reply(ctx, "Joined.").await?;
    Ok(())
}

join returns once the bot is connected and its call is encrypted. Every call is encrypted end to end with Discord’s DAVE protocol, which Discord requires of every client since March 2026; djs-voice does it with no setting. A bot joins deafened unless JoinOptions says otherwise: Discord sends a deafened bot nobody’s audio.

call.events() reports what happens in the call: users joining and leaving, who starts and stops speaking, and the disconnection, with its reason.

Playing

/// `!play <file>`: a file of `music/`, queued after the others. Only plain file names: the
/// name comes from a user, and FFmpeg would open any path or URL it is given.
fn play(call: &Call, name: &str) -> Result<String, HandlerError> {
    let name = name.trim();
    if name.is_empty() || name.starts_with('.') || name.contains(['/', '\\']) {
        return Err("give the name of a file in music/".into());
    }
    let path = Path::new("music").join(name);
    if !path.is_file() {
        return Err(format!("music/{name} does not exist").into());
    }
    call.enqueue(Input::ffmpeg(&path));
    Ok(format!(
        "Queued {name} ({} in the queue).",
        call.queue().len()
    ))
}

An Input is what a track plays:

  • Input::ogg_file and Input::ogg read Ogg/Opus, Discord’s own format, and send it as it is: no decoding, no encoding, a fraction of a CPU core for hundreds of calls.
  • Input::pcm reads raw 48 kHz stereo samples, encoded on the way.
  • Input::ffmpeg reads anything FFmpeg reads (MP3, FLAC, WAV, a URL…).

call.play plays a track now, call.enqueue after the others. Both return a TrackHandle: pause, play, stop, set_volume, seek, set_loop, its state (info) and its events (events).

Whatever FFmpeg is given, it opens: a path, a URL, a device. The program therefore takes only plain file names of its music/ directory from users. A bot that plays links should check them the same way (an allowed host, https:// only).

(discord.js: createAudioPlayer, createAudioResource, player.play; djs-voice has a queue of its own.)

The commands

    client.on(Events::MessageCreate, move |ctx, msg| {
        let voice = voice.clone();
        async move {
            let Some(guild_id) = msg.guild_id else {
                return Ok(());
            };
            let text = msg.content.trim();
            let (command, argument) = text.split_once(' ').unwrap_or((text, ""));
            if command == "!join" {
                return join(&ctx, &voice, &msg, guild_id).await;
            }
            // Every other command needs the bot in a call in this server.
            let Some(call) = voice.get(guild_id) else {
                return Ok(());
            };
            let answer = match command {
                "!play" => play(&call, argument)?,
                "!volume" => {
                    let volume: f32 = argument.trim().parse()?;
                    let track = call.queue().current().ok_or("nothing is playing")?;
                    // 1.0 is the file's own volume.
                    track.set_volume(volume.clamp(0.0, 2.0))?;
                    format!("Volume {volume}.")
                }
                "!skip" => {
                    call.queue().skip();
                    "Skipped.".to_owned()
                }
                "!leave" => {
                    call.leave().await?;
                    "Bye.".to_owned()
                }
                _ => return Ok(()),
            };
            msg.reply(&ctx, answer).await?;
            Ok(())
        }
    });

voice.get(guild) is the server’s call, if the bot is in one. call.queue() is its queue: current is the track playing, skip goes to the next one, clear empties it. leave ends the call.

Hearing

call.subscribe(user) returns a stream of that user’s audio: their packets in order, lost ones reported, as Opus or (ReceiveOptions::decode) as 48 kHz stereo samples, and EndBehavior ends it after a silence. Only the users a call is subscribed to are decrypted and decoded, so listening to one speaker in a crowded channel costs one speaker. The djs-voice README records a user until they stop speaking.

(discord.js: connection.receiver.subscribe.)

What’s next

The last chapter answers interactions over HTTP, without the gateway.