← Blog

Claude API Discord Bot Integration Guide

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

Building a Discord bot that talks to Claude means wiring three pieces together: the Discord Gateway (for receiving messages and slash commands), your bot's backend logic, and an HTTPS call to a Claude-compatible API. The integration itself isn't complicated — the tricky parts are message length limits, response latency inside Discord's interaction windows, and keeping API keys secure across a team of bot maintainers.

This guide walks through a working setup using Node.js and discord.js, including how to handle Discord's 2000-character message cap, how to simulate streaming via message edits, and how to structure your code so multiple developers can ship changes without sharing a single raw API key.

Architecture overview

A Claude-powered Discord bot typically has this flow:

  1. User sends a message or triggers a slash command.
  2. Your bot process receives the event via the Discord Gateway (WebSocket).
  3. Your backend sends the prompt to the Claude API.
  4. The response comes back (streamed or not) and your bot posts/edits a Discord message with the result.

Because Discord interactions have strict response-time windows (3 seconds for the initial ack, 15 minutes for follow-ups), you need to defer the interaction immediately and then edit it once the model finishes.

Setting up the bot shell

Install the basics:

npm install discord.js dotenv

Minimal bot skeleton with a /ask slash command:

import { Client, GatewayIntentBits, SlashCommandBuilder } from "discord.js";
import "dotenv/config";

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

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

  await interaction.deferReply(); // buys you time beyond the 3s window

  const prompt = interaction.options.getString("prompt");
  const reply = await askClaude(prompt);

  await interaction.editReply(truncate(reply));
});

client.login(process.env.DISCORD_TOKEN);

Register the command separately via Discord's REST API or the discord.js deploy script — that part is identical for any bot and not specific to Claude.

Calling the API

For the askClaude function, you need an endpoint, an API key, and a payload shape. If you're using SubToAPI as the HTTPS layer on top of your Claude access, the call looks like this:

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: 800,
      messages: [{ role: "user", content: prompt }],
    }),
  });

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

The relevant docs for the request/response shape are at /docs/messages if you want the full field reference, and /docs/quickstart covers getting your first sub_live_... key.

Handling Discord's message length limit

Discord caps a single message at 2000 characters. Claude responses for detailed questions will frequently exceed that. Two options:

Split into multiple messages:

function chunkMessage(text, size = 1900) {
  const chunks = [];
  for (let i = 0; i < text.length; i += size) {
    chunks.push(text.slice(i, i + size));
  }
  return chunks;
}

for (const chunk of chunkMessage(reply)) {
  await interaction.followUp(chunk);
}

Or send as a file when the output is code, logs, or anything long and structured:

await interaction.editReply({
  content: "Here's the full response:",
  files: [{ attachment: Buffer.from(reply), name: "response.txt" }],
});

For most Q&A bots, chunking is friendlier for readers; for code generation or long reports, a file attachment keeps the channel clean.

Simulating streaming with message edits

Discord doesn't support token-by-token streaming in the UI, but you can approximate the effect by editing a message as tokens arrive from a streaming endpoint. This matters for perceived latency — a bot that shows "thinking..." then dumps a wall of text feels slower than one that visibly fills in.

async function streamToDiscord(interaction, 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: 800,
      stream: true,
      messages: [{ role: "user", content: prompt }],
    }),
  });

  let buffer = "";
  let lastEdit = Date.now();

  for await (const chunk of res.body) {
    buffer += parseDelta(chunk);
    if (Date.now() - lastEdit > 700) {
      await interaction.editReply(truncate(buffer));
      lastEdit = Date.now();
    }
  }

  await interaction.editReply(truncate(buffer));
}

Throttle edits to roughly once per second — Discord rate-limits message edits per channel, and editing on every token will get you throttled fast. See /docs/streaming for the server-sent event format.

Tool use inside Discord commands

If your bot needs to look things up (search a knowledge base, hit an internal API, run a calculation) before answering, Claude's tool-use feature fits naturally into a slash command handler: the model requests a tool call, your bot executes it server-side, and you send the result back in a follow-up request before posting the final answer to Discord. The request/response contract for this is documented at /docs/tools.

Key management for team-maintained bots

A Discord bot is usually maintained by more than one person, and it's easy for the Claude/Claude-proxy API key to end up hardcoded in a .env file that gets copied around Discord DMs or shared drives. If several developers touch the bot, give each one (or each environment — staging vs production) its own application key with usage visibility, rather than one shared secret. SubToAPI issues separate sub_live_... keys per app/environment under one billing account, with team seats on the Team and Scale plans, so you can rotate or revoke a single developer's access without taking the bot offline. Check /pricing for seat and plan details.

Rate limits and error handling

Discord bots can generate bursty traffic — a popular server might fire a dozen /ask commands in a few seconds. Wrap your API call with basic retry logic for 429s and 5xx responses, and fail gracefully in the Discord reply rather than leaving the interaction hanging:

try {
  const reply = await askClaude(prompt);
  await interaction.editReply(truncate(reply));
} catch (err) {
  await interaction.editReply("Something went wrong generating a response. Try again in a moment.");
}

Log failures with enough context (prompt length, model, timestamp) to debug later, but avoid logging full user prompts if your server has privacy-sensitive channels.

Questions

Does Claude support true token streaming in Discord messages? No — Discord's UI doesn't render partial message edits as a live stream. You can approximate it by editing the message periodically as tokens arrive, throttled to avoid Discord's edit rate limits.

How do I handle responses longer than Discord's 2000-character limit? Split the text into chunks and send them as follow-up messages, or attach the full response as a .txt file when the content is long-form or code.

Should each bot environment have its own API key? Yes — separate keys for development, staging, and production (and per developer, if your team is larger) make it easy to track usage and revoke access without affecting the live bot.

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 →