# Music in voice

> A music bot: /join, /play, /queue, /skip, /pause, /resume, /stop, /leave, and control buttons.

A complete [voice](/docs/guide/bots/voice-and-music/) bot. The host joins the voice channel as the bot and plays Ogg Opus files or streams from the hosts in its `network` grant.

Source in zaun-bot: [`examples/ts/music`](https://github.com/zaunchat/zaun-bot/tree/main/examples/ts/music) (TypeScript) and [`examples/rust/music`](https://github.com/zaunchat/zaun-bot/tree/main/examples/rust/music) (Rust).

## The code

**TypeScript:**

```ts title="src/index.ts"
// A music bot: `/join` a voice channel, `/play` an https:// Ogg Opus file or stream, `/queue`,
// `/skip`, `/pause`, `/resume`, `/stop`, `/leave`, and buttons on the now-playing message.
//
// The host fetches and plays the audio in real time; the bot only says what to play. URLs must
// be in the bot's `network` grant, and the audio must already be Opus: nothing is transcoded.

const bot = new Bot();

const controls = () => new ActionRowBuilder().addComponents(
  new ButtonBuilder().setCustomId('music:pause').setLabel('Pause').setEmoji('⏸️').setStyle(ButtonStyle.Secondary),
  new ButtonBuilder().setCustomId('music:resume').setLabel('Resume').setEmoji('▶️').setStyle(ButtonStyle.Secondary),
  new ButtonBuilder().setCustomId('music:skip').setLabel('Skip').setEmoji('⏭️').setStyle(ButtonStyle.Primary),
  new ButtonBuilder().setCustomId('music:stop').setLabel('Stop').setEmoji('⏹️').setStyle(ButtonStyle.Danger),
);

const STATUS = { idle: 'idle', playing: 'playing', paused: 'paused', 'auto-paused': 'waiting for listeners' } as const;

function queueText(): string {
  const s = bot.voice.state();
  const lines = [`Now ${STATUS[s.status]}: **${s.current ?? 'nothing'}**`];
  s.queued.forEach((t, n) => lines.push(`${n + 1}. ${t ?? 'untitled'}`));
  return lines.join('\n');
}

/** Runs `f`, answering the invoker privately with its result or the host's refusal. */
function act(i: Interaction, f: () => string): void {
  if (!i.isRepliable() || !('reply' in i)) return;
  try {
    i.reply({ content: f(), ephemeral: true });
  } catch (e) {
    i.reply({ content: `Could not do that: ${e instanceof ZaunError ? e.code : String(e)}`, ephemeral: true });
  }
}

const simple = (name: string, description: string, run: () => string) =>
  bot.command(new SlashCommandBuilder().setName(name).setDescription(description), (i) => act(i, run));

bot.command(
  new SlashCommandBuilder().setName('join').setDescription('Join a voice channel')
    .addChannelOption((o) => o.setName('channel').setDescription('A voice channel').setRequired(true)),
  (i) => {
    if (!i.isChatInputCommand()) return;
    const channel = i.options.getChannel('channel', true);
    try {
      bot.voice.join(channel?.channelId ?? '');
      i.reply({ content: 'Joined. 🎶', components: [controls()] });
    } catch (e) {
      i.reply({ content: `Could not join: ${e instanceof ZaunError ? e.code : String(e)}`, ephemeral: true });
    }
  },
);

bot.command(
  new SlashCommandBuilder().setName('play').setDescription('Play now, or queue if something is playing')
    .addStringOption((o) => o.setName('url').setDescription('An https:// Ogg Opus file or stream').setRequired(true).setMinLength(9).setMaxLength(500))
    .addStringOption((o) => o.setName('title').setDescription('What to call it').setMinLength(1).setMaxLength(80)),
  (i) => act(i, () => {
    if (!i.isChatInputCommand()) return '';
    const url = i.options.getString('url', true) ?? '';
    const title = i.options.getString('title') ?? url;
    if (bot.voice.state().status === 'idle') {
      bot.voice.play({ url, title });
      return `Playing **${title}**`;
    }
    return `Queued **${title}** (#${bot.voice.enqueue({ url, title })})`;
  }),
);

simple('queue', 'What is playing and what comes next', queueText);
simple('skip', 'Skip the current track', () => (bot.voice.skip(), 'Skipped.'));
simple('pause', 'Pause', () => (bot.voice.pause(), 'Paused.'));
simple('resume', 'Resume', () => (bot.voice.resume(), 'Resumed.'));
simple('stop', 'Stop and clear the queue', () => (bot.voice.stop(), 'Stopped.'));
simple('leave', 'Leave the voice channel', () => (bot.voice.leave(), 'Bye! 👋'));

