How to Write a Discord Bot with an LLM Backend
This is how to write a Discord bot that answers with an LLM. You register the bot, run a short discord.py script, and point the OpenAI SDK at a different base URL.

Key points
- A working bot is about 60 lines of Python: discord.py for the gateway, the OpenAI SDK for the model.
- Change only the base URL, the key and the model ID; the rest is standard OpenAI client code.
- Discord caps messages at 2,000 characters, so split long replies and edit one message while streaming.
- Guard concurrency: a full key runs 8 requests at once, a trial key 2.
The short version
- Create an application in the Discord developer portal, add a bot user, copy its token and switch on the Message Content intent.
- Invite the bot to your server with the
botscope and permission to read and send messages. - Install the libraries:
pip install discord.py openai. - Write a script that listens for messages, calls
https://api.nsfwwriter.cc/v1with the modeluncensored, and posts the answer. - Run it on any machine that stays online.
That is the whole answer to how to write a discord bot with a language model behind it. The rest of this article fills in each step, then adds streaming, tools and JSON output. The LLM side is plain OpenAI-style chat, so if you have used the OpenAI SDK before, there is nothing new there. The quickstart lists the request fields that are supported.
Register the bot and get a key
In the Discord developer portal, create a new application, open the Bot tab and press the button to add a bot. Copy the token once and store it in an environment variable, never in your source code. Under Privileged Gateway Intents, enable Message Content, since your bot needs to read the text people send it.
To invite it, build an OAuth2 URL in the portal with the bot scope and the permissions View Channels, Send Messages and Read Message History. Open the URL, pick your server and confirm.
For the model side you need an API key. Sign up and open the key page; new users can claim $0.50 of trial credit with one click, valid for 7 days. Trial keys are limited to 2 concurrent requests and 60 requests per minute, which is plenty for testing in a private server.
Adult content on Discord has its own rules. Discord provides age-restricted channels, and its terms apply to your bot as much as to you. Read them before you point a bot with an unfiltered model at a public server, and keep all characters and users within the adult-only rule that applies here.
A minimal bot
This script replies when someone mentions the bot. It keeps a short history per channel so replies stay on topic.
import os
import discord
from openai import AsyncOpenAI
llm = AsyncOpenAI(
base_url="https://api.nsfwwriter.cc/v1",
api_key=os.environ["LLM_KEY"],
)
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Client(intents=intents)
SYSTEM = "You are a witty assistant in a Discord server. Keep replies under 1500 characters."
histories = {}
@bot.event
async def on_message(msg):
if msg.author.bot or bot.user not in msg.mentions:
return
text = msg.clean_content.replace(f"@{bot.user.display_name}", "").strip()
hist = histories.setdefault(msg.channel.id, [])
hist.append({"role": "user", "content": f"{msg.author.display_name}: {text}"})
del hist[:-20]
async with msg.channel.typing():
resp = await llm.chat.completions.create(
model="uncensored",
messages=[{"role": "system", "content": SYSTEM}] + hist,
temperature=0.8,
)
answer = resp.choices[0].message.content
hist.append({"role": "assistant", "content": answer})
await msg.reply(answer[:2000])
bot.run(os.environ["DISCORD_TOKEN"])
Run it from a terminal with LLM_KEY=... DISCORD_TOKEN=... python bot.py. Mention the bot in a channel and it answers. Three details are worth a second look. The history is trimmed to the last 20 entries, which keeps cost and latency down. Each user line carries the speaker's name so the model can tell people apart. The final slice to 2,000 characters is a blunt guard against Discord's message limit; the next section replaces it with something better.
Stream the reply into one message
Waiting for a full answer feels slow in chat. With stream: true the API sends tokens over SSE as they are produced, and you can edit a single Discord message as text arrives. Discord rate-limits edits, so update every second or so instead of per token.
import time
async def stream_reply(msg, messages):
sent = await msg.reply("...")
buf, last = "", time.monotonic()
stream = await llm.chat.completions.create(
model="uncensored", messages=messages, stream=True
)
async for chunk in stream:
if not chunk.choices:
continue
buf += chunk.choices[0].delta.content or ""
if time.monotonic() - last > 1.0 and len(buf) < 1900:
await sent.edit(content=buf)
last = time.monotonic()
chunks = [buf[i:i+1900] for i in range(0, len(buf), 1900)] or ["(empty)"]
await sent.edit(content=chunks[0])
for extra in chunks[1:]:
await msg.channel.send(extra)
return buf
The code stops live edits once the text nears 1,900 characters, then splits the final text into pieces under the limit. A streamed request occupies its concurrency slot until the stream ends, so a long answer holds a slot for its whole duration. That matters in the next section.
Handle limits and errors
A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. If ten people mention the bot at once, some calls will be refused with HTTP 429. The error code tells you which limit you hit: rate_limited for requests per minute, concurrency for too many at once. A temporary overload also returns 429 with a Retry-After: 5 header.
The cleanest fix is a semaphore sized to your key, plus one retry.
import asyncio
from openai import RateLimitError
slots = asyncio.Semaphore(6) # leave headroom under the limit of 8
async def ask(messages):
async with slots:
for attempt in range(3):
try:
r = await llm.chat.completions.create(
model="uncensored", messages=messages
)
return r.choices[0].message.content
except RateLimitError:
await asyncio.sleep(5)
return "I am busy right now, try again in a moment."
Failed or refused requests are not charged, so retries cost nothing extra when they fail. Responses carry X-Request-Id and X-Balance-USD headers; log the request ID so you can quote it if you ever contact support.
Tool calling and JSON mode
Once chat works, two features turn a chatty bot into a useful one. Tool calling lets the model ask your code to do something, such as roll dice or look up a score. You describe the tool, the model returns a tool_calls entry, you run it and send the result back as a role: "tool" message.
tools = [{
"type": "function",
"function": {
"name": "roll_dice",
"description": "Roll n dice with the given number of sides",
"parameters": {
"type": "object",
"properties": {
"n": {"type": "integer"},
"sides": {"type": "integer"},
},
"required": ["n", "sides"],
},
},
}]
resp = await llm.chat.completions.create(
model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
call = resp.choices[0].message.tool_calls
If call is set, parse call[0].function.arguments as JSON, run your function, append the assistant message and a tool message with the result, and call the API again for the final text.
JSON mode is the second feature. Setting response_format={"type": "json_object"} asks for valid JSON, which is handy for slash commands that must return a character sheet or a list. Say the word JSON in your prompt and describe the shape you want.
A cost note for bot owners: at $0.15 per 1M input and $0.50 per 1M output, a chat turn with 2,000 input tokens and 300 output tokens costs 2,000 x $0.15 / 1M + 300 x $0.50 / 1M = $0.0003 + $0.00015 = $0.00045. A thousand such replies come to $0.45. Details are on the pricing page.
Per-channel personas and slash-style commands
One bot can serve several channels with different behavior. Keep a dictionary that maps a channel ID to a system prompt, and fall back to a default. A channel for tabletop campaigns gets a game-master prompt, a channel for general chat gets a short friendly one, and a channel for story drafts gets a long-form prompt with a higher temperature. Because the model is told what it is in every request, there is no state to keep on the model side.
For commands, a simple prefix such as +reset that clears the stored history for a channel saves users from a conversation that has wandered off. Add +persona to swap the system prompt at runtime, and keep the list of allowed personas in code, not typed freely by users, so nobody can rewrite the bot's rules from chat.
Test the bot in a private channel first. A short checklist:
- Mention the bot twice in a row and confirm the second reply knows the first.
- Send a message of several thousand characters and confirm the bot still replies.
- Mention the bot from three accounts at once and confirm nothing crashes when 429 responses appear.
- Call
GET /v1/modelson the base URL once at start-up, so a wrong key fails loudly on boot, not on the first message.
Run it and keep it running
A bot is a long-running process, so use something that restarts it. On a Linux server that is a systemd unit; on a small container host it is the restart policy. Keep the two secrets in environment variables or a secrets store, and rotate the Discord token if it ever shows up in a log.
Before you open the bot to strangers, add a few guards of your own: a per-user cooldown, a cap on message length, and a channel allow-list. Prompts you send are not used for training, but your Discord server members may still not expect their messages to leave the server, so say in the channel description that the bot forwards messages to an LLM API.
More guides
Questions and answers
Do I need Python to write a Discord bot?
No. Any language with a Discord library works. The model side is plain HTTP, so the Node OpenAI SDK or curl calls to the same base URL work as well.
Why does my bot not see message text?
The Message Content intent is off. Turn it on in the developer portal under Privileged Gateway Intents and set it in your code.
Which model ID do I use?
Use uncensored in the model field. A GET request to /v1/models on the base URL lists what your key can use.
What happens when the bot gets too many messages?
The API answers with HTTP 429. Limit concurrency with a semaphore and retry after a short pause.
Is there a free tier?
New users can claim $0.50 of trial credit once, valid for 7 days. After that you top up prepaid credit from $20.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.
Read the docs