By the end of this course, your Discord server will have a member who is not a person: a bot with Grok for a brain, answering questions right in the channel, in whatever personality you give it. You will build it from three parts that each take a few minutes: a key from xAI, a bot account from Discord, and one small Python file that connects them. Every step is shown in a screenshot. No experience is assumed, and the whole build fits in an afternoon.
Starvard University Build a Grok Bot for Discord · Starvard University
The whole course in brief
A Discord bot is two accounts and a wire. Discord gives the bot an account in your server. xAI gives Grok an API key. One small Python file is the wire between them.
The key and the token are both passwords. You will create one of each, paste each exactly once into a private file, and never share them. If one ever leaks, you reset it and move on.
One switch decides whether the bot works. Message Content Intent, in Discord's developer portal. Off, and the bot is a statue. On, and it can read what people write.
The code fits on one page. About fifty lines, and Lesson 5 explains every block. You can copy it whole and change the personality line to make the bot yours.
A bot is a program that has to keep running. Your laptop is fine for the first version. Lesson 8 covers keeping it online around the clock and what it costs.
Eight short lessons. The screenshots are careful recreations of the real screens, drawn so every button stays big and readable on a phone.
Think of the finished bot as a very fast errand runner. Someone in your server types a question and mentions the bot. Your little program hears it, carries the question to Grok, waits a second, and carries the answer back as a reply. That loop, a few times a minute, is the entire product. Bots that feel magical are usually this loop plus a good personality.
how your bot works, in one picture
The whole idea on one screen. Discord is the room, your Python file is the messenger, and Grok is the brain it asks. Nothing else is required.
Three things to gather before the fun starts:
An xAI account (Lesson 2). This is where Grok lives. Using Grok through its API is separate from an X subscription: the API has its own console, its own keys, and its own pay-as-you-go credits.
A Discord account and a server you manage (Lesson 3). You need the Manage Server permission on the server you want to invite the bot into. Your own test server is perfect for version one.
A computer with Python 3 (Lesson 4). Any ordinary laptop works. The bot is a small program, not a supercomputer job.
One naming note. In this course the example bot is called GrokBuddy. Name yours anything you like; every screenshot just gets clearer with a name attached.
Try this first. Create a private test server in Discord (the plus button in the left rail, Create My Own, For me and my friends). Your bot will live there while you learn, and nobody has to watch it break.
2. Get your Grok key from xAI
The API key is a long secret string that tells xAI: this program is allowed to ask Grok questions, and this account pays for the answers. Getting one takes about three minutes.
Go to console.x.ai and sign in. You can use an X account or an email address.
Open API Keys in the left hand menu.
Press Create API Key. Name it for where it will live, like discord-bot. Names matter later, when one key is for a bot and another is for something else.
Copy the key right now. It starts with xai- and it is shown in full exactly once. After you close that box, the console only ever shows its last few characters. Paste it into a private note for the next hour; Lesson 4 gives it a permanent home.
Add a little credit under Billing. The API runs on prepaid credits, and a brand new key with no balance cannot answer anything. A small amount is plenty to learn on, and the Usage page will show you every cent as it goes.
console.x.ai
Recreated screenshot: the xAI console. 1 Open API Keys in the left menu. 2 Press Create API Key and name it something you will recognize, like discord-bot. 3 Copy the key immediately and keep it somewhere private. You will paste it into your bot in Lesson 4.
The one rule of keys. A key is a password that spends money. Never post it in a chat, a screenshot, or a public code repository. If it ever escapes, come back to this page, delete the key, and make a fresh one. Two minutes, no harm done.
3. Create your bot in Discord
Now the other account. Discord bots are created in a special workshop called the Developer Portal. You will make an application, turn on its bot half, and collect its token.
Go to discord.com/developers/applications and press New Application, top right. Name it (GrokBuddy, in our example) and create it.
Open the Bot page in the left menu. This page is your bot's control room: its username, its picture, and its token all live here.
Press Reset Token and confirm. The token appears once, like the xAI key did. Copy it into the same private note for now. This token is how your program will log in as the bot.
Scroll down to Privileged Gateway Intents and switch on Message Content Intent. Then press Save Changes. This is the famous step everyone forgets, and Lesson 7 will remind you what its absence looks like: a polite, silent statue.
discord.com/developers/applications
Recreated screenshot: your app's Bot page. 1 Open the Bot section. 2 Press Reset Token and copy the token it shows you, once. 3 Scroll down and switch on Message Content Intent, then save changes at the bottom of the page.
While you are here, you can also upload a profile picture for the bot on this same page, under its username. A friendly face makes a surprising difference to how a server treats a bot.
Two secrets, two homes. The xAI key proves who pays for answers. The Discord token proves who is speaking. Your code needs both, and strangers must get neither. The next lesson puts them in the right place.
4. Set up the project on your computer
Your bot is a folder with two small files in it. Let us build the folder.
Check Python. Open a terminal (Terminal on a Mac, Command Prompt or PowerShell on Windows) and type python3 --version. Any version 3.10 or newer is fine. If Python is missing, install it from python.org and come back.
Make a folder called grokbot somewhere sensible, and step into it in the terminal.
Create a private corner for libraries and install the three the bot needs:
On Windows, the middle line is venv\Scripts\activate instead. The three libraries: discord.py talks to Discord, openai talks to Grok (Lesson 5 explains why an OpenAI library can do that), and python-dotenv reads your secrets file.
That secrets file is the second file in the folder. Create a text file named exactly .env (yes, it starts with a dot, and it has no other name) and put your two secrets in it, one per line:
Never share the .env file. Not in a screenshot, not in a chat, not in a code repository. If you ever put this folder on GitHub, add a file named .gitignore containing the single line .env first. That one habit prevents nearly every leaked-bot story on the internet.
One bot, one .env. New project, new folder, new secrets file. It keeps accidents small.
Checkpoint. Folder named grokbot, libraries installed without errors, .env written with both secrets pasted in. That is everything the code needs. Next lesson is the code itself.
5. The whole bot in one file
Create a file named bot.py in the same folder, and put this in it. It is the entire bot. After the code, we walk through what each part does, because code you understand is code you can change.
import os
import discord
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
XAI_KEY = os.getenv("XAI_API_KEY")
# Grok lives at api.x.ai and speaks the OpenAI shape,
# so the OpenAI library works with a different address.
grok = OpenAI(api_key=XAI_KEY, base_url="https://api.x.ai/v1")
SYSTEM_PROMPT = (
"You are GrokBuddy, a friendly bot in a small Discord server. "
"Answer in two or three short sentences, warm and playful. "
"If you do not know something, say so."
)
intents = discord.Intents.default()
intents.message_content = True # matches the switch from Lesson 3
bot = discord.Client(intents=intents)
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
@bot.event
async def on_message(message):
if message.author == bot.user:
return # never answer yourself, or you will loop forever
mentioned = bot.user in message.mentions
is_dm = isinstance(message.channel, discord.DMChannel)
if not mentioned and not is_dm:
return # only answer when spoken to
question = message.content.replace(f"<@{bot.user.id}>", "").strip()
if not question:
await message.reply("Hi! Ask me anything.")
return
async with message.channel.typing():
answer = grok.chat.completions.create(
model="grok-4-0709",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": question},
],
)
text = answer.choices[0].message.content
await message.reply(text[:1900]) # Discord caps messages at 2000 characters
bot.run(DISCORD_TOKEN)
The tour, top to bottom:
The secrets load first. load_dotenv reads your .env, and the two secrets arrive as ordinary variables. Notice the code itself contains no secrets, which is exactly why the code is safe to share and the .env is not.
Grok gets an OpenAI shaped door. xAI built its API to speak the same language as OpenAI's, so the standard openai library works if you point it at https://api.x.ai/v1 and hand it your xAI key. Two platforms, one library, no extra learning.
The system prompt is the personality. One short paragraph telling Grok who it is in your server and how to talk. Everything in Lesson 8 starts by editing these three sentences.
Intents declare what the bot may see. The message_content line matches the switch you turned on in Lesson 3. Portal and code must agree, or the bot reads nothing.
on_ready is the hello. It prints one line when the bot logs in. That line is your proof of life in Lesson 7.
on_message is the whole job. Ignore your own messages (or the bot will reply to itself forever). Answer only when mentioned, or when the message is a DM. Show the typing dots while Grok thinks. Trim the answer to fit Discord's 2000 character limit.
The model name is a string you can update. This course uses grok-4-0709. Model names change over time; docs.x.ai always lists the current ones, and updating a bot is changing one line and restarting it.
Read it once more before moving on. Fifty lines, and you now own every one of them. The next two lessons are pure ceremony: invite the bot in, and switch it on.
6. Invite the bot to your server
A bot account exists, but it belongs to no server yet. Inviting it is a link, and Discord builds the link for you.
Back in the Developer Portal, open your application and go to OAuth2, then URL Generator.
Under Scopes, tick bot. A second list appears below it: Bot Permissions.
Tick three permissions: View Channel (so it can see the room), Send Messages (so it can speak), Read Message History (so it can follow a conversation). Leave everything else off. A bot should hold the smallest set of keys that does its job.
Copy the generated URL at the bottom of the page, paste it into your browser, choose your test server, and press Authorize.
Recreated screenshot: the URL Generator, inside OAuth2. 1 Tick the bot scope, nothing else. 2 Tick exactly three permissions: View Channel, Send Messages, Read Message History. 3 Your invite link appears at the bottom, ready to copy.
The bot now appears in your server's member list, greyed out and offline. Offline is expected: nobody is running its brain yet. That is the next lesson, and it takes ten seconds.
Doing it by hand. The generated link is an ordinary web address with your app's ID in it. Your app ID is on its General Information page, and the pattern is discord.com/oauth2/authorize?client_id=YOUR_ID&permissions=68608&scope=bot, where 68608 is simply the three permissions from this lesson added up. Handy when the portal is slow.
7. Run it and say hello
In the terminal, inside the grokbot folder with the virtual environment active (Lesson 4), run one command:
python3 bot.py
The terminal answers with the line your code promised: Logged in as GrokBuddy, followed by its full username. In Discord, the grey dot beside your bot's name turns green. Now, in any channel it can see, type a mention and a question:
Discord · your server · #general
Recreated screenshot: the moment it works. You @mention the bot with a question, and a second later the reply lands in the channel with a little BOT tag beside its name. Everything before this lesson exists to produce this picture.
That is a working Grok bot, built by you, answering in your server. Everything after this is refinement.
When it does not work, it is almost always one of these four, in this order:
The bot stays offline. The program is not running, or the token in .env is wrong or old. Re-run the file, read the terminal's error line, and re-paste the token from the Bot page if needed.
The bot is online but silent. Message Content Intent is off, in the portal (Lesson 3) or in the code (Lesson 5). Both must be on. Also check you actually mentioned it: in a server channel, this version only answers when spoken to.
An error mentions 401. A secret is being refused. 401 from Discord means the token; 401 from xAI means the key, or an empty credit balance.
Answers stop mid thought. Probably the 2000 character wall. The code trims to 1900; if you raise Grok's answer length, split long replies into two messages instead.
Leave it running. The bot lives exactly as long as that terminal window stays open on your computer. Closing the laptop ends the bot's day. For a bot that never sleeps, read on.
8. Make it yours, and keep it alive
A working bot is a skeleton. These four upgrades turn it into a member of the server.
Give it a personality. Rewrite the SYSTEM_PROMPT in your own words. Who is this bot in your community: a librarian, a hype coach, a deadpan trivia master? Add house rules while you are there ("never discuss spoilers for the new season", "always answer in haiku on Fridays"). Restart the file and the new person shows up. This one paragraph is where bots stop being demos.
Give it a short memory. Right now the bot forgets every question the second it answers. Keeping the last few exchanges per channel fixes most of that, and it is a small change: a list per channel, trimmed to six turns, sent along with each new question.
history = {} # one short memory per channel
# inside on_message, replace the single question-and-answer call with:
past = history.setdefault(message.channel.id, [])
past.append({"role": "user", "content": question})
past = past[-6:] # keep only the last six turns
history[message.channel.id] = past
answer = grok.chat.completions.create(
model="grok-4-0709",
messages=[{"role": "system", "content": SYSTEM_PROMPT}] + past,
)
past.append({"role": "assistant",
"content": answer.choices[0].message.content})
Mind the meter. Grok answers are paid by the token, and memory makes every question longer, because the old conversation rides along. Six turns is a good budget. The Usage page in the xAI console shows the running total; check it after busy days, and prefer a smaller, faster model from the docs list if your server mostly wants quick chat.
Keep it online. A bot is just a program that must not stop. In order of effort: leave it running on a home computer that stays awake; put it on a small rented server (a VPS) where it can run for months untouched; or use a hosting service that keeps Python programs alive for you. All three run the identical bot.py. When you update the code, restart the program and it picks the changes up.
Keep it safe. The short list that prevents every common disaster:
Tokens and keys live only in .env, and .env never gets shared or uploaded.
If a secret leaks anyway, reset it in its console first and ask questions later.
Keep the bot's permissions at the Lesson 6 minimum. It does not need to manage channels or ban anyone.
Remember it is a chatbot, not an oracle. Grok can be confidently wrong; in a friendly server that is entertainment, and anywhere serious it deserves a human check.
That is the whole craft: two accounts, one key, one token, one file, one invite link. The pattern you just learned is the same one behind a great many production bots; only the polish differs. Build the small one, watch real people talk to it, and let their questions teach you what to add next.
Your bot, assigned. This week: run the build in your test server, give your bot a name and a personality paragraph you wrote yourself, and invite it into one real channel with real people. Then come show the Starvard Discord what yours says when it is asked who it is.
Sources
The guides behind this course
Every step in this course follows the official documentation of the three tools it connects: xAI for the brain, Discord for the room, and discord.py for the wiring.
xAI developer documentation, API reference and model list (docs.x.ai), docs.x.ai
Starvard is a free university being built right now by kind, hard-working people. Do a first small task with us, like checking a course, adding a book to the library, or testing pages on your phone, and get $10 for it.