← Blog

Claude API Discord Bot Tutorial: Build Yours Today

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

If you're searching for a Claude API Discord bot tutorial, you want working code: a bot that listens for messages or slash commands, sends them to Claude, and posts the response back in a channel. This article walks through exactly that, using Node.js and discord.js, with a working example you can copy and run in under 30 minutes.

The short version: you need a Discord bot token, a Claude API key, and about 60 lines of JavaScript. The rest of this guide covers the setup, the code, how to handle Discord's message length and rate limits, and how to keep latency low with streaming.

What You Need Before Starting

Step 1: Set Up the Discord Bot Skeleton

Create a basic bot that logs in and responds to a slash command:

import { Client, GatewayIntentBits, SlashCommandBuilder, REST, Routes } from "discord.js";

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

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

client.login(process.env.DISCORD_TOKEN);

Register a /ask slash command so users can talk to Claude without needing special permissions or mentioning the bot:

const command = new SlashCommandBuilder()
  .setName("ask")
  .setDescription("Ask Claude a question")
  .addStringOption(option =>
    option.setName("prompt").setDescription("Your question").setRequired(true)
  );

const rest = new REST({ version: "10" }).setToken(process.env.DISCORD_TOKEN);
await rest.put(
  Routes.applicationGuildCommands(process.env.CLIENT_ID, process.env.GUILD_ID),
  { body: [command.toJSON()] }
);

Step 2: Call the Claude API

This is where most tutorials get messy because they mix in SDK-specific auth, model versioning, and streaming boilerplate. Using a plain HTTPS endpoint keeps it simple. Here's a call to SubToAPI's Claude-compatible endpoint:

async function askClaude(prompt) {
  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",
      max_tokens: 1024,
      messages: [{ role: "user", content: prompt }]
    })
  });

  const data = await res.json();
  return data.content[0].text;
}

This same request shape works whether you're calling the Anthropic API directly or through a proxy — see the messages API docs for the full request and response schema. If you haven't set up a key yet, sign up for a free trial and grab a sub_live_ key from the dashboard.

Step 3: Wire It Together

Now connect the slash command to the Claude call:

client.on("interactionCreate", async (interaction) => {
  if (!interaction.isChatInputCommand() || interaction.commandName !== "ask") return;

  await interaction.deferReply(); // Discord gives you 3 seconds, Claude can take longer

  const prompt = interaction.options.getString("prompt");

  try {
    const reply = await askClaude(prompt);
    await interaction.editReply(reply.slice(0, 2000)); // Discord's message limit
  } catch (err) {
    await interaction.editReply("Something went wrong talking to Claude.");
  }
});

Two details matter here:

  1. deferReply() is required. Discord interactions time out after 3 seconds, and a Claude response rarely comes back that fast. Deferring buys you up to 15 minutes.
  2. Discord messages cap at 2000 characters. Long Claude responses need to be split into multiple messages or truncated — use interaction.followUp() in a loop if you want to send the full answer in chunks.

Step 4: Handle Long Responses with Streaming

If your bot needs to feel responsive for longer answers, stream the response and edit the Discord message incrementally instead of waiting for the full completion. SubToAPI supports streaming the same way the native Claude API does — see the streaming docs for event format details.

async function askClaudeStreaming(prompt, onChunk) {
  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",
      max_tokens: 1024,
      stream: true,
      messages: [{ role: "user", content: prompt }]
    })
  });

  const reader = res.body.getReader();
  const decoder = new TextDecoder();
  let buffer = "";

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value);
    const lines = buffer.split("\n").filter(l => l.startsWith("data:"));
    for (const line of lines) {
      const json = JSON.parse(line.replace("data: ", ""));
      if (json.delta?.text) onChunk(json.delta.text);
    }
  }
}

In practice, don't edit the Discord message on every token — Discord rate-limits message edits aggressively. Batch chunks and edit every 1–2 seconds instead.

Step 5: Handle Multi-User Context and Abuse

A few things production bots need that tutorials usually skip:

Step 6: Deploy

Run the bot as a long-lived process — a small VPS, a container on Fly.io or Railway, or a serverless function if your framework supports persistent WebSocket connections (note: standard serverless functions don't support Discord's gateway connection well; you need a process that stays online).

Minimum environment variables:

DISCORD_TOKEN=your-discord-bot-token
CLIENT_ID=your-discord-application-id
GUILD_ID=your-test-server-id
SUBTOAPI_KEY=sub_live_...

For a broader walkthrough of authentication and endpoint structure outside the Discord context, check the quickstart guide.

questions

Do I need Anthropic's official SDK to build a Discord bot with Claude? No. Claude's API is a standard HTTPS JSON endpoint, so fetch or axios works fine. The SDK just wraps the same requests shown above.

How do I avoid hitting Discord's 2000-character message limit? Either truncate the response, split it across multiple followUp() messages, or ask Claude to keep answers concise using a system prompt with a target length.

Can one Claude API key support a bot running in multiple Discord servers? Yes — the key isn't tied to a specific server. Just watch total token usage across all servers so you don't exceed your plan's throughput, and consider per-user rate limiting to prevent one busy server from starving the others.

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 →