Claude API Discord Bot: Complete Guide (2026)

typescript dev.to

Originally published at claudeguide.io/claude-api-discord-bot-guide

Claude API Discord Bot: Complete Guide (2026)

To build a Discord bot powered by Claude API, install discord.js v14 and @anthropic-ai/sdk, register slash commands with the Discord REST API, then handle interactions by forwarding user messages to anthropic.messages.create() and replying with the response. The full setup takes about 30 minutes. This guide covers slash commands, message event handlers, per-user conversation context, rate limiting per server and user, and deployment with PM2 or Docker.


discord.js v14 Setup

Initialize a new project and install dependencies:

mkdir claude-discord-bot && cd claude-discord-bot
npm init -y
npm install discord.js @anthropic-ai/sdk dotenv
npm install -D typescript ts-node @types/node
npx tsc --init
Enter fullscreen mode Exit fullscreen mode

Create a .env file:

DISCORD_TOKEN=your-bot-token
DISCORD_CLIENT_ID=your-application-client-id
ANTHROPIC_API_KEY=sk-ant-...
Enter fullscreen mode Exit fullscreen mode

Create src/index.ts — the bot entry point:

import { Client, GatewayIntentBits, Partials } from "discord.js";
import * as dotenv from "dotenv";
import { registerCommands } from "./commands/register";
import { handleInteraction } from "./handlers/interaction";
import { handleMessage } from "./handlers/message";

dotenv.config();

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.DirectMessages,
  ],
  partials: [Partials.Channel],
});

client.once("ready", async () =

---

## Rate Limiting Per Server and User

Protect your API budget with a token-bucket rate limiter:

Enter fullscreen mode Exit fullscreen mode


typescript
// src/ratelimit/limiter.ts

interface Bucket {
tokens: number;
lastRefill: number;
}

// Per-user: 5 requests per minute
// Per-guild: 30 requests per minute
const USER_LIMIT = 5;
const GUILD_LIMIT = 30;
const REFILL_INTERVAL_MS = 60_000;

const userBuckets = new Map<string, Bucket


Frequently Asked Questions

What Discord bot permissions do I need to enable Claude API integration?

In the Discord Developer Portal, enable the Message Content Intent under Bot settings — this is required to read message content when the bot is mentioned. For slash commands only, you do not need message content intent. Grant the bot Send Messages, Read Message History, and Use Application Commands permissions when inviting to a server.

How do I prevent my bot from running up a large API bill?

Implement rate limiting per user and per guild before calling the Claude API (see the limiter example above). Set a max_tokens cap (1024 is usually enough for Discord replies). Use Claude Haiku for most requests — it costs 10x less than Sonnet for comparable quality on conversational tasks. Set a monthly budget alert in the Anthropic Console.

Can I store conversation history in a database instead of memory?

Yes. Replace the in-memory Map in src/context/store.ts with database calls. Use a conversations table keyed by userId, storing the history as a JSON column. PostgreSQL, SQLite (via better-sqlite3), or Redis all work well. Database-backed context survives bot restarts and works across multiple bot instances.

How do I handle Discord's 2000-character message limit with Claude responses?

Set a hard limit in your system prompt ("Never exceed 1900 characters") and truncate defensively in code before sending. For longer responses, split the text at sentence boundaries and send as multiple messages using message.reply() followed by message.channel.send(). Alternatively, send a follow-up embed or file attachment for very long output.

Should I use claude-haiku or claude-sonnet for a Discord bot?

Start with claude-haiku-4-5 for all requests. Haiku handles conversational Q&A, code snippets, and explanations well at 1/10 the cost of Sonnet. Upgrade to claude-sonnet-4-5 only if your use case requires complex reasoning, long document analysis, or nuanced writing. For model selection guidance, see Claude Haiku vs Sonnet vs Opus: Which Model.

Source: dev.to

arrow_back Back to Tutorials