EN ▾
Get API key

Discord LLM Bot: Connect an Uncensored API

To add llm to discord you need a small bot that reads a message, sends it to a chat completions endpoint and posts the answer back. This guide builds that bot in Node.js with discord.js, using an OpenAI-compatible text API with no content refusals for lawful adult use.

Updated

Glowing chat bubbles flowing from a small bot to an API server, illustrating a Discord bot connected to an LLM

Key points

  • A Discord bot is a Node.js process that forwards messages to the chat completions endpoint and replies.
  • Keep a short per-channel history, split replies at 2,000 characters and queue requests below your concurrency limit.
  • Slash commands need a deferred reply because the model can take longer than 3 seconds.
  • Credit is prepaid in crypto, and a busy small server costs a few dollars a month.

How the bot fits together

A language model never talks to Discord directly. Your bot sits in the middle. Discord delivers a message event to your code, your code builds a list of chat messages, sends it to the API and sends the text it gets back to the channel. That is the whole architecture, and it fits in about 70 lines.

The API on this site is a hosted, OpenAI-compatible endpoint for one open-weight model, run by an independent provider and tuned to answer without refusals for lawful adult use. The model ID is uncensored and the base URL is https://api.unfilteredaiimage.com/v1. Since it speaks the OpenAI chat format, the official openai package works as the client. Only text is supported. If you arrived hoping for pictures, the note on creative pipelines explains how a text-only API can still fit into them.

Write the persona and rules of your bot yourself, in the system message. For servers that host fiction, roleplay or companion-style characters for adults, state your own house rules there too. Sexual content involving minors is never allowed, and you should also mark any adult channel as age-restricted in Discord so that the server follows the platform's own rules.

Prepare the Discord side

Create an application in the Discord Developer Portal, add a bot user and copy its token. Then open the bot settings and switch on the Message Content intent. It is a privileged intent, and without it the bot receives messages with empty text, which is the most common reason a new bot appears to ignore everyone. Under the OAuth2 URL generator, select the bot scope with the permissions to view channels, send messages and read message history, then open the generated link to invite the bot to your server.

Keep the token private. Anyone who has it controls your bot. Do not paste it into code that you commit, and reset it in the portal if it ever leaks.

Next, get an API key from the key page. New accounts can claim $0.50 of trial credit with one click, valid for 7 days and free to claim. The trial key allows 2 concurrent requests and 60 per minute, which is fine for testing in a private server.

Project setup

You need a current Node release. Create the project and install the two packages:

mkdir discord-llm-bot && cd discord-llm-bot
npm init -y
npm pkg set type=module
npm install discord.js openai

Put both secrets in environment variables. A hosting panel, a systemd unit or a .env loader all work. For a quick local run:

export DISCORD_TOKEN="your-bot-token"
export LLM_API_KEY="your-api-key"
node bot.js

The commands assume the code below is saved as bot.js.

The bot: replies when mentioned

This version answers only when someone mentions the bot, which keeps costs low and avoids talking over human conversation. It stores the last 12 exchanges per channel and trims older ones, so the prompt does not grow without limit.

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

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

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

const PERSONA =
  "You are Ember, a sharp-tongued storyteller in a Discord server for adult fiction writers. " +
  "Keep replies under 250 words unless asked for more. Never write sexual content involving minors.";

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

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

function splitForDiscord(text, size = 1900) {
  const parts = [];
  for (let i = 0; i < text.length; i += size) parts.push(text.slice(i, i + size));
  return parts;
}

bot.on(Events.MessageCreate, async (message) => {
  if (message.author.bot) return;
  if (message.mentions.has(bot.user) === false) return;

  const text = message.content.replace(/<@[^>]+>/g, "").trim();
  if (text === "") return;

  remember(message.channelId, "user", message.author.username + ": " + text);
  await message.channel.sendTyping();

  try {
    const reply = await ai.chat.completions.create({
      model: "uncensored",
      messages: [
        { role: "system", content: PERSONA },
        ...histories.get(message.channelId),
      ],
      temperature: 0.9,
      max_tokens: 600,
    });
    const answer = reply.choices[0].message.content ?? "";
    remember(message.channelId, "assistant", answer);
    for (const part of splitForDiscord(answer)) await message.reply(part);
  } catch (err) {
    console.error(err.status, err.code, err.message);
    await message.reply("The model is busy right now. Try again in a few seconds.");
  }
});

bot.login(process.env.DISCORD_TOKEN);

A few choices in that code are worth explaining. The username is prefixed to each user message so the model can tell people apart in a shared channel. The history lives in memory, so a restart clears it; move it to a database if you want it to persist. The max_tokens value is optional, since the completion may use whatever is left of the 100,000-token window, but a cap keeps replies sized for chat. Discord rejects messages above 2,000 characters, so the helper cuts the answer into chunks of 1,900.

