Discord Bot Integration with an OpenAI-Compatible API
An ai chat bot discord integration needs three parts: a bot token, an HTTP client that talks to a chat API, and a little glue for memory and message length. This guide builds all three with discord.py and the standard OpenAI SDK.
Updated

No card needed. After sign-up, claim $0.50 of free test credit with one click (once per person).
Get API keyKey points
- The OpenAI Python SDK works with only a base URL and key change, so discord.py needs no special client.
- Keep a short history per channel, trim it, and split replies at 2,000 characters.
- Cap concurrency below 8 and let the SDK retry 429 responses.
- A server with 1,000 replies a day costs roughly $7.65 a month at the listed token prices.
The short version
If you want an ai chat bot discord integration that answers when someone mentions it, you need a Discord application with a bot user, the Message Content intent switched on, and about forty lines of Python. The bot receives a message event from Discord, sends the recent conversation to POST /v1/chat/completions, and posts the reply back to the channel.
Because the API is OpenAI-compatible, you use the normal openai package. Point it at https://api.nofilteraichat.top/v1, set the model to uncensored, and pass your key as a bearer token. Nothing else about the bot depends on the provider, so you can test the same code against any other compatible endpoint later.
The rest of this page covers what the short version leaves out: where memory lives, how to stay under Discord's message size limit, how many requests your bot may run at once, and what the bill looks like for a busy server.
What you need before you write code
- A Discord account with permission to add a bot to a server you manage.
- An API key. Sign-up is covered on the API key page, and new accounts can claim a small trial credit there to test the bot before topping up.
- Python 3.9 or newer, plus
pip install discord.py openai.
Create the application and bot user
Open the Discord Developer Portal, create a new application, and add a bot under the Bot tab. Copy the bot token and treat it like a password. On the same tab, enable the Message Content Intent. Without it your bot receives messages with an empty body, which is the most common reason a first bot appears to ignore everyone.
Then use the OAuth2 URL generator, select the bot scope, and give the bot permission to read messages and send messages. Open the generated link and add the bot to your server. Store both secrets as environment variables, for example DISCORD_TOKEN and NOFILTER_API_KEY, so they never end up in a repository.
A minimal bot that replies to mentions
This version has no memory. Each mention is answered on its own, which is enough to confirm that your token, intent and API key all work.
import os
import asyncio
import discord
from openai import AsyncOpenAI
ai = AsyncOpenAI(
base_url="https://api.nofilteraichat.top/v1",
api_key=os.environ["NOFILTER_API_KEY"],
max_retries=4,
)
SYSTEM = (
"You are Mara, a dry-witted ship navigator in a sci-fi roleplay server. "
"Stay in character and keep replies under 150 words."
)
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Client(intents=intents)
gate = asyncio.Semaphore(6)
@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()
async with message.channel.typing():
async with gate:
resp = await ai.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": text},
],
temperature=0.8,
max_tokens=400,
)
await message.reply(resp.choices[0].message.content[:2000])
bot.run(os.environ["DISCORD_TOKEN"])
Run it, mention the bot in a channel, and you should see the typing indicator followed by a reply. The first check in the handler ignores other bots, including itself, which prevents two bots from talking to each other forever and burning credit.
Add memory per channel
A model has no memory between calls. Every request must carry the conversation so far. The simplest store for a Discord bot is a dictionary keyed by channel id, holding the last few turns.
from collections import defaultdict, deque
history = defaultdict(lambda: deque(maxlen=12))
async def reply_with_memory(message, text):
turns = history[message.channel.id]
turns.append({"role": "user", "content": message.author.display_name + ": " + text})
async with gate:
resp = await ai.chat.completions.create(
model="uncensored",
messages=[{"role": "system", "content": SYSTEM}] + list(turns),
temperature=0.8,
max_tokens=400,
)
answer = resp.choices[0].message.content
turns.append({"role": "assistant", "content": answer})
return answer
Prefixing each user line with the Discord display name lets the model tell speakers apart in a shared channel. The deque(maxlen=12) drops the oldest turns automatically, so the prompt size stays bounded. The context window is 100,000 tokens, counting prompt and completion together, so a dozen turns is far below the ceiling. You trim for cost and focus, not because you are about to hit the limit.
Memory in a Python dictionary disappears when the process restarts. If you want it to survive, write the deque to SQLite or Redis on each turn. The format is already a plain list of role and content dictionaries, so it serializes to JSON without changes.
Handle the 2,000 character limit
Discord rejects messages longer than 2,000 characters. Roleplay replies can easily exceed that if you raise max_tokens. Rather than truncating, split the text on a newline or space and send several messages.
def chunks(text, size=1900):
while text:
if len(text) <= size:
yield text
break
cut = text.rfind("\n", 0, size)
if cut < size // 2:
cut = text.rfind(" ", 0, size)
if cut <= 0:
cut = size
yield text[:cut]
text = text[cut:].lstrip()
# inside on_message
answer = await reply_with_memory(message, text)
for part in chunks(answer):
await message.channel.send(part)
The limit is 1,900 rather than 2,000 to leave a margin for formatting characters that Discord counts. Streaming is possible too: set stream: true and edit a single message as tokens arrive. That works, but Discord throttles message edits, so most bots update every second or two instead of on every token. For a first version, a typing indicator and one finished reply feels fine.
Stay inside the rate limits
A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. When you go over, the API answers HTTP 429 with the error code rate_limited for the per-minute limit or concurrency for too many simultaneous requests. A 429 with a Retry-After: 5 header means temporary overload, and waiting five seconds is the correct response.
Three habits keep a Discord bot out of trouble:
- Gate concurrency. The
asyncio.Semaphore(6)above guarantees that no more than six requests are in flight, leaving headroom for a second process or a test script. Use a smaller number on a trial key. - Let the SDK retry. The OpenAI client retries 429 responses and honours
Retry-After. Settingmax_retries=4covers short bursts without extra code. - Remember that streams hold a slot. A streamed request occupies its concurrency slot until the stream ends, so a slow stream in a popular channel counts against your eight.
If a channel is busy enough to queue requests for many seconds, tell users. A short message such as "Mara is thinking, queue position 3" is better than silence. The response headers include X-Request-Id and X-Balance-USD, which are handy to log when you want to track spend or report a problem to support.
Roleplay bots and server rules
The model is tuned to answer without content refusals for lawful adult use, which makes it a fit for dark fantasy, horror, villain monologues and companion-style characters on servers that are meant for adults. Your bot still lives inside Discord's terms and community guidelines, and your server rules still apply. Keep a bot that produces mature fiction in channels marked age-restricted, and do not run it where members include minors. The API has one hard limit of its own: no sexual content involving minors.
Put your own guardrails in the system prompt and in code. A few that work well in practice:
- State the character, tone and length limit in the system message, and repeat a short reminder if you replay long histories.
- Add a
/resetcommand that clears the channel's deque, so a conversation that has drifted can start fresh. - Respond only to mentions or a specific channel, not to every message. This also keeps requests, and cost, predictable.
For a utility bot, such as a summarizer or a code helper, the same skeleton applies. Change the system prompt, drop the display-name prefix if you do not need it, and lower the temperature to 0.2 for steadier answers. You can also pass response_format={"type": "json_object"} when a slash command needs structured output.
What a busy server costs
Billing is pay as you go from prepaid credit at $0.15 per 1M input tokens and $0.50 per 1M output tokens. The input side is larger for a bot with memory, because every call resends the history.
Suppose your server triggers 1,000 replies a day, each with about 1,200 input tokens (system prompt plus twelve turns) and 150 output tokens.
- Input: 1,000 x 1,200 = 1,200,000 tokens, which is 1.2M x $0.15 = $0.18.
- Output: 1,000 x 150 = 150,000 tokens, which is 0.15M x $0.50 = $0.075.
- Daily total: $0.255. Over 30 days that is $7.65.
Failed or refused requests are not charged, and credit never expires, so an idle month costs nothing. Top-ups are any whole amount from $20 to $500, with a 5% bonus from $50, 10% from $100 and 15% from $200. Pay with crypto (USDT on TRC20, USDC on Base). The pricing page has the full table, and the quickstart docs list every supported parameter if you want to tune sampling. For a more general walkthrough of the endpoint itself, see the chat API guide.
More guides
Questions and answers
Do I need a special Discord library to use this API?
No. Any Discord library works, since the API call is separate from Discord. discord.py, discord.js and others all just need an HTTP client or the OpenAI SDK pointed at the base URL.
Why does my bot see empty messages?
The Message Content intent is off. Enable it in the Developer Portal under the Bot tab and set intents.message_content to true in your code.
Can the bot stream replies into Discord?
Yes. Set stream to true and edit one message every second or so. Remember that a stream holds its concurrency slot until it finishes.
How do I test the bot without paying first?
New users can claim a trial credit with one click on the API key page after sign-up. The trial key has lower limits: 2 concurrent requests and 60 per minute.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.