claude-code-discord
Health Uyari
- License — License: MIT
- Description — Repository has a description
- Active repo — Last push 0 days ago
- Low visibility — Only 6 GitHub stars
Code Uyari
- network request — Outbound network request in client/src/api.ts
Permissions Gecti
- Permissions — No dangerous permissions requested
Bu listing icin henuz AI raporu yok.
Chat with Claude Code on Discord. Support channel modes (free response or mention-only), threaded messages as claude sessions, allowlist, scheduled watcher jobs
claude-code-discord-coworker
A tiny relay that forwards Discord messages to Claude Code running on your VPS, and sends the agent's response back. Self-hosted, allowlist-gated, no external services beyond Discord and your local CLI.
- Stack: Bun + React (Vite) + Tailwind + Wouter +
bun:sqlite+ discord.js (gateway only) - No vendor SDK for the agent — spawns your local
claudeCLI (inherits its auth) - Session per conversation — each DM, channel, and thread is its own
claude --resumesession; new threads always start fresh, so context stays contained in the thread - Channel response modes — free responses (default: just talk, no mention needed; put
/tanywhere in a message to branch into a thread), mention → thread (Hermes-style: @mention the bot, it replies in a new thread), or ignore — per channel, from the dashboard - Allowlist — only approved Discord users can drive the agent; the person who completes onboarding becomes the owner
- Commands both ways — plain text (
/stop,/new_session, …) and native slash commands with autocomplete and ephemeral replies - Model & effort switch — pick the Claude model (
fable/opus/sonnet/haikuor any full id) and reasoning effort from the dashboard or/model//effort - Agent Discord tools — the agent can search members, read channels, send messages, create threads, and react via
bin/discord("mention Andi and tell him…") - Capabilities page — read-only inventory of what the host's Claude Code can reach: MCP servers with live health, skills (project, personal, plugin), and installed plugins
- Memories page — what Claude Code remembers on the host: its auto-saved memories for the relay's project, the instruction files (CLAUDE.md / AGENTS.md / rules) it reads every run, and memory folders of other projects
- Scheduled jobs — ask the agent to "watch X and alert me in #channel" and it writes a watcher script and registers it on a cron schedule with that channel as the delivery target; no billed agent turn per check (see
/jobs, the dashboard card, and docs/scheduled-jobs.md) - Background tasks — long work (builds, renders, uploads) runs through
bin/bg: it outlives the turn that started it, reports its own outcome to the conversation, and can be listed, stopped and restarted safely from a later turn (see docs/background-tasks.md) - Gateway is outbound-only — the bot opens a WebSocket to Discord; nothing connects inbound to your machine, so it works behind NAT/VPN/private hosts (exe.dev, Tailscale) with no open ports
Quick start on exe.dev (recommended)
The easiest way to run the relay is on an exe.dev VM: its
image already ships the claude CLI, every VM gets a publichttps://<vm-name>.exe.xyz domain, and you set it up by describing what you
want — an agent on the VM does the install. Sign up with this invite link:
https://exe.dev/i/rlOEOFDH72EMS2A
- Go to https://exe.dev/new, copy the prompt from
exe-dev-setup-prompt.md, and paste it into the
Describe your VM box. (Prefer the terminal? That file also has anssh exe.dev new … --prompt=/dev/stdincommand and the recommended specs.) - Open the new VM and go to its Shelley menu to watch the agent work: it
clones this repo, builds it, starts the relay under pm2 on port 8100, and
replies there with the dashboard URL. - Open that URL and finish onboarding in the browser — sign in to Claude Code
(subscription or API key), then create your Discord bot and paste its
token. No terminal login at any point.
The dashboard has no authentication of its own, but you don't need to add
any: exe.dev's proxy requires an exe.dev login by default, so only you can open
that URL. Just don't share set-public this VM (see Security).
Prefer your own server? Follow VPS setup with pm2
instead.
Prerequisites
- Bun
>= 1.3.12 - Claude Code installed on the machine that runs the relay — install;
claude --versionmust work. You can authenticate it from the dashboard during onboarding (see Authentication), so it only needs to be on PATH. python3— only for Claude's in-dashboard subscription sign-in (it drives a PTY).bin/installinstalls it; skip if you authenticate Claude another way.- The
pty-oauth-loginagent skill — lets Claude finish OAuth sign-ins (MCP servers etc.) from a Discord chat.bin/installinstalls it; by hand:npx skills add terryds/skills --skill pty-oauth-login -g - A Discord application + bot — created in the Discord Developer Portal (onboarding walks you through it, ~2 minutes).
Local development
bun install
bun run dev
This launches the server (port 8100, hot-reload) and Vite (port 5173, proxying /api to the server). Open http://localhost:5173.
You'll be sent to /onboarding:
- Authenticate Claude Code. The page verifies the CLI is installed, then checks whether it's signed in. If not, pick Subscription (sign in straight from the dashboard — no terminal) or API key (paste a key; it's stored and injected when the relay runs). See Authentication.
- Create your Discord bot. Follow the steps on the page:
- Developer Portal → New Application → name it → Create.
- Bot tab → under Privileged Gateway Intents, toggle ON Message Content Intent and Server Members Intent → Save. (Skipping Message Content Intent is the #1 cause of a bot that connects but never answers.)
- Reset Token → copy (shown once) → paste into the dashboard.
- The dashboard then shows a generated invite link (right scopes and permissions pre-filled) — open it, pick your server, Authorize. No server yet? Create one first; it can be just you and the bot.
- Say hi. Click Start listening, then send the bot any message (in the server, or a DM). The first message links you as the owner — the first entry of the allowlist — and the bot replies with a welcome.
After that you're on the dashboard: channel modes, allowlist, model/effort, persona, bookmarks, scheduled jobs, auth, updates, and a live activity feed.
Channels, modes, and threads
Every guild text channel has a response mode — a per-channel override or the global default (out of the box: free):
- Free responses (default) — the bot answers every allowlisted user's message inline, no mention needed. Put
/t(or/thread) anywhere in a message, as its own word, and the bot instead creates a thread from it and answers there, with a fresh session — great for branching off a side-task without polluting the channel conversation. The/threadslash command does the same from any channel, whatever its mode: the bot echoes your request as the thread's starter message and answers inside. - Mention → thread — the bot only reacts when you @mention it; it creates a thread from your message (named after its first words) and replies inside, again with a fresh session. Messages that mention someone else (not the bot) are left alone.
- Ignored — the bot never responds in the channel.
Regardless of mode: DMs always answer, and once the bot is in a thread it keeps answering there without a mention. Each DM / channel / thread is its own conversation with its own Claude session — contexts don't bleed. Conversations run concurrently; within one conversation it's one task at a time (a new message auto-stops that conversation's current run; prefix it with /queue to run it after the current task instead). Careful with two conversations editing the same project simultaneously — the relay doesn't referee file conflicts.
Every message reaching the agent is prefixed with its Discord context (sender username + id, channel + id, server, thread) so the agent knows who and where it's talking to — and can act on those ids with bin/discord.
Allowlist
Only allowlisted users can talk to the bot; everyone else is silently ignored. The onboarding user is the owner (can't be removed). Add more people from the dashboard's Allowed users card: enable Developer Mode in Discord (Settings → Advanced), right-click a user → Copy User ID, paste it in.
⚠️ Every allowlisted user can drive a shell-capable agent on your machine — see Security.
Authentication
The relay spawns your local claude CLI, so that CLI has to be authenticated. Onboarding (and the dashboard's auth panel) detect this and offer two methods, switchable anytime:
- Subscription — sign in with your Claude plan from the dashboard, no terminal: it drives
claude auth login(this is whypython3is needed — it runs the CLI in a PTY). Click Sign in with Claude and authorize in your browser; the CLI detects completion on its own (pasting the code the page shows is a fallback). This signs in the host'sclaudeitself, so the CLI also works outside the relay. - API key — paste an Anthropic key. It's stored in
data/app.dband injected asANTHROPIC_API_KEYwhen the relay runs (pay-per-token API billing, not your subscription).
Detection is cheap — claude auth status, no model call. You can also authenticate the CLI yourself on the host (claude auth login) and the relay will pick it up.
When the sign-in expires
A subscription login has two lifetimes: the access token renews itself every few hours, but the refresh token has a hard expiry (a few weeks, not extended by use). Past it, every run fails with "OAuth session expired and could not be refreshed" until someone signs in again — that's Claude Code's behaviour, not the relay's, and there is no headless way to renew it. The relay makes that a non-event instead of a surprise:
- The dashboard's status is kept truthful by real runs. Every Discord turn writes its outcome back: a completed turn confirms the sign-in, an auth failure flips it to signed out with the error — no need to press Check now (which, being
claude auth status, can't tell a dead token from a live one anyway; the relay also reads the credential's own expiry so a lapsed login reads as signed out even there). - The strip at the top of the dashboard shows "valid until " when healthy and becomes a banner with a Sign in again button when the login is about to lapse or already has.
- The owner gets a DM ahead of time: 3 days before expiry, the day before, and when it lapses — each once, with a direct link to the dashboard's auth section (
…/#auth). A failed run says the same thing instead of the raw CLI error. The link needs a reachable dashboard address (hostname -forDASHBOARD_URL). The check reads only the credential's timestamps (macOS keychain or~/.claude/.credentials.json), hourly, with noclaudecall.
If a re-login every few weeks is still too much, claude setup-token mints a ~1-year token the relay can inject — at the cost of only covering relay-spawned runs, not plain claude on the host.
Adding MCP servers, connectors and skills
The dashboard's Capabilities page lists what the host's Claude Code can reach — MCP servers with live health, skills, plugins. It's read-only on purpose: you add things by asking over Discord, no SSH needed.
- Connectors on your Claude account (Google Drive, Gmail, Notion, Canva…) are connected once in Claude Desktop / claude.ai → Settings → Connectors and follow your account, so this host gets them automatically. They appear as
claude.ai …servers. - MCP servers on this machine — ask Claude, e.g. "Add the Notion MCP server at https://mcp.notion.com/mcp and sign me in". Claude runs
claude mcp add, and for OAuth uses thepty-oauth-loginskill: it drives the login under a PTY, sends you the authorize link, you open it on your device and paste back the code or the redirect URL you land on (alocalhost:…URL is expected), and Claude completes the sign-in. "Sign in to the posthog MCP server" uses the same flow for servers already configured. - Skills — "Install the frontend-design skill from anthropics/skills". Claude installs it via the skills.sh CLI into
~/.claude/skills. Plugins: "Install the posthog plugin from the official marketplace".
The Memories page shows what Claude remembers across conversations: auto-saved memories for the relay's project, the instruction files it reads every run, and other projects' memory folders on the host. Tell Claude "remember that …" or "forget …" to change them.
Production build
bun run build # builds the client into dist/client/
bun start # starts the server on PORT (default 8100), serving API + client
The single Bun process serves /api/*, the static React build, and the Discord gateway connection on one port. Override with PORT=8080 bun start.
VPS setup with pm2
The manual path for your own server. (On exe.dev, use the
quick start instead — the agent does
all of this for you.) These steps assume Ubuntu/Debian. Adjust paths as needed.
1. Install dependencies
bin/install # installs anything missing (Ubuntu/Debian, uses sudo)
bin/doctor # read-only: report what's present / missing
bin/install is idempotent and does not touch the Claude CLI — install it yourself (npm install -g @anthropic-ai/claude-code, or see the docs). You don't have to log it in here: authentication can be done from the dashboard during onboarding.
2. Clone and build
cd ~
git clone https://github.com/terryds/claude-code-discord.git claude-code-discord
cd claude-code-discord
bun install
bun run build
3. Start under pm2
cd ~/claude-code-discord
PORT=8100 pm2 start server/index.ts \
--name claude-code-discord-coworker \
--interpreter "$(which bun)" \
--max-restarts 10 \
--restart-delay 3000
pm2 save
pm2 startup # follow the printed instruction to enable on boot
pm2 save snapshots the env that was current at start time, so PORT persists across pm2 resurrect and reboots. If you change an env var later, restart with pm2 restart claude-code-discord-coworker --update-env.
4. Expose the dashboard
The dashboard has no authentication — it's intended to sit behind something:
- An SSH tunnel (
ssh -L 8100:localhost:8100 your-vps) — simplest, no public exposure - A private overlay network (Tailscale, exe.dev private mode) — the relay itself needs no inbound port for Discord, so this works fully
- A reverse proxy with HTTP basic auth if you must expose it publicly
5. Onboard
Visit the dashboard, complete the three onboarding steps, and you're live. Message your bot — it reaches Claude Code on the VPS and replies.
Updating
cd ~/claude-code-discord
git pull
bun install # if dependencies changed
bin/install # picks up new requirements (e.g. required agent skills); idempotent
bun run build # rebuild the client
pm2 restart claude-code-discord-coworker
bin/safe-update-relay (what /update and the dashboard's Update button run) does all of this for you, including installing any missing required skill.
Your bot token, owner link, allowlist, channel modes, and sessions live in data/app.db — they survive restarts and code updates.
Updating from Discord
If you ask the relayed agent itself to update the project, a plain pm2 restart kills the process hosting the conversation mid-reply. The repo ships bin/safe-update-relay: it detaches, delays briefly, runs git pull → bun install (if deps changed) → bun run build → pm2 restart, waits for the process to come back online, and DMs you the result. A failed pull/build aborts before the restart. The /update command and the dashboard's Updates card both use it.
setsid nohup ~/claude-code-discord/bin/safe-update-relay >/dev/null 2>&1 < /dev/null &
Config via env vars: RELAY_PROCESS_NAME (default claude-code-discord-coworker), RELAY_REPO_DIR (default: the repo the script lives in).
Commands
Available both as plain text and as native slash commands (registered per-guild, so they appear instantly):
/help— show usage/thread <message>— ask in a new thread with a fresh session (guild channels only; the slash form works regardless of the channel's response mode; as plain text,/tis a shorthand)/stop— interrupt the agent (kills that conversation's in-flight run and discards its queue)/queue <message>— run a message after the current task finishes instead of replacing it;/queuealone lists the queue,/queue clearempties it/new_session— fresh conversation here (other channels/threads keep their context)/model— show or set the Claude model (fable,opus,sonnet,haiku, or a full id;defaultclears)/effort— show or set reasoning effort (low…max)/persona— show or customize the assistant persona/skills— list the agent skills available on this host/jobs— list scheduled watcher jobs/update— pull the latest relay version, rebuild, restart
Slash-command replies are ephemeral (only you see them), except /thread, whose echo of your request is public — it's the message the thread hangs off. Text commands answer in place.
Interrupting a run
The agent streams its progress (thinking, tool calls, results) into the conversation as it works, and the gateway keeps receiving the whole time. Send /stop to cancel that conversation's run, or just send a new prompt — it auto-stops the running task and starts the new one (anything queued with /queue is discarded too). Stopping is a hard process kill: file edits already made stay on disk, and the conversation keeps everything up to the moment of the stop, so Claude knows what it was doing — but the rest of the task is dropped, so ask again. (Exception: if the very first message of a new conversation is stopped, the next message starts fresh.)
To not interrupt, prefix the message with /queue (or use the /queue slash command with a message): it's held until the current task (and anything queued before it) finishes, then runs as a normal follow-up turn in the same session. Works with attachments too — put /queue … in the message text. /queue on its own lists what's waiting, /queue clear drops it, and /stop stops the running task and clears the queue. Queues are per conversation and in-memory — a relay restart (e.g. /update) drops them. /queue into an idle conversation just runs the message immediately.
Step message cleanup
To keep channels readable, those streamed step messages are auto-deleted 1 minute after they're posted (the final reply always stays). Change the delay — or set it to Never to keep every step — under Step messages in the dashboard. Deletions are queued in the database, so pending cleanups survive a relay restart.
Host memory guard and app previews
A relay that spawns claude -p on a starved VM looks exactly like a dead bot: the process starts but crawls, HTTP calls time out, nothing comes back. Two guards keep that from happening silently:
- Before every run the relay reads available memory (Linux
MemAvailable). BelowLOW_MEMORY_MB(default512) it posts a warning to the conversation naming the heaviest pm2 processes (at most once per 15 min per channel) and prepends the same facts to the agent's prompt, so the agent cleans up instead of guessing why its tools are slow. The run is never blocked — the message asking for the cleanup must get through. SetLOW_MEMORY_MB=0to disable. bin/previewis how the agent starts throwaway servers (PR previews, demos) under pm2: deterministicpreview-<name>names so a re-deploy restarts instead of adding a sibling, a TTL (default 3 days), a pm2 memory cap (default 512M), and a refusal to start when memory is low orPREVIEW_MAX(default 4) previews are already running.bin/preview list,stop <name>,gc(reap expired;--allfor everything) andcheck(memory only; exit 2 when low) round it out. The registry lives indata/previews.json.AGENTS.mdtells the agent to use it instead of barepm2 start, and to bookmark only durable apps.
Background tasks (bin/bg)
A relay run is one-shot — a Bash call is capped at 5 minutes and a new message kills the run in progress — so the agent starts long work in the background and manages it from later turns. bin/bg is how it does both:
bin/bg start ep12-render --cwd ~/video --channel <id> -- bash render.sh ep12
bin/bg list | status <name> | logs <name>
bin/bg stop <name> | restart <name>
- Every task has a name and a record (
data/bg/<name>/: command, log, how it ended), solistandstatussay what is running, what finished, and what failed with which exit code. A task whose supervisor vanished (host reboot, OOM kill) is detected and reported as lost rather than left looking alive. - The task reports its own outcome to the channel it was started for — success or failure, with the exit status and the last log lines — through
bin/notify, so it also reaches the agent's next turn as context. A task the agent stopped reports nothing. - Stop and restart act on the whole task. It runs in its own process group under a small supervisor;
stopsignals that recorded group and any descendants that left it (SIGTERM, then SIGKILL afterBG_STOP_GRACE, default 10 s) — never a name pattern, so it cannot hit the agent's own run or leave half a task carrying on. It refuses to run from inside the task it would kill. - Shell scripts run from a frozen copy, so the agent editing a script cannot corrupt a task that is executing it;
restartapplies the edit. Scripts that read their own location, or are named inside a quoted command line, run in place and are flagged as such. - Before each run the relay tells the agent what is running (name, age, where it reports, scripts not to edit), plus any outcome that could not be delivered to Discord.
Related hardening: the relay hands the prompt to claude -p on stdin, not as an argument. A process's arguments are what pkill -f matches, so with the prompt in argv a pattern kill for any word in the user's message would also match — and kill — the agent's own run.
AGENTS.md tells the agent to use bin/bg instead of nohup/pkill; the full contract is in docs/background-tasks.md.
Attachments
Images, audio, video, and any other file you attach are downloaded to data/incoming/<attachment_id>-<name> and the local path (plus MIME type) is appended to the prompt — Claude reads images/text/PDFs with its Read tool and handles the rest with its own tools (ffmpeg, transcription, …). Discord's standard 25 MB upload limit applies. Files are not auto-deleted — wipe data/incoming/ periodically if you don't want them around.
Notification gateway (POST /api/notify)
Other apps on the same host can push Discord alerts through the relay
instead of carrying their own bot credentials:
curl -s -X POST http://127.0.0.1:8100/api/notify \
-H 'Content-Type: application/json' \
-d '{"text": "**2 drafts ready**", "source": "myapp",
"kind": "draft digest", "context": "2 drafts ready: …"}'
text(required) — the message;source(required) — who sent it, labels
it in the dashboard feed ([myapp] …).kind(optional) — what kind of alert it is (e.g."draft digest","deploy status"); shown alongside the source in the feed and in the
agent's FYI list, so the agent knows who triggered the alert and what
it's about.channel_id(optional) — deliver to a specific channel/thread instead of
the owner's DM. The agent-context note is queued for that conversation.format—"md"(Discord-native Markdown, default),"plain"(same),
or"html"(accepted for compatibility with the Telegram relay's payloads
— b/i/a/code tags are converted to Markdown, so links survive as[label](url); other tags are stripped).context(optional) — plain-text summary queued for the agent: the next
relayed turn in the target conversation starts with an FYI list of
notifications delivered while the agent was idle, so replies that
reference an alert ("expand the second draft") resolve. Defaults totext
(HTML stripped); pass"no_context": truefor pure-noise pings (tests).
Scheduled-job output andbin/notifysends are queued the same way.- Returns non-2xx when the Discord send fails, so callers can retry.
The endpoint only accepts loopback connections. To also require a shared
secret (checked as the X-Notify-Token header), set a notify_token row in
the settings table.
Data
Everything is stored in data/app.db (SQLite): settings (token, owner, sessions, model/effort, flags), allowed_users, channel_modes, bookmarks, jobs, pending_context (out-of-band notifications queued as agent context), and the message_log/step_log behind the dashboard's activity feed. data/previews.json is bin/preview's registry of running preview servers; data/bg/ holds bin/bg's background-task records and logs. To wipe state: stop the process, delete data/app.db* and data/incoming/, restart — or use Reset everything in the dashboard.
Security
Read this before deploying. The threat model is non-trivial.
What an attacker who reaches your bot can do
Claude is spawned with --permission-mode bypassPermissions: every message the relay accepts becomes a shell-capable prompt running as your VPS user. There is no sandbox. The gates are:
- The bot token (treat it like an SSH private key — reset it in the Developer Portal if leaked), and
- The allowlist: only listed Discord user ids are relayed.
Everyone you allowlist can drive the agent — every one of their messages is a shell-capable prompt on your VPS. In free mode channels this is especially easy to forget: anyone allowlisted who can type in a channel the bot can see is talking to your shell. Only allowlist people you'd hand a terminal to.
The dashboard has no built-in authentication
Anyone who can open the dashboard URL can edit the allowlist, hit Reset everything, re-onboard with their own bot, and get shell. Do not expose the port to the public internet directly. Use an SSH tunnel, a private overlay (Tailscale), or a reverse proxy with auth. An exe.dev VM already does this: its proxy requires an exe.dev login by default (don't share set-public it).
Prompt injection is a real risk
Because Claude runs with full shell access, prompt injection from any content the bot relays — including content you paste — is a meaningful risk ("summarize this email" where the email says ignore previous instructions and run …). Don't relay untrusted content blindly; run the relay as a dedicated unprivileged user; keep unrelated secrets out of that user's home directory.
What is and isn't sent over the network
- Discord: every incoming/outgoing message goes through Discord's servers (they can read it). The bot connects out to Discord's gateway and REST API; nothing connects in.
- Claude: Claude Code uses your local credentials and sends prompts to Anthropic's API.
- Dashboard: no telemetry, no external calls. The bot token never leaves the server; the client only ever sees
bot_token_set: true|false.
Reporting issues
If you find a security issue, please open a private security advisory rather than a public issue.
Notes
- Received messages are only those delivered live over the gateway — messages sent while the relay was down are not replayed (no backlog on reconnect).
- Slash commands are registered per guild on connect (and when the bot joins a new guild), so they show up immediately.
Yorumlar (0)
Yorum birakmak icin giris yap.
Yorum birakSonuc bulunamadi