How to Build an AI Discord Bot That Answers Questions With Claude

Build an AI Discord bot that answers an /ask slash command with Claude. Setup steps, Node.js code, intents rules, costs and Discord's AI data rule.

By Archit Tamrakar · LinkedIn · · 8 min read

You can build a Discord bot that answers an /ask command with Claude using two small Node.js files and a Claude API key. The bot runs as a Discord app with its own token and reads only slash command input, so it does not need the privileged Message Content intent. Anthropic's TypeScript SDK docs set the minimum at Node.js 20 LTS, so install that version first.

What do you need before you start?

You need a Discord server where you can add apps, Node.js 20 LTS or later, and a Claude API key. Adding a server-installed app requires the Manage Server permission, which Discord's getting-started guide names MANAGE_GUILD. The same guide recommends a test server that other people do not use, and it describes a new server as free to make.

For the API key, go to the API keys page in the Claude Console. Anthropic recommends a service account key for anything shared, since a personal key is tied to one person's account and fails when that person leaves the organization, per its key guide.

How do you create the Discord app and copy its bot token?

Create an app in the Discord Developer Portal, then reset the bot token on the Bot page. Copy the token when it appears, because you cannot view it again later.

  1. Open the Discord Developer Portal and sign in.
  2. Click Create App. Enter a name, then press Create.
  3. On the General Information page, copy the Application ID. You will use it as CLIENT_ID.
  4. Click Bot in the left sidebar.
  5. Under Token, click Reset Token, then copy the new token. You will use it as DISCORD_TOKEN.

Treat the token like a password. The getting-started guide flags it as the credential that authorizes every request your app makes, so it is highly sensitive. Never paste it into a chat, a screenshot, or a public repository. If it leaks, click Reset Token again to regenerate it.

How do you add the bot to your test server?

Set the install scopes on the Installation page, then open the install link and choose your server.

  1. Click Installation in the left sidebar.
  2. Under Install Link, keep Discord Provided Link selected.
  3. Under Default Install Settings, select Guild Install. Add the applications.commands scope and the bot scope.
  4. Choose the bot permissions you need. Discord's sample selects Send Messages.
  5. Copy the install link, open it in your browser, select Add to server, and pick your test server.

How do you connect the bot to Claude in Node.js?

Create a project folder, install two packages, and add two files. One file registers the /ask command with Discord. The other answers the command with Claude.

  1. Open a terminal in a new folder and run the following commands.
npm init -y
npm install discord.js @anthropic-ai/sdk

Verify this step: the discord.js install command was not confirmed against its official install page, so check it there.

  1. Set your three values in the same terminal. On macOS or Linux, run:
export DISCORD_TOKEN="paste-your-bot-token"
export CLIENT_ID="paste-your-application-id"
export ANTHROPIC_API_KEY="sk-ant-paste-your-key"

On Windows PowerShell, set each value with $env:DISCORD_TOKEN = "paste-your-bot-token" and the same pattern for the other two. Verify this step: the PowerShell syntax was not confirmed against an official page, so the command may differ on your system.

  1. Create a file named deploy-commands.js with this code, then run node deploy-commands.js.
const { REST, Routes, SlashCommandBuilder } = require('discord.js');

const commands = [
  new SlashCommandBuilder()
    .setName('ask')
    .setDescription('Ask Claude a question')
    .addStringOption((option) =>
      option.setName('question').setDescription('What do you want to ask?').setRequired(true)
    )
    .toJSON(),
];

const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);

(async () => {
  try {
    await rest.put(Routes.applicationCommands(process.env.CLIENT_ID), { body: commands });
    console.log('Registered the /ask command.');
  } catch (error) {
    console.error(error);
  }
})();
  1. Create a file named index.js with this code, then run node index.js. Keep the terminal open, because the bot is online only while this program runs.
const { Client, Events, GatewayIntentBits } = require('discord.js');
const Anthropic = require('@anthropic-ai/sdk');