bot.component('music:', (i) => act(i, () => {
  switch (i.customId) {
    case 'music:pause': bot.voice.pause(); return 'Paused.';
    case 'music:resume': bot.voice.resume(); return 'Resumed.';
    case 'music:skip': bot.voice.skip(); return 'Skipped.';
    default: bot.voice.stop(); return 'Stopped.';
  }
}));

// Members see "Listening to <track>" next to the bot while it plays.
bot.on('trackStart', (title) => bot.presence.set('online', Activity.listening(title ?? 'music')));
bot.on('trackEnd', () => bot.presence.set('online'));
bot.on('trackError', (error) => bot.log.warn(`track failed: ${error}`));
bot.on('voiceEnd', (reason) => {
  bot.presence.set('online');
  bot.log.info(`voice stay ended: ${reason ?? 'left'}`);
});

export const { init, onEvent, onInteraction, onAutocomplete, onTimer, onVoiceEvent } = bot.exports();
```

**Rust:**

```rust title="src/lib.rs"
//! A music bot: `/join` a voice channel, `/play` an `https://` Ogg Opus file or stream,
//! `/queue`, `/skip`, `/pause`, `/resume`, `/stop`, `/leave`, and buttons on the
//! now-playing message.
//!
//! The host fetches and plays the audio in real time; the bot only says what to play. URLs
//! must be in the bot's `network` grant, and the audio must already be Opus (`.opus`, or
//! `.ogg` holding Opus): nothing is transcoded.

use zaun_bot::prelude::*;
use zaun_bot::types::OptionKind;
use zaun_bot::voice::{PlayerStatus, VoiceEvent};

#[derive(Default)]
struct Music;

fn controls() -> ActionRow {
    ActionRow::buttons([
        Button::secondary("music:pause", "Pause").emoji("⏸️"),
        Button::secondary("music:resume", "Resume").emoji("▶️"),
        Button::primary("music:skip", "Skip").emoji("⏭️"),
        Button::danger("music:stop", "Stop").emoji("⏹️"),
    ])
}

/// A short reply only the invoker sees.
fn note(ctx: &Context, text: impl Into<String>) {
    let _ = ctx.reply(Reply::new().content(text).ephemeral());
}

fn queue_text() -> String {
    let state = Voice::state();
    let now = state.current.unwrap_or_else(|| "nothing".to_owned());
    let status = match state.status {
        PlayerStatus::Playing => "playing",
        PlayerStatus::Paused => "paused",
        PlayerStatus::AutoPaused => "waiting for listeners",
        PlayerStatus::Idle => "idle",
    };
    let mut text = format!("Now {status}: **{now}**");
    for (i, title) in state.queued.iter().enumerate() {
        let title = title.as_deref().unwrap_or("untitled");
        text.push_str(&format!("\n{}. {title}", i + 1));
    }
    text
}

impl Bot for Music {
    fn commands(&mut self, _: &Config) -> Vec<ApplicationCommand> {
        let channel =
            CommandOptionBuilder::new(OptionKind::Channel, "channel", "A voice channel").required();
        let url = CommandOptionBuilder::string("url", "An https:// Ogg Opus file or stream")
            .required()
            .length(9, 500);
        let title = CommandOptionBuilder::string("title", "What to call it").length(1, 80);
        vec![
            SlashCommand::new("join", "Join a voice channel")
                .option(channel)
                .build(),
            SlashCommand::new("play", "Play now, or queue if something is playing")
                .option(url)
                .option(title)
                .build(),
            SlashCommand::new("queue", "What is playing and what comes next").build(),
            SlashCommand::new("skip", "Skip the current track").build(),
            SlashCommand::new("pause", "Pause").build(),
            SlashCommand::new("resume", "Resume").build(),
            SlashCommand::new("stop", "Stop and clear the queue").build(),
            SlashCommand::new("leave", "Leave the voice channel").build(),
        ]
    }

