What you need before you write code
The setup is short. You need a Discord account that can create applications, Python 3.9 or newer, and an API key for the text model. Everything else is a pip install away.
- A bot application in the Discord developer portal, with its token.
discord.pyfor the gateway connection andopenaifor the model calls.- An API key. New users can claim a trial credit with one click on the API key page, so you can test the bot before you add money.
- A server where you have permission to add bots.
The model side is plain OpenAI-style chat completions. The base URL is https://api.wannsfw.top/v1 and the model name is uncensored. If you have used the OpenAI SDK before, nothing about the call shape is new. The quickstart in the docs shows the same call in curl and Node.
Create the bot account and turn on message content
Open the Discord developer portal, create an application, and add a bot to it. Copy the token and store it in an environment variable, never in the source file. Then scroll to the privileged gateway intents and switch on Message Content Intent. Without it, your bot receives events but the text of each message arrives empty, which is the most common reason a new bot appears to ignore people.
Next, generate an invite link with the bot scope and permissions to view channels, send messages and read message history. Open the link, pick your server, and the bot joins as an offline member. It comes online when your script starts.
Decide early how the bot is triggered. Replying to every message in a busy channel gets expensive and annoying. A mention (@YourBot hello) or a dedicated channel are the two patterns that work well. The code below uses mentions, with an optional dedicated channel check you can add in one line.
The bot, start to finish
Install the packages and set two environment variables, DISCORD_TOKEN and API_KEY.
pip install discord.py openai
export DISCORD_TOKEN="your-discord-bot-token"
export API_KEY="your-api-key"
Then save this as bot.py. It listens for mentions, builds a message list from recent history, asks the model for a reply, and sends it back in chunks that fit Discord's 2,000 character limit.
import asyncio
import os
from collections import defaultdict, deque
import discord
from openai import AsyncOpenAI
ai = AsyncOpenAI(
base_url="https://api.wannsfw.top/v1",
api_key=os.environ["API_KEY"],
)
SYSTEM = (
"You are a friendly chat companion in a Discord server for adults. "
"Keep replies under 150 words unless asked for more. "
"Stay in character and never claim to be a human."
)
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Client(intents=intents)
# last 12 turns per channel
history = defaultdict(lambda: deque(maxlen=12))
slots = asyncio.Semaphore(6) # stay below the limit of 8 concurrent requests
@bot.event
async def on_message(msg: discord.Message):
if msg.author.bot or bot.user not in msg.mentions:
return
text = msg.clean_content.replace(f"@{bot.user.display_name}", "").strip()
if not text:
return
log = history[msg.channel.id]
log.append({"role": "user", "content": f"{msg.author.display_name}: {text}"})
async with msg.channel.typing():
async with slots:
resp = await ai.chat.completions.create(
model="uncensored",
messages=[{"role": "system", "content": SYSTEM}, *log],
max_tokens=400,
temperature=0.8,
)
reply = resp.choices[0].message.content or "..."
log.append({"role": "assistant", "content": reply})
for i in range(0, len(reply), 1900):
await msg.reply(reply[i : i + 1900], mention_author=False)
bot.run(os.environ["DISCORD_TOKEN"])
Run python bot.py, mention the bot in any channel it can see, and it answers. That is the whole core. The rest of this article is about making it behave under real traffic.
Give the bot a memory that stays small
The API is stateless. Each request must carry whatever context you want the model to see. The deque(maxlen=12) above keeps the last twelve turns of a channel and drops older ones automatically. That is enough for a conversation to feel continuous without paying to resend the whole day.
Prefixing each user line with the display name matters in a shared channel. Without it the model cannot tell three people apart and starts answering as if they were one person. Keep the system prompt short and put the persona there, not in every message.
When to store more
The context window is 100,000 tokens, so there is plenty of room if you want long threads or a persistent character sheet. The limit you will hit first is cost, not space. If you want the bot to remember something for weeks, write a short summary to a file or database and place it at the top of the system prompt, instead of replaying old messages.
Per-user versus per-channel history
Keyed by channel, the bot behaves like a participant in the room. Keyed by user ID, it behaves like a private assistant that happens to answer in public. Pick one on purpose. For roleplay servers, per-channel usually feels right, because everyone shares the same scene.
Slow replies, streaming and the 2,000 character wall
A reply of 150 words takes a few seconds, which is why the code shows the typing indicator while it waits. You can also stream the answer with stream=True and edit one Discord message as chunks arrive. If you do, edit at most once per second or so. Discord rate limits message edits per channel, and an edit on every token will get your bot throttled long before the API complains.
A simpler option is to skip streaming for chat and only stream for long outputs such as story scenes. For short chat, the typing indicator plus one finished message reads naturally.
The 1,900 character split in the loop is a safety margin under Discord's message limit. If you prefer, split on paragraph breaks instead of a fixed offset so a sentence is not cut mid-word. Setting max_tokens to 400 also keeps most replies inside one message, and it protects your budget from a runaway generation.
Limits, retries and the busy-server problem
A full key allows 8 requests at the same time and 300 per minute. A trial key allows 2 at a time and 60 per minute. The asyncio.Semaphore(6) in the code keeps a burst of mentions from crossing the concurrency line. Requests beyond six simply wait their turn, and users see the typing indicator for a little longer.
If you do cross a limit, the API answers with HTTP 429. The error code is rate_limited for requests per minute and concurrency for too many at once. On a temporary overload it also returns 429 with Retry-After: 5. The OpenAI SDK retries a few times by default, and you can raise max_retries when you build the client. For a chat bot, a short wait is better than an error message in the channel.
from openai import AsyncOpenAI
ai = AsyncOpenAI(
base_url="https://api.wannsfw.top/v1",
api_key=os.environ["API_KEY"],
max_retries=4,
timeout=60,
)
One more detail: a streamed request holds its concurrency slot until the stream finishes, so a slow reader on a long stream counts against your 8 for the whole time. Failed or refused requests are not charged, which keeps retries cheap.
What the bot will cost to run
Pricing is $0.15 per million input tokens and $0.50 per million output tokens, billed from prepaid credit. Take a typical chat turn: a system prompt plus twelve turns of history is around 1,500 input tokens, and the reply is about 200 tokens.
- Input: 1,500 tokens x $0.15 / 1,000,000 = $0.000225
- Output: 200 tokens x $0.50 / 1,000,000 = $0.0001
- One reply: $0.000325
- 1,000 replies: $0.325
- 10,000 replies: $3.25
So a community that triggers the bot 10,000 times in a month spends a little over three dollars on model calls. The smallest top-up is $20, and credit never expires, so it will last a long time on a hobby server. Larger top-ups include a bonus of 5% from $50, 10% from $100 and 15% from $200. Payment is in USDT on TRC20 or USDC on Base, and the pricing page has the details.
If costs creep up, the first lever is history length. Cutting from twelve turns to six roughly halves the input side.
Server rules, adult content and safe defaults
The model is tuned to answer without content refusals for lawful adult use, which suits fiction, roleplay and companion-style bots. That freedom needs boundaries on your side. Discord has its own rules for what may appear in which channels, and server owners are responsible for following them. Check the current Discord policies, and keep adult-oriented bots in channels set up for that purpose.
One limit is fixed: no sexual content involving minors, in any form. Build your bot so it refuses that, and add the line to your system prompt as well as your server rules. Consider a command that lets moderators wipe a channel's history and a role check so only verified adults can use the bot in age-gated channels. The terms page lists what the service itself prohibits.
Prompts sent through the API are not used for training, but your own Discord logs are a separate matter. If you store history on disk, tell your members and keep it short-lived.
