EN ▾
Get API key

Discord Bot API Token: Connect It to an LLM API

A Discord bot needs two separate secrets to answer with a language model: the token Discord gives your bot, and the key your LLM provider gives you. This page shows where each one comes from and how to join them in under 50 lines of Python.

Two keys connecting a chat bubble bot to a language model, illustrating a Discord bot token and an LLM key

No card needed. After sign-up, claim $0.50 of free test credit with one click (once per person).

Get API key

Key points

  • The Discord token proves who your bot is; the LLM key pays for and authorizes the model calls. Never mix them up or share either.
  • Enable the Message Content intent in the Developer Portal or your bot will see empty messages.
  • Point the OpenAI SDK at the base URL, use model uncensored, and keep both secrets in environment variables.
  • Cap concurrent calls below 8 and split replies at Discord's 2,000 character limit.

Two secrets, two jobs

If you searched for a discord bot api token, you are probably at the first step of building a bot that chats. The token is only half of the setup. An AI bot talks to two different services, and each one hands you its own credential.

SecretIssued byWhat it doesWhere it goes
Discord bot tokenDiscord Developer PortalLogs your bot into Discord so it can read and send messagesbot.run(...)
LLM API keyYour model providerAuthorizes requests to the model and bills your balanceAuthorization: Bearer header, set by the SDK

People often paste the wrong one into the wrong place and then read the error as a bug in the library. A quick rule: the Discord token is a long string made of three parts separated by dots, and it only ever goes to Discord. The LLM key only ever goes to the model endpoint. They never appear in the same request.

Get the Discord bot token

You create the bot in Discord's Developer Portal. The labels move around from time to time, but the flow has been stable for years.

  1. Open the Developer Portal while signed in, choose to create a new application, and give it a name. That name is what members see.
  2. Open the Bot section of the application. Use the reset option to generate a token and copy it at once. Discord shows it a single time; if you lose it, you reset again and the old one stops working.
  3. On the same page, switch on the Message Content privileged intent. Without it, a bot in a normal server receives messages with empty text, which looks like the model is ignoring people.
  4. Go to the OAuth2 URL generator, tick the bot scope, and choose the permissions Send Messages and Read Message History. Open the generated link and add the bot to a server you manage.

The Message Content intent is a privileged intent. Small bots can enable it with one switch. If a bot grows large, Discord asks for verification and a review of why you need it, so read their current rules before you plan a public bot for many servers.

Get the LLM key and base URL

On the model side you need an OpenAI-compatible endpoint. This service exposes POST /v1/chat/completions and GET /v1/models at https://api.grokunfiltered.top/v1, the model ID is uncensored, and auth is a standard bearer header. Any OpenAI SDK works once you change the base URL and the key.

Sign up with Google or with email and password, then open the API key page. New accounts can claim $0.50 of trial credit with one click, valid for 7 days, one per person, no payment needed. That is plenty for testing a bot: at the prices below it covers hundreds of short replies. When you move to real traffic, top up from $20 in whole dollars through USDT on TRC20 or USDC on Base. The pricing page lists the bonus tiers: +5% from $50, +10% from $100, +15% from $200.

The model is one open-weight model run by an independent provider, tuned to answer without content refusals for lawful adult use. It is not the official API of any big vendor, and it is text only. The one hard limit is that nothing sexual involving minors is allowed. If your Discord server has a mixed audience, keep age-gated channels and set your own rules in the system prompt.

Keep both secrets out of your code

A bot token pasted into a public repository gets scraped within minutes, and a leaked LLM key lets strangers spend your balance. Use environment variables from the first line you write.

export DISCORD_TOKEN="paste-discord-token-here"
export LLM_API_KEY="paste-llm-key-here"
python bot.py

If you prefer a file, create .env, add it to .gitignore before your first commit, and load it with python-dotenv. On a server, set the variables in the service definition or in your host's secret settings. If either value ever lands in a chat, a log or a commit, treat it as burned: reset the Discord token in the portal and create a new LLM key.

A bot that answers when mentioned

Install the two libraries with pip install discord.py openai. The bot below replies only when someone mentions it, which keeps cost and noise down. It uses the async OpenAI client so a slow model call does not freeze the Discord connection.

