Discord Bot API Key: Connect an Uncensored LLM
A Discord bot that talks back needs two separate keys: a bot token from Discord and an API key from your language model provider. This guide wires both together in Python, with streaming, memory and tool calling.
Updated

On this page
- The two keys a Discord bot needs
- Get the model key and test it before writing a bot
- A minimal reply-on-mention bot in Python
- Stream replies by editing one message
- Personas, memory and roleplay settings
- Add tool calling for slash commands and game logic
- Rate limits, concurrency and what a bot costs
- Keep both keys safe and run the bot
- More guides
Key points
- Discord gives you a bot token; the LLM service gives you a separate API key. Never mix or share them.
- Point the OpenAI SDK at https://api.mimoapi.cc/v1 and use the model ID uncensored.
- Stream replies by editing one message every second or two, and cap concurrent calls at 8.
- A typical chat reply costs a fraction of a cent, so $20 of credit lasts a long time.
The two keys a Discord bot needs
When people search for a discord bot api key, they usually mean one of two things, and a working AI bot needs both. The first is the bot token. You create it in the Discord Developer Portal: add an application, open its Bot tab, and copy the token. That string lets your code log in as the bot. The second is the API key for the language model that writes the replies. It comes from the LLM provider, not from Discord.
Keep them apart in your head and in your code. The Discord token only talks to Discord. The model key only talks to the model API. If either one leaks, you rotate that one without touching the other. Store both as environment variables, never in the source file and never in a public repository.
This site provides the second key. It is a hosted, OpenAI-compatible text API running one open-weight model that is tuned to answer without content refusals for lawful adult use. It is run by an independent provider and is not the official API of any model vendor. Because it speaks the OpenAI protocol, any Discord bot library that can call an OpenAI-style endpoint works with it after you change two settings: the base URL and the key.
- Base URL:
https://api.mimoapi.cc/v1 - Model ID:
uncensored - Auth:
Authorization: Bearer <key>
Get the model key and test it before writing a bot
Create an account 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. It needs no card, lasts 7 days, and is limited to one per person. That is plenty to build and test a bot, because a short chat reply costs a small fraction of a cent (the math is further down).
Before you touch Discord code, check the key from a terminal. A bot that fails silently is hard to debug, and a bad key is the most common cause.
export LLM_API_KEY="paste-your-key-here"
curl https://api.mimoapi.cc/v1/chat/completions \
-H "Authorization: Bearer $LLM_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"messages": [{"role": "user", "content": "Say hello in one sentence."}],
"max_tokens": 50
}'
You should get a JSON body with a choices array. The response headers include X-Balance-USD, which is handy for a bot owner who wants to see the remaining credit. You can also list models with GET /v1/models; the ID to use in requests is uncensored. The quickstart docs cover the same request in Python and Node if you want a second reference.
A minimal reply-on-mention bot in Python
Install the two libraries: pip install discord.py openai. In the Developer Portal, enable the Message Content intent for your bot, otherwise Discord sends empty message bodies for ordinary messages. Then invite the bot to a server with the standard OAuth2 invite link.
The bot below answers only when it is mentioned. That keeps it from replying to every line in a busy channel, which also keeps your bill small. It stores a short history per channel so the model can follow the conversation.
import os
import discord
from openai import AsyncOpenAI
llm = AsyncOpenAI(
base_url="https://api.mimoapi.cc/v1",
api_key=os.environ["LLM_API_KEY"],
)
SYSTEM = "You are Marlow, a dry-witted narrator for a fantasy roleplay server. Stay in character and keep replies under 150 words."
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Client(intents=intents)
history = {} # channel id -> list of messages
@bot.event
async def on_message(message):
if message.author.bot or bot.user not in message.mentions:
return
turns = history.setdefault(message.channel.id, [])
turns.append({"role": "user", "content": f"{message.author.display_name}: {message.clean_content}"})
del turns[:-16] # keep the last 16 messages only
async with message.channel.typing():
resp = await llm.chat.completions.create(
model="uncensored",
messages=[{"role": "system", "content": SYSTEM}] + turns,
max_tokens=400,
temperature=0.8,
)
text = resp.choices[0].message.content or "..."
turns.append({"role": "assistant", "content": text})
await message.reply(text[:2000])
bot.run(os.environ["DISCORD_TOKEN"])
Two details matter here. Discord caps a message at 2,000 characters, so the code slices the reply; the max_tokens value of 400 keeps replies short enough to fit in most cases. And prefixing each user line with the display name lets the model tell several players apart in a shared channel.
Stream replies by editing one message
Long answers feel slow if the channel shows only a typing indicator for ten seconds. The API supports streaming over SSE with stream: true, and you can show text as it arrives. Discord has no true streaming for messages, so the usual trick is to send a placeholder and edit it on a timer. Edit too often and you hit Discord's own rate limits, so once every second or two is a sensible rhythm.
import time
async def stream_reply(message, turns):
sent = await message.reply("...")
stream = await llm.chat.completions.create(
model="uncensored",
messages=[{"role": "system", "content": SYSTEM}] + turns,
max_tokens=600,
stream=True,
)
buf, last = "", time.monotonic()
async for chunk in stream:
if not chunk.choices:
continue # the final usage chunk has no choices
buf += chunk.choices[0].delta.content or ""
if time.monotonic() - last > 1.5:
await sent.edit(content=buf[:2000] or "...")
last = time.monotonic()
await sent.edit(content=buf[:2000] or "(no reply)")
return buf
A streamed request holds its concurrency slot until the stream ends. For a bot this matters: if forty players all trigger a long streamed reply at once, only eight can run, and the rest will see a 429. The next section deals with that.
Personas, memory and roleplay settings
Most Discord roleplay bots live or die by the system prompt. Put the character, the setting and the output rules there, and keep it stable. A few habits help in practice:
- One persona per channel. Key your history dictionary by channel ID, and look up a different system prompt per channel from a small config table.
- Trim by tokens, not only by message count. The context window is 100,000 tokens, which is large, but you pay for every input token on every request. Sixteen messages is a cheap default; summarising older turns into one line is cheaper than carrying them forever.
- Tune sampling.
temperature,top_p,stop,seedand the penalties are passed through. A higher temperature suits narration; a lower one suits a rules-lawyer bot. A repetition-type penalty helps when a long scene starts to loop. - Use age-restricted channels. Discord lets you mark channels as age-restricted. If your server hosts mature fiction, keep that bot in such channels and make the rules clear. The service is for lawful adult use only, and sexual content involving minors is never allowed.
The model is tuned to answer without content refusals, which means it will follow the persona you write instead of breaking character with a lecture. That also puts moderation on you. Add a server rule list, a block word list if you want one, and a way for moderators to clear a channel's history.
Add tool calling for slash commands and game logic
Tool calling lets the model ask your code to do something exact, like rolling dice, looking up a character sheet or checking a score. You describe functions with tools, the model replies with tool_calls, you run them and send results back as role: "tool" messages. Language models are poor at fair random numbers, so a dice tool is a good first example.
import json, random
TOOLS = [{
"type": "function",
"function": {
"name": "roll_dice",
"description": "Roll dice and return the total.",
"parameters": {
"type": "object",
"properties": {
"count": {"type": "integer"},
"sides": {"type": "integer"},
},
"required": ["count", "sides"],
},
},
}]
async def answer_with_tools(turns):
msgs = [{"role": "system", "content": SYSTEM}] + turns
for _ in range(3): # allow a few tool rounds, then stop
resp = await llm.chat.completions.create(
model="uncensored", messages=msgs, tools=TOOLS, max_tokens=400
)
msg = resp.choices[0].message
if not msg.tool_calls:
return msg.content or "..."
msgs.append(msg)
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
rolls = [random.randint(1, args["sides"]) for _ in range(args["count"])]
msgs.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps({"rolls": rolls, "total": sum(rolls)}),
})
return "The dice rolled off the table."
Cap the loop, as above, so a confused model cannot call tools forever. Also validate the arguments: limit count and sides to sensible numbers before you use them, since the model's JSON is input like any other.
Rate limits, concurrency and what a bot costs
A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. When you go over, the API answers HTTP 429 with the error code rate_limited (too many per minute) or concurrency (too many at once). On temporary overload you also get a 429, with a Retry-After: 5 header. The simplest guard is an asyncio.Semaphore(8) around the model call, plus a retry that waits five seconds on a 429.
import asyncio
slots = asyncio.Semaphore(8)
async def limited_call(**kwargs):
for attempt in range(3):
async with slots:
try:
return await llm.chat.completions.create(model="uncensored", **kwargs)
except Exception as exc:
if getattr(exc, "status_code", None) == 429:
pass # fall through to the wait below
else:
raise
await asyncio.sleep(5)
raise RuntimeError("Model busy, try again later")
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, billed from prepaid credit. Take a reply that carries 1,500 input tokens of history and produces 300 output tokens. Input costs 1,500 x $0.15 / 1,000,000 = $0.000225. Output costs 300 x $0.50 / 1,000,000 = $0.00015. The total is $0.000375, so 1,000 replies cost $0.375. If you let history grow to 6,000 input tokens with 400 output tokens, one reply costs $0.0009 plus $0.0002, which is $0.0011, or $1.10 per 1,000 replies. Failed or refused requests are not charged. See the pricing page for top-up amounts and bonuses.
Keep both keys safe and run the bot
Put LLM_API_KEY and DISCORD_TOKEN in the environment of whatever runs the bot: a systemd unit, a Docker secret or your host's settings page. Do not paste either into a Discord channel, an issue tracker or a screenshot. If the Discord token leaks, regenerate it in the Developer Portal. If the model key leaks, stop using it and contact support to have it replaced.
Top-ups run from $20 to $500 in whole dollars, with a bonus of 5% from $50, 10% from $100 and 15% from $200. You can pay by crypto (USDT on TRC20, USDC on Base). Credit does not expire, so a hobby bot with irregular traffic does not waste money while idle. Prompts are not used for training.
If you would rather host a model yourself, our Ollama comparison lays out the trade-offs between a local setup and a hosted API. For a Discord community without a spare GPU, the hosted route is usually the shorter path to a working bot.
More guides
Questions and answers
Is a Discord bot token the same as an LLM API key?
No. The bot token comes from the Discord Developer Portal and lets your code log in as the bot. The LLM API key comes from the model provider and authorises requests to the model. You need both for an AI chat bot.
Which Discord library works with this API?
Any library works, because the model call is separate from the Discord connection. discord.py with the openai package is shown above, and the same base URL and the model ID uncensored work from Node, Go or any HTTP client.
How do I stop the bot from running up a bill?
Reply only to mentions, set max_tokens, trim history, and add a per-user cooldown. Prepaid credit also gives a hard ceiling, since the bot stops when the balance reaches zero.
Can the bot be used for adult roleplay?
The model is tuned to answer without content refusals for lawful adult use. Keep such bots in age-restricted channels, follow Discord's rules, and note that sexual content involving minors is never allowed.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.