Skip to content

Music in voice

A complete voice 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 (TypeScript) and examples/rust/music (Rust).

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.
import { ActionRowBuilder, Activity, Bot, ButtonBuilder, ButtonStyle, SlashCommandBuilder, ZaunError, type Interaction } from '@zaun/bot';
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();
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"]
  • 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).
  • 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.
Terminal window
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