ChatGPT Bot for Discord on an OpenAI-Compatible API
A Discord bot that talks like a chat assistant needs three things: a gateway client, a model API and some memory. Here is a working Python version that uses an OpenAI-compatible endpoint instead of the usual one.
Updated

Key points
- discord.py plus the openai library is enough; only the base URL and model name differ.
- Keep a short rolling history per channel and trim it before it grows.
- Edit the reply while it streams, but not on every token.
- At $0.15 and $0.50 per 1M tokens, 1,000 replies of typical size cost under a dollar.
What you are building
A chatgpt bot for discord is a small program with two halves. One half is a Discord client that listens for messages, usually when the bot is mentioned. The other half calls a chat completions API with the recent conversation and posts the answer back. The language model does not care that the request came from Discord, so any OpenAI-compatible endpoint can sit behind it.
This guide uses the endpoint at https://api.uncensoredgpt.cc/v1 with the model ID uncensored. That model is tuned to answer without content refusals for lawful adult use, which suits bots for fiction, roleplay or adult community servers where a stock assistant keeps declining. Discord has its own rules for bots and for age-restricted channels, so read them and keep this kind of bot in the places where it is allowed. The minors rule is absolute: the model never produces sexual content involving minors.
Prerequisites
- A Discord application with a bot user, created in the Discord developer portal. Copy the bot token.
- The Message Content intent switched on for that bot, because the bot needs to read the text of messages that mention it.
- Python 3.10 or newer, with
pip install discord.py openai. - An API key. A new account can claim a $0.50 trial in one click on the key page, which needs no card and is valid for 7 days. See how to get an API key.
Put both secrets in environment variables, DISCORD_TOKEN and LLM_API_KEY, and never commit them.
The bot, step by step
The bot below answers when it is mentioned. It keeps the last few turns for each channel in memory, sends them with a system prompt, and streams the answer into a message that it edits as text arrives.
import asyncio
import os
from collections import defaultdict, deque
import discord
from openai import AsyncOpenAI
llm = AsyncOpenAI(
base_url="https://api.uncensoredgpt.cc/v1",
api_key=os.environ["LLM_API_KEY"],
)
SYSTEM = "You are a witty assistant in a Discord server. Keep answers under 1500 characters."
history = defaultdict(lambda: deque(maxlen=12)) # last 12 messages per channel
slots = asyncio.Semaphore(6) # stay under 8 concurrent requests
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Client(intents=intents)
@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.name}", "").strip()
history[msg.channel.id].append({"role": "user", "content": f"{msg.author.display_name}: {text}"})
reply = await msg.reply("...")
messages = [{"role": "system", "content": SYSTEM}, *history[msg.channel.id]]
async with slots:
stream = await llm.chat.completions.create(
model="uncensored",
messages=messages,
stream=True,
temperature=0.8,
max_tokens=500,
)
answer, last_edit = "", 0.0
async for chunk in stream:
if not chunk.choices:
continue
answer += chunk.choices[0].delta.content or ""
now = asyncio.get_event_loop().time()
if now - last_edit > 1.2 and answer:
await reply.edit(content=answer[:1990])
last_edit = now
await reply.edit(content=answer[:1990] or "(no answer)")
history[msg.channel.id].append({"role": "assistant", "content": answer})
bot.run(os.environ["DISCORD_TOKEN"])Three details matter here. The semaphore caps how many requests the bot has in flight, because a full key allows 8 at once and a streamed request holds its slot until the stream ends. The edit throttle is there because Discord rate-limits message edits, so updating on every token would stall the bot. And the answer is cut at 1,990 characters because a Discord message cannot exceed 2,000.
Memory, and why 100,000 tokens is not a reason to use all of it
The context window is 100,000 tokens, prompt plus completion. That is large enough to paste a long character sheet, a server rulebook or a whole chapter of a story. It is tempting to keep the entire channel log in the prompt. Resist it, because you pay for every input token on every turn.
A rolling window of 12 messages, as in the code above, is a good start. For a roleplay channel you can pin a longer fixed block at the top, such as a persona and a few rules, and let only the chat part roll. If a channel needs long memory, store a short summary yourself and prepend it, rather than sending the raw log. Per-channel history also means two people talking in different channels do not see each other's context, which is usually what you want.
One more habit: store a name in each user message, as the code does, so the model can tell speakers apart in a busy channel. Without it, a group chat collapses into one voice.
Handling 429s and slow replies
A bot in a busy server can exceed the limits of a key: 8 concurrent requests and 300 requests per minute for a full key, 2 and 60 for a trial key. The API answers with HTTP 429. The error code is rate_limited when you exceeded the per-minute count, concurrency when too many requests ran together, and on temporary overload the response carries a Retry-After: 5 header.
The openai library retries some errors on its own, but a bot should also tell the user something. Wrap the call, catch openai.RateLimitError, wait the number of seconds in the header, and retry once. If it still fails, edit the placeholder to say the bot is busy. Never leave a "..." message hanging, because that looks like a crash.
import openai
async def ask(messages):
for attempt in range(2):
try:
return await llm.chat.completions.create(
model="uncensored", messages=messages, max_tokens=500
)
except openai.RateLimitError as e:
wait = int(e.response.headers.get("Retry-After", "5"))
await asyncio.sleep(wait)
return NoneFor a large server, add a per-user cooldown of a few seconds. It protects your credit as well as your rate limit.
When the bot says nothing
Most first-run failures have dull causes. Work down this list before you suspect the model.
- The bot never reacts to mentions. The Message Content intent is probably off, either in the developer portal or in your code. Both places must agree.
- It reacts in some channels only. The bot role lacks permission to read or send messages in the other channels. Check the channel overrides as well as the server role.
- It answers twice. Two copies of the process are running, often an old terminal you forgot. Kill the extra one.
- Discord returns an error about message length. The 2,000-character cap was exceeded. The slice in the code prevents it, but if you add a prefix, shorten the slice to match.
- The reply is cut off mid-sentence. That is
max_tokens=500doing its job. Raise it or ask the model for shorter answers in the system prompt. - An authentication error appears in the console. The key is missing from the environment of the process, which commonly happens when the bot runs under a service manager that does not load your shell profile.
Keep the console output. When a request fails on the API side, the X-Request-Id response header is the identifier to quote in a message to support.
Keeping it running
A bot is a long-lived process, so a laptop terminal is only good for development. A cheap virtual machine, a container or a process manager such as systemd or pm2 will restart it after a crash or a reboot. Load the two secrets from the service's environment file with restrictive permissions, and keep that file out of your repository.
Because the history lives in memory, a restart forgets every conversation. That is acceptable for casual servers. If you want continuity, write each channel's last few messages to a small SQLite file after every reply and load them on start. Keep the stored text short for the same reason you trim the prompt: you pay for every token you send again.
Finally, give moderators a kill switch. A simple admin-only command that flips a flag and makes the bot ignore mentions costs ten lines and can save a bad evening. Because this model is tuned not to refuse, server rules about what the bot may write are yours to enforce, in the system prompt and in channel settings.
When the mention-based bot works, add a slash command, a /reset command that clears the channel history, and a per-channel system prompt. For structured output, such as a game state returned as a JSON object, JSON mode is available through response_format, and tool calling works if you want the bot to call your own functions. The docs cover both, along with the full parameter list.
What it costs to run
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit. Suppose a typical reply sends 1,500 input tokens (system prompt plus 12 messages of history) and returns 300 tokens.
- Input: 1,500 × $0.15 / 1,000,000 = $0.000225
- Output: 300 × $0.50 / 1,000,000 = $0.00015
- Per reply: $0.000375, so 1,000 replies cost $0.375
A minimum top-up of $20 would cover about 53,000 replies of that size ($20 / $0.000375 = 53,333). The credit never expires, so a quiet server does not waste it, and a failed or refused request is not charged. Top-ups run from $20 to $500 with a bonus of 5% from $50, 10% from $100 and 15% from $200; see the pricing page. You can pay with crypto (USDT on TRC20, USDC on Base).
The X-Balance-USD response header shows the remaining balance, so the bot can warn you in a private channel when credit drops below a threshold you choose.
More guides
Questions and answers
Do I need a different library from the usual OpenAI one?
No. The standard openai Python package works. You set base_url to the endpoint and use uncensored as the model ID.
Can the bot stream replies?
Yes, streaming over server-sent events is supported. In Discord you edit one message every second or so rather than on every chunk, to stay inside Discord's edit limits.
How many users can the bot serve at once?
A full key allows 8 concurrent requests and 300 requests per minute. Beyond that you get HTTP 429, so queue requests or use a per-user cooldown.
Can I test it without paying?
Yes. New users can claim $0.50 of trial credit with one click after sign-up. It needs no card, is valid for 7 days, and the trial key allows 2 concurrent requests.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.