const anthropic = new Anthropic(); // reads ANTHROPIC_API_KEY from the environment
const MODEL = 'claude-opus-5-5'; // replace with a model ID from Anthropic's model list

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.once(Events.ClientReady, (readyClient) => {
  console.log(`Logged in as ${readyClient.user.tag}`);
});

client.on(Events.InteractionCreate, async (interaction) => {
  if (!interaction.isChatInputCommand() || interaction.commandName !== 'ask') return;

  await interaction.deferReply();

  try {
    const question = interaction.options.getString('question', true);
    const message = await anthropic.messages.create({
      model: MODEL,
      max_tokens: 500,
      messages: [{ role: 'user', content: question }],
    });

    const reply = message.content
      .filter((block) => block.type === 'text')
      .map((block) => block.text)
      .join('\n');

    await interaction.editReply(reply || 'Claude returned no text.');
  } catch (error) {
    console.error(error);
    await interaction.editReply('The request to Claude failed. Check the bot console for details.');
  }
});

client.login(process.env.DISCORD_TOKEN);
  1. In a server where the bot is installed, type /ask and enter a question.

The code calls deferReply() before it calls Claude. A bot has three seconds to acknowledge an interaction, and the deferred reply leaves 15 minutes for the answer to arrive. The filter that keeps only text blocks follows the pattern in the SDK documentation.

The model line uses claude-opus-5-5, the example ID in the SDK docs. Anthropic's model list changes over time, so replace it with the ID you want before you deploy.

Do you need the Message Content intent for an AI bot?

No, not for a slash command bot. Discord's intents guide advises against the Message Content intent for any app that can run on other inputs. Slash commands are the replacement Discord offers for text commands.

How the bot gets the questionNeeds Message Content?Notes
/ask slash command optionNoDiscord does the argument handling for you
Messages that mention the botNoDiscord lists mentions as an exception
Every message in a channelYesPrivileged. Smaller apps switch it on in the portal

To use a privileged intent, turn it on in the Developer Portal. Below 10,000 users, toggling an intent is enough. Past that point, Discord reviews the request. An app in 100 or more guilds has to go through verification, and each intent needs approval during that step. Sending an intent that has not been approved gets the connection cut off with code 4014.

What's free and what costs money?

Discord's setup steps are covered above, but Claude usage is metered. This table lists each piece as of 21 October 2026.

ItemCostNotes
Discord test serverFree to create, per Discord's guideUse a server nobody else uses for testing
Discord app and bot tokenSet up in the Developer PortalThis guide lists no Discord fee for it
Claude API usageMetered per requestAccording to Tygart Media, the API has no ongoing free tier and charges by the million tokens processed. No rates are listed here
HostingNot coveredThe bot runs while index.js runs on your computer
Gateway limits120 events per 60 seconds; 1,000 Identify calls per 24 hoursDiscord's gateway docs

Each SDK response includes a usage field with its token counts, so you can see what each question consumed. Set spending controls in the Claude Console and confirm what it offers before you open the bot to a large server.

Is this bot allowed under Discord's rules?

Yes, if the bot follows Discord's Developer Policy. The rules that matter most for this bot are these:

  • Keep message content from the API out of AI training unless Discord grants permission (item 21).
  • Limit API data to what the bot's stated purpose needs (item 15).
  • Keep password and login token requests out of your bot's prompts (item 4).
  • Message people privately only when they asked for it (item 5).
  • Keep the bot away from users under 13 (item 9).

Anthropic's docs link to its commercial terms and usage policy. Read them before you send private server content to the API.

What can go wrong, and how do you fix it?

Most setup errors come from a mismatched ID, a missing environment variable, or a slow first response. Use this table to find the fix.

ProblemLikely causeFix
/ask shows no answerThe bot did not acknowledge within three secondsKeep deferReply() as the first call, as the code does
/ask does not appearThe command was never registeredRun node deploy-commands.js again and confirm CLIENT_ID is the Application ID
Claude returns an authentication errorANTHROPIC_API_KEY is missing or wrong in this terminalSet it again in the same terminal and check that the key starts with sk-ant-
The bot disconnects with code 4014A privileged intent is requested but not enabledRemove the intent from the code, or enable it on the Bot page if the bot truly needs it
You suspect the token leakedAnyone with the token can control the botClick Reset Token on the Bot page and update DISCORD_TOKEN
The bot is blocked after many restartsThe Identify limit was reachedStop restart loops. Hitting the limit ends all sessions and resets the token

