How to Build a Discord Bot That Auto-Replies With AI
Create a discord.js bot that listens for messages and answers with an LLM in real time.
A Discord bot that replies with AI turns any server into a help desk, a study buddy, or a lore-keeper. In this guide you will register a bot application, give it the right intents, and wire its messages to an LLM so it answers whenever someone mentions it. Everything runs on Node and a single file.
What you need
- A Discord account and a server where you can add a bot
- Node 18+ installed (
node -vto check) - An OpenAI API key (or any chat-completions compatible key)
- Five minutes in the Discord Developer Portal
Step 1: Create the application and bot
Open the Discord Developer Portal, click New Application, name it, then open the Bot tab and click Add Bot. Copy the token now and keep it secret. A leaked token lets anyone control your bot, so treat it like a password.
Step 2: Invite the bot to your server
Under OAuth2 > URL Generator, tick the bot scope and the Send Messages and Read Message History permissions. Open the generated URL in a browser and pick your server. The bot now appears offline in the member list until you start the code.
Step 3: Install the libraries
Step 4: Write the bot
Put your secrets in a .env file, then create index.js. The bot ignores its own messages, only answers when mentioned, and shows a typing indicator while the model thinks.
DISCORD_TOKEN=your-bot-token
OPENAI_API_KEY=sk-your-keyimport "dotenv/config";
import { Client, GatewayIntentBits, Events } from "discord.js";
import OpenAI from "openai";
const ai = new OpenAI();
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
client.once(Events.ClientReady, (c) =>
console.log(`Logged in as ${c.user.tag}`),
);
client.on(Events.MessageCreate, async (msg) => {
if (msg.author.bot) return;
if (!msg.mentions.has(client.user)) return;
const prompt = msg.content.replace(/<@!?\d+>/g, "").trim();
await msg.channel.sendTyping();
const res = await ai.chat.completions.create({
model: "gpt-5-mini",
messages: [
{ role: "system", content: "You are a concise, friendly Discord helper." },
{ role: "user", content: prompt },
],
});
await msg.reply(res.choices[0].message.content.slice(0, 1900));
});
client.login(process.env.DISCORD_TOKEN);Step 5: Run it
Result
You now have a live Discord bot that replies with AI whenever a member mentions it. Host it on a small VPS or a free tier worker with a process manager like pm2 so it stays online after you close your laptop.
Watch related tutorials
12:38
14:09
17:53
15:00
12:00
1:42:18