The catch block matters in a live server. A 429 response means you went over a limit or the service was briefly overloaded, and in the second case it includes a Retry-After: 5 header. The openai package already retries that kind of response a couple of times before it throws, so by the time your handler runs, the situation has lasted a while.

Slash commands and the 3-second rule

Mentions are easy, but slash commands are cleaner for a public server because users see the options in Discord's own menu. The catch is timing: Discord expects the first response to an interaction within 3 seconds, and a model can take longer. Call deferReply() first, then edit the reply when the text is ready.

import { SlashCommandBuilder } from "discord.js";

export const askCommand = new SlashCommandBuilder()
  .setName("ask")
  .setDescription("Ask the storyteller something")
  .addStringOption((o) => o.setName("prompt").setDescription("Your message").setRequired(true));

bot.on(Events.InteractionCreate, async (interaction) => {
  if (interaction.isChatInputCommand() === false) return;
  if ((interaction.commandName === "ask") === false) return;

  await interaction.deferReply(); // Discord wants a first answer within 3 seconds

  const prompt = interaction.options.getString("prompt");
  const reply = await ai.chat.completions.create({
    model: "uncensored",
    messages: [
      { role: "system", content: PERSONA },
      { role: "user", content: prompt },
    ],
    max_tokens: 500,
  });
  await interaction.editReply((reply.choices[0].message.content ?? "").slice(0, 1900));
});

You still have to register the command once with Discord, using the REST route in the discord.js guide, before it appears in the server. A slash command has no memory by default, so each call is a fresh conversation unless you add the same history map as above.

Rate limits and a simple queue

A single user will never hit the limits. A server with a busy channel can. A full key allows 8 concurrent requests and 300 requests per minute, and the API answers with HTTP 429 and the code rate_limited or concurrency when you pass either. Streaming holds a slot until the stream ends, so if you later switch to streamed edits of a Discord message, count those too.

The simplest protection is a small gate that lets at most six calls run at once and makes the rest wait their turn:

const MAX_PARALLEL = 6; // a full key allows 8 at once, leave some room
let active = 0;
const waiting = [];

async function withSlot(task) {
  if (active >= MAX_PARALLEL) {
    await new Promise((resolve) => waiting.push(resolve));
  } else {
    active += 1;
  }
  try {
    return await task();
  } finally {
    const next = waiting.shift();
    if (next) next();
    else active -= 1;
  }
}

// usage inside the handler:
// const reply = await withSlot(() => ai.chat.completions.create({ ... }));

Wrap the call in the handler with withSlot. Users then see a slightly longer typing indicator at peak time instead of an error. If you share one key between several bots, lower the number accordingly. Keep a per-user cooldown of a few seconds as well, because a single person pasting commands in a loop is the usual way a server burns through credit.

What it costs to run

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit. Picture a small community where the bot answers 500 times a day. Each call sends about 1,200 tokens of persona and history and gets back about 250 tokens.

Input per call: 1,200 × $0.15 / 1,000,000 = $0.00018. Output per call: 250 × $0.50 / 1,000,000 = $0.000125. Together that is $0.000305 per call. Multiply by 500 calls and you get $0.1525 a day, or about $4.58 over 30 days. A $20 top-up, which is the minimum, would last more than four months at that rate.

You pay with crypto: USDT on TRC20 or USDC on Base, in any whole amount from $20 to $500. Larger top-ups carry a bonus of +5% from $50, +10% from $100 and +15% from $200. Failed or refused requests are not charged, and credit never expires. The pricing page shows the current terms, and the API docs list the parameters you can pass, including temperature, top_p, stop, seed and the penalties. Prompts are not used for training, which is worth saying in your server rules, since your members are writing into it.

Questions and answers

Why does my bot reply with empty text or nothing at all?

Usually the Message Content intent is off. Enable it in the Developer Portal under the bot settings and also request it in your code with GatewayIntentBits.MessageContent.

Can the bot send long answers?

Yes, but Discord caps a message at 2,000 characters. Split the answer into chunks of about 1,900 characters and send each one as its own message.

Can I run it for free to test it?

New users can claim $0.50 of trial credit with one click on the key page. It costs nothing to claim, lasts 7 days and is limited to one per person.

Does the bot generate images?

No. The API is text only. It does not produce images, audio or video, and it offers no embeddings.

What happens if many people use the bot at once?

The API returns HTTP 429 when you pass the request or concurrency limit. A small queue in your bot keeps parallel calls under the limit, so users wait a little instead of seeing errors.

Your key is one form away

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

Get API key