Claude API Slack Bot: Build Tutorial
What you're building
A Claude-powered Slack bot listens for mentions or direct messages, sends the text to Claude, and posts the reply back into the channel. This tutorial walks through the full stack: creating the Slack app, wiring up the Events API, calling Claude from a small backend, and handling the quirks that trip people up — threading, Slack's 3-second ack window, and streaming responses.
You need three things before starting: a Slack workspace where you can install apps, a backend you can deploy (Node.js in the examples below, but any language works), and API access to Claude. You can call Anthropic directly, or use SubToAPI to get an HTTPS API key (sub_live_...) with streaming, usage metadata, and a single dashboard if you're already managing Claude access for a team — either way the integration code is nearly identical.
Architecture overview
The flow is simple:
- Slack sends an event (mention, DM, or slash command) to your backend via a webhook.
- Your backend acknowledges the event within 3 seconds (Slack requirement).
- Your backend calls Claude with the message content.
- Your backend posts Claude's reply back to Slack using the
chat.postMessageAPI.
Because Claude responses can take a few seconds, you must ack Slack's event immediately and do the Claude call asynchronously — otherwise Slack will retry the event and you'll get duplicate replies.
Step 1: Create the Slack app
- Go to api.slack.com/apps and create a new app "from scratch."
- Under OAuth & Permissions, add these bot token scopes:
chat:writeapp_mentions:readim:history(if you want DMs)
- Install the app to your workspace and copy the Bot User OAuth Token (
xoxb-...). - Under Event Subscriptions, enable events and point the Request URL at your backend endpoint (e.g.
https://yourapp.com/slack/events). Subscribe toapp_mentionandmessage.im.
Slack will send a verification challenge to your endpoint the first time you save this — your handler needs to echo back the challenge field.
Step 2: Set up the event handler
import express from "express";
import { WebClient } from "@slack/web-api";
const app = express();
app.use(express.json());
const slack = new WebClient(process.env.SLACK_BOT_TOKEN);
app.post("/slack/events", async (req, res) => {
const { type, challenge, event } = req.body;
if (type === "url_verification") {
return res.json({ challenge });
}
// Ack immediately, process async
res.sendStatus(200);
if (event?.type === "app_mention" || event?.type === "message") {
handleMessage(event).catch(console.error);
}
});
app.listen(3000);
The res.sendStatus(200) before any slow work is the part people miss most often. If Claude takes 4 seconds to respond and you wait before acking, Slack retries the event and you get two bot replies.
Step 3: Call Claude and reply
This is where you plug in Claude. Strip the bot mention (<@U12345>) from the text, send it to Claude, and post the result.
async function handleMessage(event) {
const text = event.text.replace(/<@[^>]+>/, "").trim();
const response = 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: text }]
})
});
const data = await response.json();
const reply = data.content[0].text;
await slack.chat.postMessage({
channel: event.channel,
thread_ts: event.ts, // reply in-thread
text: reply
});
}
If you'd rather call Anthropic directly, swap the endpoint and headers — the request shape is the same. SubToAPI's /v1/messages endpoint mirrors the standard Messages API, so this code doesn't need to change if you're already using Anthropic's SDK format. Full request/response details are in the Messages docs.
Step 4: Keep conversations in context
Slack threads are a natural place to maintain conversation history. Store the Slack thread_ts as a key and append each new message/reply pair to an array before sending it back to Claude:
const history = conversations.get(thread_ts) || [];
history.push({ role: "user", content: text });
// send full history to Claude, then push the assistant reply too
history.push({ role: "assistant", content: reply });
conversations.set(thread_ts, history);
For anything beyond a demo, back this with Redis or a database instead of an in-memory Map — process restarts will wipe conversation state otherwise.
Step 5: Stream for long replies (optional)
Slack doesn't support token-by-token streaming in a single message the way a chat UI does, but you can simulate progressive updates by editing the message with chat.update every second or two while tokens arrive. If you're building something closer to a real-time assistant UI, standard server-sent-event streaming (see streaming docs) is still the right approach for the Claude call itself — you just batch the output before pushing updates to Slack.
Step 6: Add tool use for real actions
A Slack bot that only answers questions is useful; one that can look up a ticket, create a Jira issue, or query your database is more useful. Claude's tool use lets you define functions the model can call, and you execute them server-side before returning the result to Claude for a final answer. This is covered in the tool use docs — the pattern plugs directly into the handleMessage function above: check data.stop_reason === "tool_use", execute the matching function, and send the result back in a follow-up request.
Step 7: Deploy and handle rate limits
Deploy the backend anywhere that accepts webhooks (Vercel, Fly.io, a plain VPS). A few production details:
- Retries: wrap the Claude call in a retry with backoff for transient errors.
- Rate limits: if multiple team members mention the bot at once, queue requests rather than firing them all in parallel.
- Keys: don't hardcode tokens. Use environment variables for both the Slack bot token and your Claude API key.
If several people on your team are building Slack bots or internal tools against Claude, giving everyone individual API keys under one billing account — rather than sharing a single key — avoids a lot of operational headaches. SubToAPI's pricing covers Solo, Team, and Scale plans with per-seat keys and usage tracking, and there's a free trial from signup if you want to test this setup before committing.
Quick start checklist
- [ ] Slack app created with
chat:writeandapp_mentions:readscopes - [ ] Event Subscriptions pointed at your backend, verified
- [ ] Backend acks within 3 seconds, processes Claude call async
- [ ] Claude API key configured (see quickstart)
- [ ] Conversation history stored per thread
- [ ] Deployed with retry/backoff logic for rate limits
Questions
Do I need Socket Mode instead of Events API? Socket Mode avoids exposing a public webhook URL, which is convenient for local development or firewalled environments. For production, a standard HTTPS endpoint with Events API is usually simpler to deploy and debug.
Why does my bot sometimes reply twice? This almost always means you're acking the Slack event after calling Claude instead of before. Slack retries events that aren't acknowledged within 3 seconds — ack immediately, then process asynchronously.
Can the bot handle slash commands as well as mentions? Yes. Slash commands use a separate Slack endpoint and payload format, but the Claude call and reply logic are identical — you're just parsing a different request body before calling the model.