EN ▾
Get API key

How to Set Up a TTS Bot on Discord with LLM Text

If you want to know how to set up tts bot discord, the practical route is a small discord.js bot that asks an LLM for the lines and posts them with the TTS flag. This page gives the code and the settings.

Updated

Chat bubbles turning into sound waves from a speaker, representing an LLM-written Discord TTS bot

Key points

  1. The API writes text only; Discord's TTS flag reads it aloud, or you add a separate speech engine for voice channels.
  2. Enable the Message Content intent and give the bot the Send Text-to-Speech Messages permission.
  3. Use model uncensored at https://api.nsfwtts.com/v1 with the openai package; keep requests under 8 at once.
  4. A system prompt with no formatting and a short length cap makes text sound natural when read aloud.

What this setup does and does not do

A Discord TTS bot can mean two different things, so decide which one you want before writing code. The first is a bot that posts messages with Discord's text-to-speech flag set, so that members who have the option enabled hear the message read aloud by their own client. The second is a bot that joins a voice channel and plays synthesized audio. The second needs a speech engine that produces audio files or streams, and that is a separate service.

The API on this site is a text model. It does not produce audio. What it does well is write the words: a narrator's lines, an in-character reply, a nightly announcement in a persona you define, a roleplay game master. In this guide the LLM produces the text and Discord's own TTS flag reads it out. If you later want voice-channel playback, you keep the same text step and add a speech engine after it. The TTS integration guide on this site covers the speech side.

The workflow is simple enough to hold in your head:

  1. A member types a command such as !say the harbor at midnight.
  2. Your bot sends the topic and a system prompt to the chat completions endpoint.
  3. The model returns a short passage.
  4. The bot posts it to the channel with tts: true.

Step 1: create the Discord application

In the Discord Developer Portal, create an application and add a bot to it. Copy the bot token and keep it out of your source files. Then:

  • On the Bot page, turn on the Message Content privileged intent. Without it the bot cannot read the text after !say.
  • In the OAuth2 URL generator, choose the bot scope and give the bot the permissions View Channels, Send Messages and Send Text-to-Speech Messages.
  • Open the generated URL and add the bot to your server.

A bot that sits in a private test server is the safest place to start. Use a channel only you can see while you tune the prompt.

Members hear a TTS message only if text-to-speech is enabled in their own client's notification settings, and the channel permissions allow it. If nobody hears anything, check those two things first, because the bot posting the message and a client reading it aloud are separate steps.

Step 2: get an API key and test the endpoint

Create an account on the API key page. Sign-up is with Google or with email and password, and a new account can claim $0.50 of trial credit with one click, no card needed. Top-ups after that are paid in crypto (USDT on TRC20 or USDC on Base). Then confirm the key works with a plain request:

curl https://api.nsfwtts.com/v1/chat/completions \
  -H "Authorization: Bearer $LLM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "messages": [
      {"role": "system", "content": "You are a dramatic narrator. Reply in at most three sentences."},
      {"role": "user", "content": "The harbor at midnight"}
    ],
    "max_tokens": 200
  }'

You should get back a JSON body with a choices array. The text is in choices[0].message.content. If the call fails, fix it here, before adding Discord into the picture.

Step 3: the bot code

This example uses Node 18 or newer, discord.js version 14 and the official openai package, pointed at the base URL. Install with npm install discord.js openai and run the file as an ES module.

import { Client, Events, GatewayIntentBits } from "discord.js";
import OpenAI from "openai";

const llm = new OpenAI({
  baseURL: "https://api.nsfwtts.com/v1",
  apiKey: process.env.LLM_API_KEY,
});

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
  ],
});

const SYSTEM = [
  "You are Captain Mirelle, a weary ship captain narrating short announcements for a fiction server.",
  "Write in first person, in plain spoken sentences that sound natural when read aloud.",
  "No lists, no markdown, no emoji, no web addresses. Maximum four sentences.",
].join(" ");

let inFlight = 0;

client.on(Events.MessageCreate, async (msg) => {
  if (msg.author.bot || !msg.content.startsWith("!say ")) return;
  const topic = msg.content.slice(5).trim().slice(0, 500);
  if (!topic) return;

  if (inFlight >= 6) {
    await msg.reply("Too many requests right now. Try again in a few seconds.");
    return;
  }

  inFlight++;
  try {
    await msg.channel.sendTyping();
    const res = await llm.chat.completions.create({
      model: "uncensored",
      messages: [
        { role: "system", content: SYSTEM },
        { role: "user", content: topic },
      ],
      max_tokens: 250,
      temperature: 0.8,
    });
    const text = (res.choices[0].message.content ?? "").trim().slice(0, 1900);
    if (text) await msg.channel.send({ content: text, tts: true });
  } catch (err) {
    console.error(err.status, err.message);
    await msg.reply(err.status === 429 ? "The model is busy. Try again shortly." : "Something went wrong.");
  } finally {
    inFlight--;
  }
});

