EN ▾
Get API key

How to Get a Discord Bot API Token and Add an LLM

Updated

There is no single Discord bot API key to buy. You create an application in the Developer Portal, copy its bot token, and invite the bot to a server. Here is how to get Discord bot API access in six steps, then connect it to an LLM.

Illustration of a glowing key above three linked layers representing an app, a bot and a language model

Step 1 to 3: create the application and copy the token

If you searched for how to get discord bot api credentials, the answer is the Developer Portal. Discord does not hand out a separate API key. Its API is open to anything that presents a valid bot token, and that token belongs to an application you create.

  1. Create the application. Sign in to Discord's Developer Portal in a browser, choose New Application, and give it a name. The name becomes the default bot name, though you can change it later.
  2. Add the bot and copy the token. Open the Bot tab. Use the Reset Token button to generate a token and copy it straight away. Discord shows it once. If you lose it you reset again, which also invalidates the old one.
  3. Decide on intents. On the same tab, privileged intents are switches. Message Content lets the bot read the text of ordinary messages. If you only use slash commands or answer when someone mentions the bot, you can leave it off, and you avoid extra approval steps if the bot ever grows large.

Save the token in an environment variable such as DISCORD_TOKEN or a secrets manager. Never commit it to a repository and never paste it into a chat. Anyone holding it can act as your bot. If it leaks, reset it in the portal and the leaked value stops working at once.

Step 4 to 6: invite the bot to your server

A token alone does not put the bot anywhere. You also need an invite link.

  1. Open OAuth2 and find the URL generator.
  2. Tick the scopes bot and applications.commands. The second one is what allows slash commands.
  3. Pick the smallest set of permissions that works. Send Messages and Read Message History cover most chat bots. Add Embed Links or Attach Files only if you use them.

Open the generated URL, pick a server where you have the Manage Server permission, and confirm. The bot appears in the member list as offline until your code logs in. Create a private test server first. It costs nothing, and you will break a few things on the way.

Get the LLM key

The Discord part gives you a bot that can send and receive messages. The brain is a separate service. This site offers an OpenAI-compatible text API with one model, uncensored, tuned to answer without content refusals for lawful adult use. It has one hard limit, no sexual content involving minors, and it generates text only.

Sign up with Google or with email and password, then open the key page. New users can claim $0.50 of trial credit with one click, one per person, valid for 7 days with no payment needed. When the trial runs out, top up any whole amount from $20 to $500 in crypto (USDT on TRC20 or USDC on Base). Pay-as-you-go prices are $0.15 per 1M input tokens and $0.50 per 1M output tokens, listed on the pricing page.

You now hold two secrets: the Discord bot token and the LLM key. Keep them in different variables, DISCORD_TOKEN and LLM_API_KEY. The base URL for the API is https://api.nsfwttsapi.com/v1.

A bot that answers when mentioned

This version replies when someone mentions the bot and keeps a short rolling history per channel. It needs the Message Content intent because it reads the message text, so switch that on in the Bot tab. Install with pip install discord.py openai.

import os
import discord
from collections import defaultdict, deque
from openai import AsyncOpenAI

llm = AsyncOpenAI(
    base_url="https://api.nsfwttsapi.com/v1",
    api_key=os.environ["LLM_API_KEY"],
)

SYSTEM = "You are a helpful, plain-spoken assistant in a Discord server. Keep replies short."

intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)

history = defaultdict(lambda: deque(maxlen=12))


@client.event
async def on_message(message: discord.Message):
    if message.author == client.user or client.user not in message.mentions:
        return
    text = message.clean_content.replace(f"@{client.user.name}", "").strip()
    log = history[message.channel.id]
    log.append({"role": "user", "content": text})
    async with message.channel.typing():
        resp = await llm.chat.completions.create(
            model="uncensored",
            messages=[{"role": "system", "content": SYSTEM}, *log],
            temperature=0.8,
            max_tokens=600,
        )
    reply = resp.choices[0].message.content or "No reply."
    log.append({"role": "assistant", "content": reply})
    await message.reply(reply[:1900])


client.run(os.environ["DISCORD_TOKEN"])

The deque caps history at 12 messages so cost per call stays flat. Without a cap, each reply resends the whole conversation, and long channels get slower and pricier. Discord limits a message to 2,000 characters, so the reply is cut at 1,900.

Streaming the reply into an edited message

Waiting ten seconds for a long answer feels broken. With stream: true the API sends tokens over server-sent events and you edit one message as text arrives. Edit about once a second or slower, because Discord rate limits message edits.

import time

async def stream_reply(message, messages):
    sent = await message.reply("...")
    stream = await llm.chat.completions.create(
        model="uncensored",
        messages=messages,
        stream=True,
    )
    buf, last = "", time.monotonic()
    async for chunk in stream:
        if not chunk.choices:
            continue
        buf += chunk.choices[0].delta.content or ""
        if buf and time.monotonic() - last > 1.2:
            await sent.edit(content=buf[:1900])
            last = time.monotonic()
    await sent.edit(content=buf[:1900] or "No reply.")
    return buf

