EN ▾
Get API key

GetAiApiKeyArtificial Intelligence API Checklist for Production

LLM API Key for a Discord Bot: Setup Guide

A Discord bot needs three things from an LLM provider: an OpenAI-compatible endpoint, a key, and limits that fit a busy server. Here is a working bot, the settings behind it, and the cost per message.

Updated

Isometric illustration of chat bubbles linked to a server rack, representing a Discord bot calling an LLM API

Key points

  1. Use the openai package with base URL https://api.getaiapikey.com/v1 and model uncensored.
  2. Keep a short rolling history per channel; the window is 100,000 tokens but cost grows with every resent turn.
  3. Cap in-flight calls at 6 or so, since a full key allows 8 concurrent requests and 300 per minute.
  4. A chat reply of 1,500 input and 200 output tokens costs $0.000325.

What an LLM API key does for a Discord bot

If you want an llm api key discord bot, the moving parts are simple. Discord delivers a message to your code through its bot gateway. Your code sends the recent conversation to an LLM endpoint, receives text, and posts it back to the channel. The API key is what proves to the LLM provider that the request is yours and bills it to your balance.

This service is OpenAI-compatible, so the bot uses the standard openai Python package. You change two settings, the base URL and the model ID uncensored, and everything else is normal chat completions. New users can try it first: after sign-up the API key page offers $0.50 of trial credit, valid for 7 days, no card needed.

One honest boundary up front. This is a text model. It cannot generate images, voice or video, and it does not read attachments by itself. Your bot can forward text from a message, but anything beyond text is outside what this API does.

Before you write code

  1. Get an API key. Sign up with Google or email, create a key on the key page, and keep it in an environment variable.
  2. Create a Discord application. In Discord's developer portal, add a bot, copy its token, and enable the Message Content intent so the bot can read message text. Invite it to your server with the permissions to read and send messages.
  3. Install the libraries. You need discord.py and openai.
python3 -m venv .venv
source .venv/bin/activate
pip install discord.py openai
export API_KEY="your-llm-key"
export DISCORD_TOKEN="your-discord-bot-token"

Never commit either secret. If a token leaks, reset it in the respective dashboard. For the LLM side, the quickstart docs show the same call in curl and Node if you prefer another language.

A working bot in about 50 lines

This bot answers when someone mentions it. It keeps the last 20 messages per channel, calls the model with a persona prompt, and splits long answers to fit Discord's 2,000-character message limit.

import os
import asyncio
from collections import defaultdict, deque

import discord
from openai import AsyncOpenAI, RateLimitError

ai = AsyncOpenAI(
    base_url="https://api.getaiapikey.com/v1",
    api_key=os.environ["API_KEY"],
)

SYSTEM = (
    "You are Mara, the resident storyteller of a community server for adult "
    "fiction writers. Keep replies under 150 words unless asked for more. "
    "Stay in character, write in plain prose, and ask one question at the end."
)

history = defaultdict(lambda: deque(maxlen=20))
gate = asyncio.Semaphore(6)

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


@bot.event
async def on_message(message):
    if message.author.bot or bot.user not in message.mentions:
        return

    text = message.clean_content.replace("@" + bot.user.display_name, "").strip()
    if not text:
        return

    log = history[message.channel.id]
    log.append({"role": "user", "content": message.author.display_name + ": " + text})

    async with gate:
        async with message.channel.typing():
            try:
                resp = await ai.chat.completions.create(
                    model="uncensored",
                    messages=[{"role": "system", "content": SYSTEM}, *log],
                    temperature=0.8,
                    max_tokens=500,
                )
            except RateLimitError:
                await message.reply("I am busy right now. Try again in a few seconds.")
                return

    reply = resp.choices[0].message.content or ""
    log.append({"role": "assistant", "content": reply})

    for i in range(0, len(reply), 1900):
        await message.reply(reply[i:i + 1900])


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

Run it with python bot.py, mention the bot in a channel, and you should see a reply. The typing indicator shows while the request is in flight, which makes the wait feel shorter.

Write a system prompt that holds a persona

The system prompt does most of the work in a chat bot. A good one is short and specific: who the bot is, how long its replies are, and what it should do when the conversation drifts. Compare two versions.

A weak prompt says "be a helpful assistant". A stronger one gives a role, a length limit and a habit: "You are Mara, a storyteller. Reply in under 150 words. End with one question that moves the scene forward." The second gives the model something to hold on to across a dozen turns, and the length limit also keeps your cost predictable.

