Claude API Discord Bot: A Python Tutorial
What this tutorial covers
If you're searching for how to build a Claude API Discord bot in Python, you want a working bot that listens to messages, sends them to Claude, and replies in the channel — without blocking the bot's event loop or hitting rate limits the first week it's live. This guide walks through exactly that: project setup, the discord.py event handler, async API calls, streaming responses, and deployment considerations that trip up most first-time bot builders.
The short version: you'll use discord.py for the Discord side, an async HTTP client (or an official SDK) for the Claude side, and you'll keep the two completely non-blocking so your bot stays responsive under load. Below is the full build, step by step.
Project setup
Install the two libraries you need:
pip install discord.py httpx python-dotenv
Create a .env file to keep secrets out of your code:
DISCORD_TOKEN=your-discord-bot-token
CLAUDE_API_KEY=your-api-key
If you're calling Claude directly through Anthropic's API, you'll need a provisioned account with billing set up before you can make requests. If you want to skip that step entirely and just reuse your existing Claude access, a service like SubToAPI issues a standard HTTPS API key (sub_live_...) that works with the same request/response shape, so the bot code below needs zero changes either way — just swap the base URL and key.
The basic bot skeleton
import os
import discord
from dotenv import load_dotenv
load_dotenv()
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f"Logged in as {client.user}")
@client.event
async def on_message(message):
if message.author == client.user:
return
if not message.content.startswith("!ask "):
return
prompt = message.content[len("!ask "):]
reply = await ask_claude(prompt)
await message.channel.send(reply)
client.run(os.getenv("DISCORD_TOKEN"))
This is the entire Discord-facing layer. Users type !ask <question>, and the bot replies in the same channel. The only missing piece is ask_claude.
Calling the Claude API asynchronously
The critical mistake in most Claude API Discord bot tutorials is using a blocking HTTP client (plain requests) inside on_message. That freezes the bot's entire event loop — every other server, every other message, stalls until the API call finishes. Use httpx.AsyncClient instead:
import httpx
import os
API_URL = "https://api.subtoapi.app/v1/messages"
API_KEY = os.getenv("CLAUDE_API_KEY")
async def ask_claude(prompt: str) -> str:
async with httpx.AsyncClient(timeout=60.0) as http:
response = await http.post(
API_URL,
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
},
json={
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": prompt}],
},
)
response.raise_for_status()
data = response.json()
return data["content"][0]["text"]
Swap the API_URL for Anthropic's endpoint if you're calling them directly — the request shape is the same. This is the full request/response cycle: see the messages docs for the complete payload reference if you're using SubToAPI as your backend.
Handling long responses and Discord's message limit
Discord caps messages at 2000 characters. Claude will happily return more than that, so chunk it:
async def send_long_message(channel, text: str):
for i in range(0, len(text), 1900):
await channel.send(text[i:i + 1900])
Replace await message.channel.send(reply) with await send_long_message(message.channel, reply) in the handler above.
Adding streaming for a better UX
Waiting several seconds for a full response feels sluggish in a chat context. Streaming lets you edit a single Discord message as tokens arrive, which feels far more responsive:
async def ask_claude_streaming(message, prompt: str):
sent = await message.channel.send("Thinking…")
buffer = ""
async with httpx.AsyncClient(timeout=120.0) as http:
async with http.stream(
"POST",
API_URL,
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"stream": True,
"messages": [{"role": "user", "content": prompt}],
},
) as response:
async for line in response.aiter_lines():
if line.startswith("data: "):
buffer += parse_delta(line)
if len(buffer) % 200 < 20:
await sent.edit(content=buffer[:1900])
await sent.edit(content=buffer[:1900])
You'll need a small parse_delta helper to extract text from each SSE event — the exact event names are covered in the streaming docs. In practice, editing on every token hits Discord's own rate limits on message edits, so batch edits every few hundred characters as shown above.
Keeping conversation context per channel
A bot that forgets everything after each message feels broken. Keep a simple in-memory history per channel (or per user) and pass it as the messages array:
history = {}
async def ask_claude_with_memory(channel_id: int, prompt: str) -> str:
convo = history.setdefault(channel_id, [])
convo.append({"role": "user", "content": prompt})
reply_text = await ask_claude_messages(convo)
convo.append({"role": "assistant", "content": reply_text})
history[channel_id] = convo[-20:] # cap history length
return reply_text
This is intentionally simple — for production bots you'll want persistence (Redis or a database) so history survives restarts, and a token-budget check so long conversations don't exceed context limits.
Adding tool use for real commands
If you want the bot to do more than chat — look up server stats, query a database, moderate content — Claude's tool use feature lets the model call functions you define and get structured results back. The request format and schema requirements are detailed in the tools docs; the Discord integration is just wiring the tool's return value back into the conversation history before sending the final reply.
Rate limits and running multiple bots
Discord bots tend to spike in bursts — a raid of questions in a busy server, or a bot added to several servers at once. Hitting your Claude account's rate limit mid-conversation produces a visible error in Discord, which looks bad to users. If you're running this bot for a community or a client, SubToAPI plans give each team member or bot instance its own sub_live_ key with separate usage tracking, so you can see exactly which bot or server is driving load without digging through raw Anthropic logs. Setup takes about five minutes — see the quickstart — and there's a free trial if you want to test the bot before committing to a plan, starting from Solo at €9 or Team seats at €19 via signup.
questions
Do I need discord.py or can I use another library? discord.py is the most mature async Discord library for Python and works cleanly with async HTTP clients like httpx. Nextcord and Pycord are drop-in forks with the same API if you need an actively maintained alternative.
Why does my bot freeze when multiple users message it at once? You're almost certainly using a blocking HTTP call inside on_message. Switch to httpx.AsyncClient (or any async-compatible client) so the Discord event loop keeps processing other messages while a Claude request is in flight.
How do I stop the bot from exceeding Discord's 2000-character message limit? Chunk the response into slices of under 2000 characters (1900 is a safe margin) and send them as separate messages, or truncate and offer a "read more" follow-up for very long replies.