← Blog

Claude API Discord Bot Tutorial: Build One Step by Step

2026-11-17 · 5 min read · SubToAPI Team

If you're looking for a working example of a Discord bot powered by Claude, this tutorial walks through the whole thing: setting up the bot, wiring it to the Claude API, handling messages without hitting rate limits, and deploying it so it stays online. By the end you'll have a bot that responds in channels and DMs, keeps conversation context per-user, and streams replies instead of making people wait for a wall of text.

The core pattern is simple: Discord.js listens for messages, forwards the text to Claude, and edits a placeholder message as the response streams back. The tricky parts are managing conversation history, avoiding duplicate replies, and not blowing through your API rate limits when ten people talk to the bot at once. We'll cover all three.

Prerequisites

Install dependencies:

npm install discord.js node-fetch

Step 1: Basic bot skeleton

import { Client, GatewayIntentBits, Partials } from "discord.js";

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

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

client.login(process.env.DISCORD_TOKEN);

Make sure "Message Content Intent" is enabled in the bot's settings in the Developer Portal, or message.content will come back empty.

Step 2: Calling the Claude API

This example uses SubToAPI's endpoint, which mirrors the standard Messages format so you don't have to change your request shape if you ever switch providers:

async function askClaude(messages) {
  const res = await fetch("https://api.subtoapi.app/v1/messages", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "claude-sonnet-4-5",
      max_tokens: 1024,
      system: "You are a helpful, concise Discord bot. Keep replies under 1800 characters.",
      messages,
    }),
  });
  const data = await res.json();
  return data.content[0].text;
}

That system prompt matters: Discord caps messages at 2000 characters, so telling Claude to stay concise avoids truncation or needing a message-splitting function.

Step 3: Handling messages and keeping context

Each user should get their own conversation history, otherwise replies will blend between unrelated users. A simple in-memory map works for small bots; for anything production-grade, swap it for Redis or a database.

const histories = new Map();

client.on("messageCreate", async (message) => {
  if (message.author.bot) return;
  if (!message.mentions.has(client.user) && message.channel.type !== 1) return;

  const userId = message.author.id;
  const history = histories.get(userId) || [];
  const content = message.content.replace(/<@!?\d+>/g, "").trim();

  history.push({ role: "user", content });

  await message.channel.sendTyping();

  try {
    const reply = await askClaude(history);
    history.push({ role: "assistant", content: reply });
    histories.set(userId, history.slice(-10)); // keep last 10 turns
    await message.reply(reply.slice(0, 2000));
  } catch (err) {
    console.error(err);
    await message.reply("Something went wrong talking to Claude. Try again in a moment.");
  }
});

The .slice(-10) trims history so you don't send an ever-growing context window on every request — that keeps both latency and token costs predictable.

Step 4: Streaming for a better user experience

Waiting several seconds for a full response feels sluggish in a chat app. Streaming the reply and editing a message as tokens arrive makes the bot feel responsive. SubToAPI supports streaming the same way the standard Messages API does — see /docs/streaming for the full event format. In Discord, you edit a sent message on an interval instead of on every token, since Discord's edit rate limits are tight:

async function streamReply(message, messages) {
  const placeholder = await message.reply("…");
  let buffer = "";
  let lastEdit = Date.now();

  const res = await fetch("https://api.subtoapi.app/v1/messages", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "claude-sonnet-4-5",
      max_tokens: 1024,
      stream: true,
      messages,
    }),
  });

  for await (const chunk of res.body) {
    const lines = chunk.toString().split("\n").filter(Boolean);
    for (const line of lines) {
      if (!line.startsWith("data:")) continue;
      const parsed = JSON.parse(line.replace("data: ", ""));
      if (parsed.type === "content_block_delta") {
        buffer += parsed.delta.text;
        if (Date.now() - lastEdit > 900) {
          await placeholder.edit(buffer.slice(0, 2000));
          lastEdit = Date.now();
        }
      }
    }
  }
  await placeholder.edit(buffer.slice(0, 2000));
  return buffer;
}

Editing roughly once per second avoids Discord's per-message edit rate limit while still feeling live.

Step 5: Rate limits and concurrency

If your bot gets used in a busy server, multiple messages can arrive at once. Queue requests per channel or per user instead of firing them all in parallel — this protects you from API rate limits and from burning through your plan's quota unevenly. SubToAPI's dashboard shows usage per API key, which is useful if you run multiple bots or environments (staging vs. production) and want to see which one is consuming the most tokens. Pricing is per seat, starting at the Solo plan on /pricing, with a free trial at /signup.

Step 6: Deployment

For always-on hosting, a small VPS, Fly.io, or Railway instance running the Node process with a process manager (pm2 or a systemd service) is enough for most community bots. Store DISCORD_TOKEN and your API key as environment variables, never in code. Restart on crash, and log errors to a file or logging service so you can debug silent failures.

Putting it together

A minimal but solid Claude-powered Discord bot needs: an intents-configured client, a per-user history store, a call to the Messages endpoint (see /docs/messages for the full request/response shape), and either a simple reply or a streamed one. Start with the simple version, confirm it works end-to-end, then add streaming and tool use (if your bot needs to look things up or run commands — see /docs/tools) once the basics are stable. The /docs/quickstart page covers authentication and key setup if you're starting from scratch.

questions

Do I need Anthropic's SDK, or can I just use fetch/curl? Plain HTTP requests work fine — the Messages API is a standard JSON POST endpoint, so fetch in Node or curl for testing is all you need. An SDK just saves boilerplate.

How do I stop the bot from responding to every message in a channel? Only call Claude when the bot is mentioned or messaged in a DM, as shown in the messageCreate handler above. Responding to every message in a busy channel will spam users and burn through your quota fast.

Can one bot serve multiple Discord servers without separate API keys? Yes — a single API key can serve all servers your bot is in. Use per-user or per-channel history keys so conversations don't mix, and monitor total usage in your provider's dashboard to catch unexpected spikes.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →