EN ▾
[uncensoredgpt.top]Get API key
uncensoredgpt.top(7)

Updated

Discord Chat GPT Bot With a Pay-Per-Token API

A slash command is the cleanest way to put a chat model in a Discord server. This walkthrough builds one in Node with discord.js and an OpenAI-compatible endpoint, then works out the monthly bill.

Key points

  • discord.js plus the openai package, with deferred replies so Discord never times out.
  • Per-user cooldown and an in-flight cap keep you under the rate limits.
  • 3,000 replies of typical size cost about $1.50 at $0.15 and $0.50 per 1M tokens.
  • A $20 top-up covers roughly 40,000 such replies, and credit does not expire.
Floating command bar sending a stream of chat bubbles across a grid, representing a Discord slash command bot

Why a slash command

Many tutorials for a discord chat gpt bot read every message in a channel and answer when mentioned. That works, but it needs the privileged message-content permission and makes the bot reply to things nobody asked it. A slash command such as /chat prompt:... avoids both problems. Discord sends your bot an interaction when someone runs the command, and you answer it.

There is one rule to design around: you must acknowledge an interaction within 3 seconds, and a language model rarely answers that fast. The fix is deferReply(), which shows a "thinking" state and gives you up to 15 minutes to send the real answer with editReply(). That is also where streaming fits, because you can keep editing the same reply while text arrives.

The model side uses https://api.uncensoredgpt.top/v1 with the model ID uncensored. It is tuned to answer without content refusals for lawful adult use, so it suits fiction, roleplay and companion-style bots for adult servers. Follow Discord's own rules on age-restricted channels, and note that sexual content involving minors is never produced.

Setup

  1. Create an application and bot in the Discord developer portal and copy the bot token and the application ID.
  2. Invite the bot to a test server with the applications.commands and bot scopes.
  3. Get an API key. A new account can claim $0.50 of trial credit in one click on the key page; no card is needed and it lasts 7 days.
  4. Create a Node project, set "type": "module" in package.json, and run npm install discord.js openai.
  5. Export DISCORD_TOKEN, APP_ID and LLM_API_KEY.

Register the command once. Global commands can take a while to show up everywhere, so while developing it is faster to register on a single server with Routes.applicationGuildCommands.

// register.js
import { REST, Routes, SlashCommandBuilder } from "discord.js";

const cmd = new SlashCommandBuilder()
  .setName("chat")
  .setDescription("Talk to the assistant")
  .addStringOption((o) =>
    o.setName("prompt").setDescription("What do you want to say?").setRequired(true)
  );

const rest = new REST().setToken(process.env.DISCORD_TOKEN);
await rest.put(Routes.applicationCommands(process.env.APP_ID), {
  body: [cmd.toJSON()],
});
console.log("registered");

The bot

The handler below defers, builds the message list from a short per-channel history, streams the answer, and edits the reply about once a second. It also enforces a cooldown per user and refuses new work when too many requests are already running.

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

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

const SYSTEM = "You are a sharp, friendly assistant in a Discord server. Stay under 1500 characters.";
const history = new Map();      // channelId -> [{role, content}]
const lastUse = new Map();      // userId -> timestamp
let active = 0;
const MAX_ACTIVE = 6;           // a full key allows 8 concurrent requests
const COOLDOWN_MS = 4000;

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

client.on(Events.InteractionCreate, async (i) => {
  if (i.isChatInputCommand() && i.commandName === "chat") await handle(i);
});

async function handle(i) {
  const now = Date.now();
  if (now - (lastUse.get(i.user.id) ?? 0) < COOLDOWN_MS) {
    return i.reply({ content: "Give it a few seconds between messages.", ephemeral: true });
  }
  if (active >= MAX_ACTIVE) {
    return i.reply({ content: "The bot is busy. Try again in a moment.", ephemeral: true });
  }
  lastUse.set(i.user.id, now);

  await i.deferReply();
  active++;
  try {
    const prompt = i.options.getString("prompt", true);
    const log = history.get(i.channelId) ?? [];
    log.push({ role: "user", content: `${i.user.displayName}: ${prompt}` });

    const stream = await ai.chat.completions.create({
      model: "uncensored",
      messages: [{ role: "system", content: SYSTEM }, ...log.slice(-10)],
      stream: true,
      max_tokens: 500,
      temperature: 0.8,
    });

    let text = "";
    let lastEdit = 0;
    for await (const part of stream) {
      text += part.choices[0]?.delta?.content ?? "";
      if (text && Date.now() - lastEdit > 1000) {
        await i.editReply(text.slice(0, 1990));
        lastEdit = Date.now();
      }
    }
    await i.editReply(text.slice(0, 1990) || "No answer came back.");

    log.push({ role: "assistant", content: text });
    history.set(i.channelId, log.slice(-20));
  } catch (err) {
    await i.editReply("Something went wrong. Please try again.");
    console.error(err);
  } finally {
    active--;
  }
}

client.login(process.env.DISCORD_TOKEN);