    fn on_command(&mut self, ctx: Context, command: CommandData) {
        match command.name.as_str() {
            "join" => match command.str("channel").map(Voice::join) {
                Some(Ok(())) => {
                    let _ = ctx.reply(Reply::new().content("Joined. 🎶").row(controls()));
                }
                Some(Err(e)) => note(&ctx, format!("Could not join: {}", e.code)),
                None => note(&ctx, "Pick a voice channel."),
            },
            "play" => {
                let (Some(url), title) = (command.str("url"), command.str("title")) else {
                    return;
                };
                let title = title.unwrap_or(url);
                let idle = Voice::state().status == PlayerStatus::Idle;
                let done = if idle {
                    Voice::play_url(url, Some(title)).map(|()| format!("Playing **{title}**"))
                } else {
                    Voice::enqueue_url(url, Some(title))
                        .map(|n| format!("Queued **{title}** (#{n})"))
                };
                match done {
                    Ok(text) => {
                        let _ = ctx.reply(Reply::new().content(text).row(controls()));
                    }
                    Err(e) if e.code == "CONFLICT" => note(&ctx, "Use /join first."),
                    Err(e) => note(&ctx, format!("Could not play: {}", e.code)),
                }
            }
            "queue" => note(&ctx, queue_text()),
            "skip" => {
                Voice::skip();
                note(&ctx, "Skipped.");
            }
            "pause" => {
                Voice::pause();
                note(&ctx, "Paused.");
            }
            "resume" => {
                Voice::resume();
                note(&ctx, "Resumed.");
            }
            "stop" => {
                Voice::stop();
                note(&ctx, "Stopped, queue cleared.");
            }
            "leave" => {
                Voice::leave();
                note(&ctx, "Bye. 👋");
            }
            _ => {}
        }
    }

    fn on_component(&mut self, ctx: Context, component: ComponentData) {
        match component.custom_id.as_str() {
            "music:pause" => Voice::pause(),
            "music:resume" => Voice::resume(),
            "music:skip" => Voice::skip(),
            "music:stop" => Voice::stop(),
            _ => return,
        }
        let _ = ctx.update_message(Reply::new().content(queue_text()).row(controls()));
    }

    fn on_voice_event(&mut self, event: VoiceEvent) {
        match event {
            // Members see "Listening to <track>" next to the bot while it plays.
            VoiceEvent::TrackStart(title) => zaun_bot::presence::set(
                zaun_bot::presence::Status::Online,
                zaun_bot::presence::Activity::listening(title.unwrap_or_else(|| "music".into())),
            ),
            VoiceEvent::TrackEnd(_) => {
                zaun_bot::presence::set(zaun_bot::presence::Status::Online, None);
            }
            VoiceEvent::TrackError(e) => log_info!("track failed: {e}"),
            VoiceEvent::Ended(why) => {
                zaun_bot::presence::set(zaun_bot::presence::Status::Online, None);
                log_info!("left voice: {}", why.unwrap_or_default());
            }
            _ => {}
        }
    }
}

export_bot!(Music);
```

## The manifest

**TypeScript:**

```toml title="zaun-bot.toml"
app_id = "org.zaun.examples.ts-music"
version = "0.1.0"
name = "Music"
description = "Plays Ogg Opus files and streams in voice channels, with a queue and buttons."
permissions = ["VIEW_CHANNEL", "SEND_MESSAGES", "CONNECT", "SPEAK"]

[capabilities]
# Join voice channels and play audio.
voice = true
# The hosts the music comes from. The host fetches them, so they learn the host's address.
network = ["music.example.org"]
```

**Rust:**

```toml title="zaun-bot.toml"
app_id = "org.zaun.examples.music"
version = "0.1.0"
name = "Music"
description = "Plays Ogg Opus files and streams in voice channels, with a queue and buttons."
permissions = ["VIEW_CHANNEL", "SEND_MESSAGES", "CONNECT", "SPEAK"]

[capabilities]
# Join voice channels and play audio.
voice = true
# The hosts the music comes from. The host fetches them, so they learn the host's address.
network = ["music.example.org"]
```

## How it works

- `voice` is a capability the owner grants; `CONNECT` and `SPEAK` apply per channel as for members.
- `/join` joins the channel and posts control buttons (pause, resume, skip, stop).
- `/play` plays at once when nothing is playing, and queues otherwise; the host fetches each URL
  through the bot's network grant as it plays. `/queue` shows what is playing and what comes next.
- Every command and button answers the invoker privately, with the result or the host's refusal
  (for example `FORBIDDEN` without `CONNECT`).
- While a track plays, members see "Listening to" the track next to the bot; it clears when the
  track ends or the bot leaves ([Status and presence](/docs/guide/bots/status-and-presence/)).
- Track errors and the end of the voice stay are logged. Audio must already be Opus: convert other
  formats once with `ffmpeg -c:a libopus`.

## Run it

**TypeScript:**

```sh
git clone https://github.com/zaunchat/zaun-bot && cd zaun-bot/examples/ts/music
npm install
zbot build && zbot pack --unsigned
zaun-host bot install --community <ID> *.zbot   # on a host with allow_unsigned = true
```

**Rust:**

```sh
git clone https://github.com/zaunchat/zaun-bot && cd zaun-bot/examples/rust/music
zbot build && zbot pack --unsigned
zaun-host bot install --community <ID> *.zbot   # on a host with allow_unsigned = true
```
