Discord AI Bot Tutorial: Python and an Uncensored API
This Discord AI bot tutorial builds a working chat bot in about 60 lines of Python. It uses discord.py for the Discord side and the OpenAI SDK pointed at an uncensored, OpenAI-compatible API for the replies.
Updated

What you need
- Python 3.9 or newer.
- A Discord application with a bot user, created in the Discord Developer Portal. Copy the bot token.
- An API key from the key page. The $0.50 trial is enough to finish this tutorial many times over.
- A server where you can invite your bot.
In the Developer Portal, open your bot's settings and switch on the Message Content Intent. Without it the bot receives empty messages. Invite the bot with the permissions to read and send messages in the channels you pick.
pip install discord.py openai
export DISCORD_TOKEN="your-bot-token"
export API_KEY="your-api-key"Create a virtual environment so the packages do not clash with other projects, and keep both secrets out of your code. If you plan to host the bot for friends, make a separate Discord application for it instead of reusing a personal one, so you can reset its token without breaking anything else.
The minimal bot
This version answers whenever someone mentions the bot. The API is OpenAI-compatible, so the only changes from a stock OpenAI setup are the base URL and the model name uncensored.
import os
import asyncio
import discord
from openai import AsyncOpenAI
ai = AsyncOpenAI(
base_url="https://api.abliteratedai.cc/v1",
api_key=os.environ["API_KEY"],
)
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Client(intents=intents)
SYSTEM = "You are Mira, a dry-witted tavern keeper in a fantasy story. Stay in character."
@bot.event
async def on_message(message):
if message.author == bot.user or bot.user not in message.mentions:
return
text = message.clean_content.replace("@" + bot.user.display_name, "").strip()
async with message.channel.typing():
resp = await ai.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": text},
],
max_tokens=400,
)
reply = resp.choices[0].message.content or "..."
await message.reply(reply[:2000])
bot.run(os.environ["DISCORD_TOKEN"])Run it, mention the bot in your server, and you should get an in-character answer in a few seconds. Discord caps messages at 2,000 characters, which is why the reply is cut with [:2000]. The next section handles long answers better.
Two details are easy to miss. First, message.clean_content turns mentions into readable names, which is why the code strips the bot's name from the text. Second, the or "..." guard covers the rare case where the model returns an empty string, because Discord rejects empty messages.
Add memory per channel
A bot with no memory answers each message as if it were the first. Store the last few turns per channel in a dictionary and send them with every request. The model itself keeps nothing between calls, so the history you send is the only memory it has.
from collections import defaultdict, deque
history = defaultdict(lambda: deque(maxlen=20))
gate = asyncio.Semaphore(6)
def chunks(s, n=1900):
return [s[i:i + n] for i in range(0, len(s), n)] or ["..."]
@bot.event
async def on_message(message):
if message.author == bot.user or bot.user not in message.mentions:
return
text = message.clean_content.replace("@" + bot.user.display_name, "").strip()
h = history[message.channel.id]
h.append({"role": "user", "content": f"{message.author.display_name}: {text}"})
async with gate, message.channel.typing():
resp = await ai.chat.completions.create(
model="uncensored",
messages=[{"role": "system", "content": SYSTEM}, *h],
max_tokens=500,
temperature=0.9,
)
reply = resp.choices[0].message.content or ""
h.append({"role": "assistant", "content": reply})
for part in chunks(reply):
await message.channel.send(part)The deque with maxlen=20 drops the oldest turns on its own, so the prompt cannot grow without limit. Prefixing each line with the speaker's display name lets the model tell apart several people in one channel.
Memory held in a dictionary disappears when the process restarts. For a hobby bot that is fine. If you want characters to remember a story across days, write the history to a small SQLite table keyed by channel ID and load the last 20 rows on start. Summarising older turns into one short paragraph, using the same API, keeps long stories coherent without sending 50,000 tokens on every reply.
Stay inside the rate limits
A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. The asyncio.Semaphore above caps in-flight calls so a busy channel queues instead of failing. Set it to 2 on a trial key and to 6 or 8 on a full one.
The OpenAI SDK retries some failures on its own, with short backoff. If you expect heavy traffic, add a per-user cooldown of a few seconds, which also protects your balance from one person spamming the bot. Read X-Balance-USD from the response headers if you want the bot to warn you when credit gets low.
Here is a simple per-user cooldown to add next to the semaphore.
last_used = {}
def too_soon(user_id, seconds=4):
now = asyncio.get_running_loop().time()
if now - last_used.get(user_id, 0) < seconds:
return True
last_used[user_id] = now
return FalseCall it at the top of on_message and return early when it says true. Four seconds is enough to stop button-mashing without making the bot feel sluggish. On a busy server you can raise it, or scale it by channel.
Personas and what to keep in mind
The model is tuned to answer without content refusals for lawful adult use, which suits fiction, roleplay and character bots. Put the character in the system prompt: name, voice, setting and a rule or two about format. Short, concrete prompts work better than long ones.
Some rules are not negotiable. Nothing sexual involving minors is allowed on this API. You are also responsible for how your bot behaves on Discord, so read Discord's terms and community guidelines, and keep adult-oriented bots to servers and channels where they are permitted. Consider an admin command that clears the channel history, and a clear note in your server that people are talking to an AI.
Try separating the persona from the rules. A good system prompt for a character bot often has three parts: who the character is, how it speaks (length, tone, whether it uses actions in asterisks), and what it should do when a user steers the story somewhere you do not want. Test it with a few awkward inputs before you invite other people. Low temperature gives steadier characters, and a higher value gives more surprising replies. The frequency_penalty and presence_penalty options are passed through if the bot repeats phrases.
Stream replies as they are written
Waiting several seconds for a long reply feels slow in chat. The API supports streaming over SSE, so you can send a placeholder message and edit it as text arrives. Discord limits how often you can edit a message, so update every second or so rather than on each chunk.
import time
async def stream_reply(message, msgs):
sent = await message.channel.send("...")
text, last = "", time.monotonic()
stream = await ai.chat.completions.create(
model="uncensored", messages=msgs, max_tokens=500, stream=True,
)
async for chunk in stream:
if not chunk.choices:
continue
text += chunk.choices[0].delta.content or ""
if time.monotonic() - last > 1.2:
await sent.edit(content=text[:2000] or "...")
last = time.monotonic()
await sent.edit(content=text[:2000] or "...")
return textThe final edit makes sure the last words appear. If a reply passes 2,000 characters, send the remainder as a new message with the chunks helper from earlier. Streaming does not change the price: you pay for the same tokens either way.
Run it all day and fix common problems
A bot is only useful if it stays online. A small VPS, a spare machine or a container host will do. Run the script under a process manager such as systemd or Docker with a restart policy, and read the token and key from environment variables, never from the source file. Do not commit them to a public repository.
- The bot is online but silent. Check the Message Content Intent and the channel permissions. Also confirm you mention the bot with a real mention, not plain text.
- Replies take long. You may be queuing on the semaphore, or on a trial key with its limit of 2 concurrent requests. Raise the limit after you top up.
- Authentication errors from the API. The key has a stray space or quote. Print its length at startup to confirm.
- The bot answers itself in a loop. Keep the check that ignores messages from the bot's own user, and ignore other bots too if you run several.
- Replies drift out of character. Shorten the history, restate the persona in the system prompt, and lower the temperature a little.
Costs and next steps
Rates are $0.15 per 1M input tokens and $0.50 per 1M output tokens. Assume a reply with 1,500 tokens of history and persona going in and 200 tokens coming out. Input costs $0.000225, output costs $0.0001, so each reply costs $0.000325. A thousand replies cost $0.325 and ten thousand cost $3.25. The $0.50 trial would cover about 1,538 replies. More on the pricing page.
From here you can add slash commands, streaming edits (set stream: true and update the message as chunks arrive), or tool calling for things like dice rolls. The API docs cover streaming and tools. If you are still choosing a provider, the page on the uncensored OpenRouter alternative explains how this single-model service differs from a router.
More guides
Questions and answers
Which library should I use for a Discord bot in Python?
discord.py is the most common choice and works well with async code, which fits the AsyncOpenAI client used in this tutorial.
Why does my bot see empty messages?
The Message Content Intent is off. Enable it in the Developer Portal and set intents.message_content to True in the code.
How do I handle Discord's 2,000-character limit?
Split the reply into chunks of about 1,900 characters and send them one by one, as the chunks function in this tutorial does.
How many users can the bot serve at once?
A full key allows 8 concurrent requests and 300 per minute. A semaphore in your code keeps extra messages waiting instead of failing.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.