Run node register.js once and then node bot.js. Type /chat in your test server and watch the reply grow.

Rate limits and the 429 path

The in-flight counter and the cooldown are your first defence, but they are not a guarantee. A full key allows 8 concurrent requests and 300 requests per minute, and a trial key allows 2 and 60. When you exceed a limit the API returns HTTP 429. The error code rate_limited refers to requests per minute and concurrency to requests running at once. On temporary overload you also get a Retry-After: 5 header.

Streaming makes the concurrency limit easier to hit than it looks, because a streamed request holds its slot until the stream ends. A bot that streams 400-token answers into Discord, with edits throttled to one per second, holds each slot for several seconds. With 8 slots and answers taking about 10 seconds each, you can serve roughly one new reply per 1.25 seconds in the best case. That is fine for a community server and tight for a very large one.

If you do see a 429, the openai package for Node retries some failures by itself. Add a catch that checks err.status === 429, waits for the retry-after value, and tries once more before telling the user. For a trial key, set MAX_ACTIVE to 2.

Prompting and memory choices

The context window is 100,000 tokens for prompt plus completion, so memory is a question of cost, not of space. The bot above sends the last 10 entries. That is enough for a conversation to feel continuous without paying to resend a day of chat on every command.

Three practical tips. First, put the persona in the system message and keep it short; a long one is paid for on every call. Second, prefix user messages with the display name so the model can tell speakers apart. Third, if you want the bot to carry a fictional character, write the rules of the scene once and trust the model to hold them, then add a /reset command that clears the channel history when the story changes direction.

If you need structured results, for example a game master bot that returns dice results as JSON, use JSON mode through response_format. Tool calling is also supported if you want the model to call a function in your code. Both are covered in the docs.

Putting it into production

A development laptop is a fine host for the first week. After that, move the bot to a small server or container with a process manager such as systemd or pm2 so it comes back after a crash. Store the three secrets in the service's environment, keep them out of the repository, and rotate the Discord token if it ever appears in a log or a screenshot.

Log each failure together with the X-Request-Id header from the API, so that any odd reply can be traced later. Record the X-Balance-USD value now and then and send yourself a message when the balance falls under an amount you choose. A bot that silently runs out of credit looks broken to your members, while a warning a day early looks like good management.

Mind where replies appear. Ephemeral replies, visible only to the person who ran the command, are a good fit for cooldown and error messages. The model's answers usually belong in the channel so others can join in. For an adult server with age-restricted channels, restrict the command to those channels in the server's integration settings, and state the rules in the pinned message.

Ideas beyond plain chat

Once /chat works, the same pattern supports other commands. A /persona command that stores a system prompt per channel turns one bot into several characters. A /story command can keep a running summary that you update every few turns, so the live prompt stays short while the plot persists.

The long context window enables a /recap command: fetch the last few hundred messages of a channel (this needs the permission to read message history), join them into one block, and ask for a summary. Say the block is 30,000 tokens and the summary is 600 tokens. Input costs 30,000 × $0.15 / 1,000,000 = $0.0045, output costs 600 × $0.50 / 1,000,000 = $0.0003, and the recap costs $0.0048, under half a cent.

If you want the bot to do things as well as talk, tool calling lets the model request a function call, such as rolling dice or looking up a character sheet in your database, and you send the result back as a role: "tool" message. Combined with the free trial and a low per-reply cost, that makes the bot a cheap place to experiment.

What a month costs

Prices are $0.15 per 1M input tokens and $0.50 per 1M output tokens, billed from prepaid credit. Assume an average exchange sends 2,000 input tokens (system prompt plus history) and returns 400 output tokens.

  • Input: 2,000 × $0.15 / 1,000,000 = $0.0003
  • Output: 400 × $0.50 / 1,000,000 = $0.0002
  • Per reply: $0.0005

A server that produces 3,000 replies a month spends 3,000 × $0.0005 = $1.50. A busier one with 30,000 replies spends $15. The smallest top-up, $20, pays for 40,000 replies of this size ($20 / $0.0005), and because the credit never expires, a slow month does not waste anything. A failed or refused request is not charged. The pricing page lists the bonus tiers: +5% from $50, +10% from $100, +15% from $200. You can pay with with crypto (USDT on TRC20, USDC on Base).

Trimming history is the biggest lever. Halving the history in the example drops input from 2,000 to about 1,000 tokens and the reply cost from $0.0005 to $0.00035, a 30% saving.

Questions and answers

Why does my slash command say the application did not respond?

Discord needs an acknowledgement within 3 seconds. Call deferReply() first, then send the model's answer with editReply().

Do I need the message content intent?

Not for slash commands. The bot above only uses the Guilds intent. You need the message content intent only if you want it to read ordinary messages.

Can the bot stream answers?

Yes. The API streams over server-sent events, and you update the Discord reply with editReply about once per second.

What happens if many people use the bot at once?

A full key allows 8 concurrent requests and 300 per minute. Beyond that the API returns HTTP 429, so cap in-flight work and use a cooldown.

Your key is one form away

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

Get API key