Grok AI Discord Bot: Build One With an Open API
A grok ai discord bot is usually a bot that chats in a server with a sharp tone and fewer refusals than the stock options. You can build exactly that in about 60 lines of Python against an OpenAI-compatible endpoint, and this guide walks through every step.

What you are building
The idea is simple. Someone mentions your bot in a channel, your script collects the recent messages, sends them to a language model, and posts the answer back. The model does the writing, and Discord only sees a normal bot account. Nothing about this requires access to the official Grok service, which is a different product with its own terms.
Here you will use a hosted open-weight model that answers without content refusals for lawful adult use. It follows the OpenAI chat completions format, which means the standard openai Python package works once you change the base URL. The model ID is uncensored.
If you are making a bot for a community that is not adults-only, you should think about tone before you ship. A model that does not refuse will happily go where the conversation goes, so the system prompt and the channel you deploy in matter more than usual. We come back to this near the end.
Prerequisites
You need four things before writing any code.
- Python 3.9 or newer, plus
pip install discord.py openai. - A Discord application with a bot user, created in the Discord Developer Portal. Copy the bot token and keep it out of your repository.
- The Message Content intent switched on for that bot in the Developer Portal. Without it your bot receives messages with empty text.
- An API key for this service. Sign up on the API key page and claim the $0.50 trial credit with one click. It needs no payment method and is valid for 7 days, which is enough to build and test everything below.
Store both secrets as environment variables, for example DISCORD_TOKEN and LLM_API_KEY. Invite the bot to a test server with the permissions to read and send messages in the channel you plan to use.
The bot, step by step
Below is a complete working script. It replies when the bot is mentioned, remembers the last 20 messages per channel, and splits long answers to fit Discord's 2,000 character message limit.
import asyncio
import os
import discord
from openai import AsyncOpenAI
SYSTEM = (
"You are Rook, a dry-witted assistant in a Discord server for adults. "
"Keep replies under 150 words unless asked for more. Stay in character."
)
llm = AsyncOpenAI(
base_url="https://api.unfilteredgrok.com/v1",
api_key=os.environ["LLM_API_KEY"],
)
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Client(intents=intents)
history = {} # channel id -> list of messages
slots = asyncio.Semaphore(6) # stay under the 8 concurrent limit
@bot.event
async def on_message(message):
if message.author.bot or bot.user not in message.mentions:
return
text = message.clean_content.replace(f"@{bot.user.display_name}", "").strip()
log = history.setdefault(message.channel.id, [])
log.append({"role": "user", "content": f"{message.author.display_name}: {text}"})
del log[:-20]
async with slots, message.channel.typing():
resp = await llm.chat.completions.create(
model="uncensored",
messages=[{"role": "system", "content": SYSTEM}] + log,
max_tokens=500,
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 message.channel.send(reply[i:i + 1900])
bot.run(os.environ["DISCORD_TOKEN"])
Run it, mention the bot in your test channel, and you should get an answer within a few seconds. Prefixing each user line with the display name lets the model tell speakers apart in a busy channel, which is the cheapest way to get sensible group replies.
Why a semaphore
A full key allows 8 concurrent requests and 300 requests per minute. A semaphore of 6 keeps a burst of mentions from tripping the concurrency limit and leaves a couple of slots free for anything else using the same key. A trial key allows only 2 concurrent requests and 60 per minute, so drop the semaphore to 2 while you test.
Handling limits and errors
When you exceed a limit, the API answers HTTP 429. The error code is rate_limited for too many requests per minute and concurrency for too many in flight at once. A temporary overload also gives a 429, with a Retry-After: 5 header. The official OpenAI Python client retries some failures on its own, but for a bot it is worth being explicit.
import openai
from openai import AsyncOpenAI
llm = AsyncOpenAI(base_url="https://api.unfilteredgrok.com/v1", api_key="YOUR_API_KEY")
async def ask(messages):
for attempt in range(3):
try:
return await llm.chat.completions.create(
model="uncensored", messages=messages, max_tokens=500
)
except openai.RateLimitError:
await asyncio.sleep(5 * (attempt + 1))
return None
If ask returns None, send a short apology to the channel instead of crashing the event handler. Failed and refused requests are not charged, so retrying does not cost extra. If you want live typing, you can set stream: true, but remember that a streamed request holds its concurrency slot until the stream ends, and Discord message edits are rate limited too. For most bots, one complete message per answer is simpler and just as good.
What it costs to run
The price is $0.15 per 1M input tokens and $0.50 per 1M output tokens, billed from prepaid credit. Take a busy channel where each call sends about 4,000 tokens of system prompt plus history and returns 400 tokens.
- Input: 4,000 x $0.15 / 1,000,000 = $0.0006
- Output: 400 x $0.50 / 1,000,000 = $0.0002
- Per reply: $0.0008
That is $0.80 for 1,000 replies, and a $20 top-up covers 25,000 replies of that size. A bot that answers 300 mentions a day would use about $0.24 a day. Credit never expires, so a quiet month costs nothing. Top-ups run from $20 to $500 in whole dollars, with a +5% bonus from $50, +10% from $100 and +15% from $200, paid in USDT on TRC20 or USDC on Base. The pricing page lists the details.
To trim cost, shorten the history window and keep the system prompt tight. Every token you resend on every turn is billed again as input.
Making group chat feel natural
A Discord channel is not a one-to-one chat, and a bot that treats it like one tends to feel strange. People interrupt each other, change topic and answer old messages. A few small choices in the script make a visible difference.
First, decide what the bot sees. Feeding it every message in the channel is expensive and noisy, so the example above stores only the messages that mention the bot, plus its own replies. If you want the bot to follow the room, store the last few messages from everyone but only reply when mentioned. The extra context costs input tokens, so keep it to ten or fifteen lines.
Second, tell the model who it is talking to. The display-name prefix in each line is enough for the model to address people by name and keep two conversations apart. Add a sentence to the system prompt such as "Several people may speak; answer the person who mentioned you."
Third, keep replies short. A system prompt line that caps length at around 150 words gives the quick back-and-forth people expect in chat, and it keeps the output bill small. If a user wants a long story, let them ask for it explicitly, and raise max_tokens for that command only.
Last, run the script somewhere that stays up. A small VPS with a systemd service, or a container with a restart policy, is enough. The bot holds no state except the in-memory history, so a restart only means it forgets recent context.
Keeping the bot safe to run
The model is tuned not to refuse, so the guardrails live in your code and your server settings. A few habits help.
- Restrict the bot to specific channels and keep any adult-themed persona in channels that Discord lets you mark as age-restricted. Follow Discord's own rules for bots and servers.
- State in the system prompt who the audience is and what topics are out of bounds for your community. The model follows those instructions.
- Never allow sexual content involving minors. It is the one hard limit on this service, and you should also block it in your own rules and report violations.
- Add a cooldown per user, for example one reply per five seconds, so one person cannot drain your credit.
The same pattern works for roleplay servers, tabletop game masters, and companion-style bots. Only the system prompt and the history window change.
Next steps
Once the basic bot works, a few upgrades are straightforward. Add slash commands by using discord.app_commands. Store history in a database so the bot remembers a channel after a restart. Use tool calling to let the bot roll dice or look things up, since the endpoint supports tools, tool_choice and tool results sent back as role: "tool". JSON mode, enabled with response_format: {"type":"json_object"}, helps when you want structured output for a game engine.
Full parameter details are on the docs page. For the background on how this endpoint relates to Grok-style tools, the Grok API explainer is a short read.
More guides
Questions and answers
Does this use the official Grok API?
No. It calls an independent hosted open-weight model through an OpenAI-compatible endpoint. It is not made by xAI and does not forward your messages to xAI.
Can I use discord.js instead of discord.py?
Yes. Any library works because the model call is a plain HTTPS request. Use the openai npm package with baseURL set to https://api.unfilteredgrok.com/v1 and the model uncensored.
How many users can the bot serve at once?
A full key allows 8 concurrent requests and 300 requests per minute. Queue extra messages with a semaphore, and retry on HTTP 429 after the Retry-After delay.
Are my server's messages used for training?
Prompts are not used for training. Still, tell your members that their messages are sent to an external API.