Unhinged AI/How to Make an AI Discord Bot in Node.js
How to Make an AI Discord Bot in Node.js
To make an AI Discord bot you need three things: a Discord application with a token, an API key for a language model, and a short program that connects the two. This walkthrough uses Node.js and discord.js.
Updated
Key points
- Create the application and enable the Message Content intent before writing any code.
- The OpenAI npm package works as is. Only the base URL, key and model name change.
- Edit one message while the reply streams, but throttle edits to respect Discord's limits.
- Run the bot under systemd or pm2 so it comes back after a crash or reboot.

Step 1: Create the Discord application
Open the Discord developer portal, create a new application and add a bot under the Bot tab. Press the button to reset the token, copy it once and store it in a password manager. Anyone with that token controls your bot.
On the same tab, switch on the Message Content Intent. This is the setting that trips up most first-time builders. Without it the bot connects, shows as online, and then sees every message as an empty string.
Next, open the OAuth2 URL generator, tick the bot scope, tick the permissions View Channels, Send Messages and Read Message History, and open the generated link to add the bot to a server you manage. A private test server with just you in it is the best place to start.
Step 2: Get an API key and test it
The language side needs a key. Sign up on this site with Google or with email and password, then open the API key page and claim the $0.50 trial credit with one click. It needs no payment, lasts 7 days and is limited to one claim per person. That is plenty to build and test a bot.
Before involving Discord, confirm the key works with a single request. The service implements POST /v1/chat/completions in the OpenAI format, and the model ID is uncensored:
curl https://api.unhingedai.cc/v1/chat/completions \
-H "Authorization: Bearer $AI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"messages": [{"role": "user", "content": "Say hello in five words."}]
}'
A JSON reply with a choices array means the key, URL and model name are all correct. If you see HTTP 401, the key is wrong or missing the Bearer prefix. Testing here first saves you from guessing later whether a failure came from Discord or from the API.
Step 3: Set up the project
You need Node.js 18 or newer. Create a folder, run npm init -y, then npm install discord.js openai. Add "type": "module" to package.json so the import syntax below works. Put your secrets in the shell environment or an .env file that is listed in .gitignore: DISCORD_TOKEN and AI_API_KEY.
The official openai package does not care who hosts the model. You tell it where to send requests with baseURL. Everything else, including streaming helpers and error classes, behaves the way the OpenAI docs describe.
Step 4: The bot code
This bot answers when it is mentioned, keeps a short history for each channel and streams the answer into a single message that it edits as text arrives.
import { Client, GatewayIntentBits, Events } from "discord.js";
import OpenAI from "openai";
const ai = new OpenAI({
baseURL: "https://api.unhingedai.cc/v1",
apiKey: process.env.AI_API_KEY,
maxRetries: 3,
});
const bot = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
const SYSTEM = "You are a blunt, funny assistant in a private friends server. Keep answers short.";
const histories = new Map();
let active = 0;
bot.on(Events.MessageCreate, async (msg) => {
if (msg.author.bot || msg.mentions.has(bot.user) === false) return;
const text = msg.content.replace(/<@\d+>/g, "").trim();
if (text === "") return;
if (active >= 6) return msg.reply("Busy right now, ask again in a few seconds.");
const log = histories.get(msg.channelId) ?? [];
log.push({ role: "user", content: msg.author.displayName + ": " + text });
while (log.length > 10) log.shift();
histories.set(msg.channelId, log);
active++;
const sent = await msg.reply("...");
let reply = "";
let lastEdit = 0;
try {
const stream = await ai.chat.completions.create({
model: "uncensored",
messages: [{ role: "system", content: SYSTEM }, ...log],
temperature: 0.8,
max_tokens: 600,
stream: true,
});
for await (const part of stream) {
reply += part.choices[0]?.delta?.content ?? "";
if (Date.now() - lastEdit > 1500 && reply) {
await sent.edit(reply.slice(0, 1900));
lastEdit = Date.now();
}
}
await sent.edit(reply.slice(0, 1900) || "No answer came back.");
log.push({ role: "assistant", content: reply });
} catch (err) {
await sent.edit("Something went wrong on my side. Try again.");
console.error(err);
} finally {
active--;
}
});
bot.login(process.env.DISCORD_TOKEN);
The regular expression strips the bot mention from the message. The active counter is a plain guard that keeps the bot below the full-key limit of 8 concurrent requests, and well below the trial limit of 2 if you lower it for testing. A streamed request holds its concurrency slot until the stream ends, so the counter is decreased in finally, after the loop completes.
Why the edits are throttled
Streaming makes a bot feel alive, but Discord rate limits message edits. If you edit on every token you will hit those limits, and discord.js will start queuing and delaying requests. Editing roughly every 1.5 seconds gives smooth text without trouble. The final edit after the loop makes sure the complete answer is shown.
The 1,900-character slice is a safety margin below Discord's 2,000-character message cap. If you want longer answers, send the extra text as follow-up messages instead of one large edit. Alternatively, tell the model in the system prompt to stay within a length and set max_tokens to match.
Streaming also reports token usage at the end of the response, which is handy if you want to log the cost of each conversation. For the full list of supported parameters, temperature, top_p, stop, seed and the penalties among them, see the documentation.
Step 5: Keep it running
A bot started in a terminal dies when you close the terminal. Move it to a small VPS or any always-on machine and run it under a process manager. On Linux, a systemd unit does the job:
[Unit]
Description=AI Discord bot
After=network-online.target
[Service]
WorkingDirectory=/opt/aibot
EnvironmentFile=/opt/aibot/.env
ExecStart=/usr/bin/node index.js
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
Save it as /etc/systemd/system/aibot.service, then run systemctl enable --now aibot. If you prefer something lighter, pm2 start index.js followed by pm2 save does a similar job. Either way, the bot restarts after a crash and after a reboot.
Common problems and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Bot is online but never replies | Message Content intent is off, or the bot lacks permission in the channel | Enable the intent in the portal and in the client options, then check channel permissions |
| HTTP 401 from the API | Wrong key, or an extra space or newline copied with it | Re-copy the key from the API key page and test it with curl first |
| HTTP 429 with code rate_limited | More than the allowed requests per minute | Slow down, queue messages, and let the SDK retry |
| HTTP 429 with code concurrency | Too many requests running at once | Lower your active counter; a streamed request keeps its slot until it ends |
| Reply cut off mid-sentence | max_tokens set too low | Raise it, or remove it, since the completion can use the rest of the window |
| Discord error about message length | Reply longer than 2,000 characters | Slice the text or split it across several messages |
The trial key is stricter than a full key: 2 concurrent requests and 60 per minute, against 8 and 300. If your test server has several people typing at once, expect the occasional busy message until you top up.
Choosing a persona and settings
The system prompt is where a bot gets its character. A sentence such as "You are a dry-witted game master who answers in three sentences or fewer" does more than a paragraph of vague adjectives. Start with a temperature near 0.8 for conversation and lower it to 0.2 or 0.3 for a bot that answers factual questions. Change one setting at a time, so you can tell which change improved the replies.
Safety basics
Never paste the Discord token or the API key into a public repository or a screenshot. If one leaks, reset the Discord token in the portal and rotate the API key on the key page. Keep the bot out of channels where you cannot supervise it, and add a command that lets moderators switch it off quickly.
Cost and next steps
The price is $0.15 per 1M input tokens and $0.50 per 1M output tokens, paid from prepaid credit that never expires. Say your friends server produces 100 replies a day, each with 2,000 input tokens and 400 output tokens. Input is 200,000 tokens, which costs $0.03. Output is 40,000 tokens, which costs $0.02. That is $0.05 a day, or $1.50 over 30 days.
When the trial runs out, top-ups on this site are by crypto (USDT on TRC20, USDC on Base), any whole amount from $20 to $500, with a +5% bonus from $50, +10% from $100 and +15% from $200. See the pricing page for the details.
From here you can add slash commands, per-user memory in a database, or tool calling so the bot can roll dice or look things up. The API supports tool calls and JSON mode in the same OpenAI format. The model is tuned to answer without content refusals for lawful adult use, so keep your server rules in order, and keep sexual content involving minors out entirely. That is a hard limit.
More guides
Questions and answers
Is it free to make an AI Discord bot?
Discord itself is free. The model calls cost money, but the trial credit of $0.50 is enough for hundreds of test replies, and a small bot can cost cents per day afterwards.
Do I need to know how to code?
You need basic JavaScript or Python. The code above is a working starting point, and you only have to set three values: the Discord token, the API key and the bot persona.
Which model name do I use?
Use uncensored as the model ID, with the base URL https://api.unhingedai.cc/v1. The /v1/models endpoint lists what the key can use.
Can I write the bot in Python instead?
Yes. discord.py plus the openai Python package works the same way: set base_url and api_key on the client and call chat.completions.create with model uncensored.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.