import asyncio
import os

import discord
from openai import AsyncOpenAI

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

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

slots = asyncio.Semaphore(6)  # stay under the 8 concurrent limit

SYSTEM = "You are a witty assistant in a Discord server. Keep answers short."


def split_text(text, size=1900):
    return [text[i:i + size] for i in range(0, len(text), size)] or ["..."]


@bot.event
async def on_message(message):
    if message.author.bot or bot.user not in message.mentions:
        return
    question = message.clean_content.replace("@" + bot.user.display_name, "").strip()
    if not question:
        return
    async with slots, message.channel.typing():
        resp = await llm.chat.completions.create(
            model="uncensored",
            messages=[
                {"role": "system", "content": SYSTEM},
                {"role": "user", "content": question},
            ],
            max_tokens=600,
        )
    answer = resp.choices[0].message.content or ""
    for part in split_text(answer):
        await message.reply(part)


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

Three details matter. First, Discord limits a message to 2,000 characters, so the helper cuts long answers into pieces below that. Second, the semaphore keeps you under the concurrency cap of a full key, which is 8 requests at once (a trial key allows 2, so lower the number while testing). Third, max_tokens is optional on this API, but a cap protects you from an essay in a chat channel.

Streaming, tools and history

The first version waits for the full answer. For a nicer feel, send a placeholder message and edit it as chunks arrive with stream=True. Discord throttles edits, so update every second or so, not on every chunk. Remember that a streamed request holds its concurrency slot until the stream ends, which matters when several people ask at once.

Tool calling works with the standard tools and tool_choice fields, and results go back as messages with role: "tool". A bot can expose a dice roller, a server-rules lookup or a small database query this way. Keep the tool list short; every definition is sent with every call and counts as input tokens.

For memory, keep the last few turns per channel in a dictionary and send them with each request. The context window is 100,000 tokens, prompt plus completion, so you will rarely hit it, but long histories raise your cost on every message. Trimming to the last 10 or 20 turns is a sensible default.

What the bot costs

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit with no subscription. Take a typical exchange: a 1,200 token prompt (system text plus recent history) and a 300 token answer.

  • Input: 1,200 / 1,000,000 x $0.15 = $0.00018
  • Output: 300 / 1,000,000 x $0.50 = $0.00015
  • Total per reply: $0.00033

A server that triggers 2,000 replies a month spends about $0.66. Failed or refused requests are not charged, and credit never expires, so an idle month costs nothing. The X-Balance-USD response header shows your remaining balance; log it now and then and have the bot post a warning to an admin channel when it drops low.

Fixing common errors

  • LoginFailure: Improper token. The Discord token is wrong, has spaces around it, or was reset. Copy a fresh one.
  • Bot is online but silent. Message Content intent is off, or the bot lacks permission to read or send in that channel.
  • HTTP 401 from the LLM endpoint. You passed the Discord token as the LLM key, or the key has a typo. Check the variable names.
  • HTTP 429 with code concurrency. Too many requests at once. Lower the semaphore. Code rate_limited means the per-minute cap of 300 (60 on trial) was reached. A 429 with Retry-After: 5 is temporary overload; wait five seconds and retry.

The quickstart has a plain curl test you can run first, so you know the LLM half works before you debug the Discord half.

Questions and answers

Is the Discord bot token the same as an API key?

No. The bot token logs your bot into Discord. An LLM API key authorizes calls to a model endpoint. You need both, and each goes only to its own service.

What if my Discord bot token leaks?

Open the Bot page in the Developer Portal and reset the token. The old one stops working at once. Then update the environment variable on every machine that runs the bot.

Can I test the bot without paying?

Yes. Claim the $0.50 trial credit with one click on the API key page after sign-up. It lasts 7 days and has lower limits: 2 concurrent requests and 60 per minute.

Does the bot work with libraries other than discord.py?

Yes. The LLM side is plain HTTP with the OpenAI format, so any Discord library and any OpenAI-compatible client in JavaScript, Go or another language can use the same base URL and model ID.

Your key is one form away

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

Get API key