client.login(process.env.DISCORD_TOKEN);

A few details in that file are deliberate. The 1,900-character slice keeps the message under Discord's 2,000-character limit. The in-flight counter stops the bot from sending more than six requests at once, which keeps it under the 8 concurrent requests a full key allows (the trial key allows 2, so lower the number to 2 while you test on trial credit). The catch block turns a 429 into a friendly reply instead of a crash.

Writing a system prompt that reads well out loud

Text that looks fine on screen can sound wrong when a synthetic voice reads it. The system prompt is where you fix that, and it is the part of this project that deserves the most iteration.

  • Ban formatting. Asterisks, bullet markers, headings and emoji are either read aloud or skipped awkwardly. Say "no markdown, no emoji" in the prompt.
  • Set a length. Say "maximum four sentences" in the prompt and also set max_tokens in code. The prompt shapes the style, and the cap protects you from a long answer.
  • Ask for spoken rhythm. Short sentences, commas where a speaker would breathe, numbers written the way you would say them.
  • Define the persona once. A name, a mood and a few habits of speech are enough. Long character sheets work too, since the window is 100,000 tokens, but you pay for them on every call.

The model is tuned to answer without content refusals for lawful adult use, which suits horror, dark fantasy, war stories and mature fiction on servers built for it. It does not allow anything sexual involving minors, and you should set your own channel rules and age gates according to Discord's terms and your community's expectations. Keep such channels marked appropriately and keep the bot out of spaces where its output is not welcome.

Adding memory so the bot remembers the scene

The example above treats each command on its own. For a roleplay channel you want the persona to remember what happened a minute ago. The chat completions endpoint is stateless, so you keep the history and send it each time.

const histories = new Map(); // channel id -> array of messages
const MAX_TURNS = 12;

function remember(channelId, role, content) {
  const h = histories.get(channelId) ?? [];
  h.push({ role, content });
  while (h.length > MAX_TURNS * 2) h.shift();
  histories.set(channelId, h);
}

// inside the handler, build the messages like this:
const messages = [
  { role: "system", content: SYSTEM },
  ...(histories.get(msg.channel.id) ?? []),
  { role: "user", content: topic },
];
// after a successful reply:
remember(msg.channel.id, "user", topic);
remember(msg.channel.id, "assistant", text);

Trimming to the last 12 exchanges keeps prompts small. At roughly 150 tokens per exchange, a full history adds about 3,600 tokens of input per call, which costs $0.00054 at $0.15 per 1M. A 250-token answer is another $0.000125. A busy command therefore stays well under a tenth of a cent, and you can see current rates on the pricing page.

Keeping the bot running

Once the commands behave, move the bot off your laptop. Any small server that runs Node continuously will do, with a process manager that restarts the bot if it exits. Keep the Discord token and the API key in environment variables, rotate them if they ever land in a log or a screenshot, and add a per-user cooldown of a few seconds so one member cannot use up your request budget in a minute. A cooldown also keeps you well below the 300 requests per minute that a full key allows.

That is the whole answer to how to set up tts bot discord for text-driven voices: a command, one model call, one message with the TTS flag. Everything after that is prompt work and moderation rules for your own community, and you can change either without touching the plumbing.

The history lives in the bot's memory, so it resets when the process restarts. If you want it to persist, write it to a small database keyed by channel.

Voice channels, limits and troubleshooting

If you want audio in a voice channel, the pattern stays the same, with one more stage. The bot gets the text from the LLM, sends it to a speech engine that you choose, and plays the resulting audio into the channel using a voice library for discord.js. Check that engine's pricing and terms separately. This API will not produce the audio itself.

ProblemWhat to check
Bot ignores the commandMessage Content intent is off, or the prefix does not match
Message appears but nobody hears itBot lacks the Send Text-to-Speech Messages permission, or members have TTS disabled in their client
Reply cut off mid-sentencemax_tokens set too low for the length you asked for
429 responsesMore than 8 requests at once (2 on trial), or over 300 per minute (60 on trial); the response may include Retry-After: 5
Text reads awkwardlyTighten the system prompt: no formatting, shorter sentences

Failed or refused requests are not charged, and prompts are not used for training. For the full list of parameters, including streaming, tool calling and JSON mode, see the API documentation. If you add slash commands later, the model call stays identical, because only the Discord side of the code changes.

Questions and answers

Can this API speak in a Discord voice channel by itself?

No. It is a text model and produces no audio. You can pair it with a speech engine of your choice, or use Discord's TTS message flag so members' clients read the text aloud.

Which permissions does the bot need?

View Channels, Send Messages and Send Text-to-Speech Messages, plus the Message Content intent enabled in the Developer Portal so it can read commands.

How much does a bot reply cost?

A 500-token prompt with a 250-token answer costs $0.000075 for input and $0.000125 for output, so $0.0002 in total at $0.15 and $0.50 per 1M tokens.

How many users can the bot serve at once?

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60, so queue or reject extra commands in your bot.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.