The Anthropic SDK maps a 401 response to an AuthenticationError, according to its error table. The gateway docs describe what the Identify limit does to a bot, including the token reset.

What's still unclear?

Model names and prices. This post lists no rates. Third-party pricing pages disagree on model names and prices, so check Anthropic's pricing page and model list on the day you deploy.

The verification threshold. Discord's docs tie the approval requirement to 100 or more guilds. A third-party privacy guide says a bot reaching 75 servers goes through verification. This post uses Discord's figure, and you should confirm it in the Developer Portal before you grow the bot.

Long answers. The code sends back whatever Claude returns and does not split long replies. Test with long prompts before you share the bot.

Memory. Each /ask is a separate question, so the bot forgets earlier answers. Adding memory means adding storage, and stored user data brings privacy duties.

The weakest point. The code has no per-user limit and no spending cap. Anyone in the server can trigger a Claude call, so set spending controls in the Claude Console and consider a role check before you open the bot to a large community.

Frequently asked questions

Do I need the Message Content intent to build an AI Discord bot?

No, not for a slash command bot. The /ask command passes the question as an option, so the bot never reads channel messages. Discord's docs advise against requesting the Message Content intent when an app can work another way. Mentions and direct messages also reach a bot without the intent. A bot that reads every channel message does need it, and apps in 100 or more servers need Discord's approval for it.

Is it free to build a Discord bot that uses Claude?

Discord's getting-started guide describes creating a server as free. Claude API use is metered. According to Tygart Media, the API has no ongoing free tier and charges by the million tokens processed. This guide lists no model rates because third-party pricing pages disagree, so check Anthropic's pricing page before you deploy. Hosting the bot on a server is not covered here.

Why does my bot say the interaction failed or did not respond in time?

A bot has three seconds to acknowledge an interaction. Calling deferReply() first shows a placeholder and leaves 15 minutes for the real answer. The code in this guide calls deferReply() before it calls Claude, then uses editReply() to post the answer. If errors persist, read the bot console output, which prints the error from the Claude request.

Where do I get the Claude API key for the bot?

Sign in at platform.claude.com, open the API keys page at platform.claude.com/settings/keys, and select Create key. The key is displayed a single time, so copy it when it appears. Keys start with sk-ant-. If you lose one, create a new key. Store it in an environment variable named ANTHROPIC_API_KEY, which the Anthropic SDK reads automatically.

Can the messages my bot sees be used to train an AI model?

Not without Discord's express permission. Item 21 of Discord's Developer Policy forbids AI training on message content from the APIs unless Discord permits it. The rule targets training, so keep server messages out of any training dataset and use them only to answer the question that was asked.

Which Node.js version does the Claude SDK need?

The Anthropic TypeScript SDK docs set Node.js 20 LTS as the minimum. Install the SDK with npm install @anthropic-ai/sdk. The discord.js library installs in the same project with npm install discord.js. Check the discord.js guide for its own version requirements before you start.

Sources

  1. Building your first Discord Bot, Discord Developer Docs (2026-10-21)
  2. Gateway, Discord Developer Docs (2026-10-21)
  3. You Might Not Need a Privileged Intent, Discord Developer Docs (2026-10-21)
  4. Discord Developer Policy, Discord (2024-07-08)
  5. Gateway Intents, discord.js Guide (2026-10-21)
  6. Command Responses, discord.js Guide (2026-10-21)
  7. Get your Claude API key, Claude Platform Docs (2026-10-21)
  8. TypeScript SDK, Claude Platform Docs (2026-10-21)
  9. Anthropic Console: Login, API Keys & Billing (2026), Tygart Media (2026-10-04)
  10. Privacy Policy for Discord Bots: Complete Guide for Developers (2026), LegalForge (2026-02-10)