One detail matters for limits: a streamed request holds its concurrency slot until the stream ends. A full key allows 8 concurrent requests, a trial key 2. If your server is busy and every reply streams for 20 seconds, the ninth simultaneous user gets HTTP 429 with the error code concurrency. Queue the requests or tell the user to retry. The usage figures arrive in the last chunk, so you can log tokens per reply.

Tool calling and JSON mode

Both work through the same endpoint, so a Discord bot can do more than chat. JSON mode is the simplest: pass response_format={"type": "json_object"} and describe the shape in the system prompt. It suits moderation labels, summaries and structured replies.

Tool calling lets the model ask your code to do something. You describe the function, the model answers with a tool call, you run it, and you send the result back with the role tool.

import json, random

tools = [{
    "type": "function",
    "function": {
        "name": "roll_dice",
        "description": "Roll one die with the given number of sides",
        "parameters": {
            "type": "object",
            "properties": {"sides": {"type": "integer"}},
            "required": ["sides"],
        },
    },
}]

msgs = [{"role": "user", "content": "Roll a d20 for my attack."}]
first = await llm.chat.completions.create(
    model="uncensored", messages=msgs, tools=tools, tool_choice="auto"
)
msg = first.choices[0].message
if msg.tool_calls:
    call = msg.tool_calls[0]
    sides = json.loads(call.function.arguments)["sides"]
    msgs.append(msg.model_dump(exclude_none=True))
    msgs.append({"role": "tool", "tool_call_id": call.id, "content": str(random.randint(1, sides))})
    final = await llm.chat.completions.create(model="uncensored", messages=msgs, tools=tools)
    print(final.choices[0].message.content)

Always parse the arguments with a try block and check ranges before you act on them. The model proposes the call; your code decides whether to run it.

Keeping secrets and hosting the bot

A bot has to stay online to answer, so your laptop is a poor home for it. Any small server, container host or home machine that can hold an outbound connection will do. The bot opens the connection to Discord; you do not need an open port or a public address.

Put both secrets in environment variables set on the host, or in a file that your process manager reads and git ignores. A .env file is fine as long as it is listed in .gitignore from the first commit. If a token ever lands in a public repository, assume it is compromised: reset it in the portal before you do anything else, then clean the history.

The LLM key deserves the same care, since anyone holding it spends your credit. Do not send it to the browser, and do not let users type their own prompts straight into a system that also holds admin tools. Keep an eye on the X-Balance-USD response header, and have the bot post a warning to an admin channel when the balance drops below a figure you choose. It is a cheap guard against a runaway loop.

Cost for a chat bot is small. A reply with 1,500 input tokens and 300 output tokens costs 1,500 x $0.15 / 1M + 300 x $0.50 / 1M = $0.000225 + $0.00015 = $0.000375, so 1,000 replies come to $0.375. Failed or refused requests are not charged.

The same thing in Node with discord.js

If you prefer JavaScript, the OpenAI Node package works with the same two settings. This listens for the /ask slash command, which you register separately, and defers before calling the model.

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

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

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

client.on(Events.InteractionCreate, async (interaction) => {
  if (interaction.isChatInputCommand() && interaction.commandName === "ask") {
    await interaction.deferReply();
    const resp = await llm.chat.completions.create({
      model: "uncensored",
      messages: [{ role: "user", content: interaction.options.getString("question") }],
      max_tokens: 500,
    });
    const text = resp.choices[0].message.content || "No reply.";
    await interaction.editReply(text.slice(0, 1900));
  }
});

client.login(process.env.DISCORD_TOKEN);

Common problems are easy to spot. A 401 from the LLM means the key is wrong or has a stray space. A bot that is online but silent usually lacks the Message Content intent or the permission to send messages in that channel. A slash command that does not appear needs applications.commands in the invite scope. More request details are in the API documentation.

Two more habits save time. Log the value of X-Request-Id from each response, so a bad reply can be traced when you ask for help. And test the LLM call from a plain script before you attach it to Discord: if the script works, any later failure is on the Discord side, and the search narrows by half.

Questions and answers

Is the Discord bot API free?

Creating an application and a bot token in the Developer Portal does not cost anything. Check Discord's current terms for limits that apply to large bots. The LLM side is billed separately from prepaid credit.

Where do I find my bot token again?

You cannot view it a second time. Reset the token on the Bot tab to generate a new one, and update every place that used the old value.

Do I need the Message Content intent?

Only if your bot reads ordinary message text. Slash commands and replies to mentions work without it, though a plain mention bot that quotes message text needs it.

Can I use the official OpenAI library?

Yes. Set the base URL to the one shown in this article, pass your key, and use the model name "uncensored". Nothing else changes.

Can the bot generate images or voice?

No. This API handles text only, so images and audio need other tools.

Your key is one form away

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