Build a Discord Bot That Writes Songs with an AI Song Generator API
In this guide
A song bot is one of the most fun things you can add to a Discord community. Someone types /song a sea shanty about our raid failing again, and a couple of minutes later the bot drops a finished track into the channel. In this tutorial we'll build exactly that with discord.js and an AI song generator API.
What You Need
- Node.js 18 or newer and a Discord application with a bot token (Discord Developer Portal).
- An API key for the AI Song Generator API. We use APIstable, a pay-per-request platform we like for side projects, where generations that fail cost nothing.
- The model identifier, listed on the model page.
Install the dependency and set your secrets as environment variables:
npm install discord.js
export DISCORD_TOKEN="your-bot-token"
export APISTABLE_API_KEY="your-api-key"
export MUSIC_MODEL_ID="model-id-from-the-model-page"
Step 1: Register the /song Command
Slash commands are registered once. This script adds /song with a required idea and an optional instrumental flag:
// register.js
import { REST, Routes, SlashCommandBuilder } from "discord.js";
const command = new SlashCommandBuilder()
.setName("song")
.setDescription("Turn an idea into a song")
.addStringOption((o) => o.setName("idea").setDescription("What should the song be about?").setRequired(true))
.addBooleanOption((o) => o.setName("instrumental").setDescription("No vocals"));
const rest = new REST().setToken(process.env.DISCORD_TOKEN);
await rest.put(Routes.applicationCommands(process.env.DISCORD_APP_ID), { body: [command.toJSON()] });
console.log("Registered /song");
Step 2: Talk to the Song API
Two small helpers: one creates a generation task in prompt mode, the other waits for it to finish.
// song-api.js
const BASE = "https://apistable.ai/api/v1/tasks";
const headers = {
Authorization: `Bearer ${process.env.APISTABLE_API_KEY}`,
"Content-Type": "application/json",
};
export async function createSong(idea, instrumental = false) {
const res = await fetch(`${BASE}/create_task`, {
method: "POST",
headers,
body: JSON.stringify({
model: process.env.MUSIC_MODEL_ID,
input: { custom_mode: false, instrumental, prompt: idea },
}),
});
const body = await res.json();
if (!body?.data?.task_id) throw new Error(body?.msg || "Could not create task");
return body.data.task_id;
}
export async function waitForSong(taskId, { intervalMs = 10000, timeoutMs = 10 * 60000 } = {}) {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
const { data } = await fetch(`${BASE}/${taskId}`, { headers }).then((r) => r.json());
if (data.status !== "processing") return data;
await new Promise((r) => setTimeout(r, intervalMs));
}
throw new Error("Timed out");
}
Step 3: Handle the Command
Discord expects a reply within three seconds, so defer the reply first, then edit it when the song is ready:
// bot.js
import { Client, GatewayIntentBits } from "discord.js";
import { createSong, waitForSong } from "./song-api.js";
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.on("interactionCreate", async (interaction) => {
if (!interaction.isChatInputCommand() || interaction.commandName !== "song") return;
const idea = interaction.options.getString("idea", true);
const instrumental = interaction.options.getBoolean("instrumental") ?? false;
await interaction.deferReply();
try {
const taskId = await createSong(idea, instrumental);
const task = await waitForSong(taskId);
if (task.status !== "succeeded") {
return interaction.editReply("That one didn't work out. Try rephrasing your idea!");
}
// task.result holds the generated tracks; log it once to see the fields for your model.
console.log(JSON.stringify(task.result));
await interaction.editReply(`🎵 Your song about **${idea}** is ready!`);
} catch (err) {
console.error(err);
await interaction.editReply("Something went wrong while making your song.");
}
});
client.login(process.env.DISCORD_TOKEN);
Once you've seen the shape of task.result for your model, attach the audio files (or post their links) in the final reply. Re-upload the audio to Discord instead of posting the raw links, since the URLs the API hands back expire after a while.
Step 4: Keep It Fun and Affordable
A song bot can get popular fast. Four guardrails keep it healthy:
- Per-user cooldowns. Allow one song per member every few minutes. A simple in-memory
Mapof user ID to timestamp is enough to start. - A daily server budget. Count requests per day and pause the command when you hit your limit.
- Prompt moderation. Block slurs, harassment and requests for copyrighted lyrics before sending anything to the API.
- Clear feedback. Post a "🎶 writing your song…" message right away so people know the bot is working.
Ideas to Extend the Bot
- Add a
lyricsoption and switch to custom mode (custom_mode: truewithtitle,styleandlyrics) for members who want to write their own words. - Create a weekly "server anthem" contest where members vote on generated tracks.
- Generate short instrumental intros for your streams or community events.
Just Want to Make a Song?
If you'd rather skip the code, you can create songs directly in Nafy: type an idea, pick a style, and listen in minutes. For developers who want songs inside their own apps and bots, start with the AI Song Generator API.