Some practical points from running chat bots:

  • Prefix each user turn with the speaker's name, as the code does. In a shared channel the model otherwise cannot tell people apart.
  • Put rules for your server in the system prompt, such as topics to avoid or a house style. The model is tuned to answer without content refusals for lawful adult use, so limits you want must come from your prompt and your moderation, not from the model.
  • Keep the persona steady. If you change it often, old turns in the history will contradict the new instructions.

Context, history and the 100,000-token window

The context window is 100,000 tokens, prompt plus completion. A 20-message rolling history is nowhere near that, and that is deliberate. The API is stateless: every request must carry the whole conversation you want the model to see, so each extra turn you keep is paid for again on every following call.

Pick a history length by how much memory the bot needs. A casual chat bot works with 10 to 20 messages. A long-running roleplay may need more, and for that a common approach is to summarise old turns into a short note kept near the top of the prompt, then drop the originals. Use a second model call to write the summary when history passes a size you choose.

Per-channel history, as in the code, keeps conversations separate. If you also want per-user memory across channels, store notes in a database and add them to the system prompt for that user. That part is your application's job, since the API itself keeps nothing between calls. For privacy, note that prompts sent to this API are not used for training; see the privacy page for the details.

Rate limits on a busy server

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. A quiet server never notices, but a popular channel can send a burst of mentions at once.

The asyncio.Semaphore(6) in the code limits the bot to 6 calls in flight, so it never reaches the cap of 8 and leaves room for a second script using the same key. On a trial key, set it to 2. If you do exceed a limit, the API returns HTTP 429: rate_limited for requests per minute, concurrency for too many at once. Temporary overload also gives 429 with Retry-After: 5. The OpenAI client retries some of these by default, and the code above replies with a polite message if retries run out.

Streaming deserves a note. If you edit the Discord message as tokens arrive, the request holds its concurrency slot until the stream ends, and Discord limits how fast you may edit messages. For most bots a single reply after the full answer is simpler and reliable.

What a Discord bot costs to run

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit. Work out one reply first. Say the system prompt plus 20 messages of history come to 1,500 input tokens, and the answer is 200 tokens.

  • Input: 1,500 / 1,000,000 x $0.15 = $0.000225
  • Output: 200 / 1,000,000 x $0.50 = $0.0001
  • Total: $0.000325 per reply, so 1,000 replies cost $0.325

Now a heavier case with 3,000 input and 300 output tokens: $0.00045 + $0.00015 = $0.0006 per reply, or $0.60 per 1,000 replies. A server that gets 500 replies a day at that size spends about $0.30 a day, roughly $9 over 30 days.

The smallest top-up is $20 (any whole amount up to $500), with a bonus of 5% from $50, 10% from $100 and 15% from $200. Credit never expires, and failed or refused requests are not charged. Pay by card (Visa, Mastercard, Apple Pay, Google Pay) or crypto (USDT on TRC20, USDC on Base). More on the pricing page.

Rules and safety for adult communities

The model serves lawful adult use, and the hard limit is that sexual content involving minors is never allowed. If your server hosts fiction or roleplay for adults, keep it to adults: gate channels in Discord's own settings, state your rules in the channel topic, and moderate. Read Discord's current developer and community policies before you launch, since they apply to your bot regardless of what the model will write.

Log request IDs. Every API response includes X-Request-Id, which helps when you contact support about a specific call. The X-Balance-USD header lets the bot warn you in an admin channel when credit runs low, so it never goes quiet without notice.

Questions and answers

Which library do I use to call the API from a Discord bot?

Use the openai Python package with AsyncOpenAI, set base_url to https://api.getaiapikey.com/v1, and use the model uncensored. Any OpenAI-compatible client works the same way.

Can I test the bot without paying?

Yes. New users can claim $0.50 of trial credit with one click on the API key page. It lasts 7 days, needs no card, and the trial key allows 2 concurrent requests and 60 per minute.

How many messages can the bot remember?

The window is 100,000 tokens, but you choose how much history to resend. Most bots keep 10 to 20 messages per channel to control cost.

Can the bot read images or reply with voice?

No. This API handles text only, with no image, audio or video generation and no embeddings.

What happens if many people mention the bot at once?

Extra requests above 8 concurrent or 300 per minute get HTTP 429. Use a semaphore or queue in the bot so it stays under those limits.

Your key is one form away

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