summaryrefslogtreecommitdiff
path: root/external_plugins/discord
diff options
context:
space:
mode:
Diffstat (limited to 'external_plugins/discord')
-rw-r--r--external_plugins/discord/README.md4
-rw-r--r--external_plugins/discord/server.ts45
2 files changed, 42 insertions, 7 deletions
diff --git a/external_plugins/discord/README.md b/external_plugins/discord/README.md
index 3cbdf2b8..ad04f6fa 100644
--- a/external_plugins/discord/README.md
+++ b/external_plugins/discord/README.md
@@ -55,7 +55,9 @@ Install the plugin:
/discord:configure MTIz...
```
-Writes `DISCORD_BOT_TOKEN=...` to `.claude/channels/discord/.env` in your project. You can also write that file by hand, or set the variable in your shell environment — shell takes precedence.
+Writes `DISCORD_BOT_TOKEN=...` to `~/.claude/channels/discord/.env`. You can also write that file by hand, or set the variable in your shell environment — shell takes precedence.
+
+> To run multiple bots on one machine (different tokens, separate allowlists), point `DISCORD_STATE_DIR` at a different directory per instance.
**6. Relaunch with the channel flag.**
diff --git a/external_plugins/discord/server.ts b/external_plugins/discord/server.ts
index 078c29ab..927ef978 100644
--- a/external_plugins/discord/server.ts
+++ b/external_plugins/discord/server.ts
@@ -29,7 +29,7 @@ import { readFileSync, writeFileSync, mkdirSync, readdirSync, rmSync, statSync,
import { homedir } from 'os'
import { join, sep } from 'path'
-const STATE_DIR = join(homedir(), '.claude', 'channels', 'discord')
+const STATE_DIR = process.env.DISCORD_STATE_DIR ?? join(homedir(), '.claude', 'channels', 'discord')
const ACCESS_FILE = join(STATE_DIR, 'access.json')
const APPROVED_DIR = join(STATE_DIR, 'approved')
const ENV_FILE = join(STATE_DIR, '.env')
@@ -58,6 +58,15 @@ if (!TOKEN) {
}
const INBOX_DIR = join(STATE_DIR, 'inbox')
+// Last-resort safety net — without these the process dies silently on any
+// unhandled promise rejection. With them it logs and keeps serving tools.
+process.on('unhandledRejection', err => {
+ process.stderr.write(`discord channel: unhandled rejection: ${err}\n`)
+})
+process.on('uncaughtException', err => {
+ process.stderr.write(`discord channel: uncaught exception: ${err}\n`)
+})
+
const client = new Client({
intents: [
GatewayIntentBits.DirectMessages,
@@ -342,7 +351,7 @@ function checkApprovals(): void {
}
}
-if (!STATIC) setInterval(checkApprovals, 5000)
+if (!STATIC) setInterval(checkApprovals, 5000).unref()
// Discord caps messages at 2000 chars (hard limit — larger sends reject).
// Split long replies, preferring paragraph boundaries when chunkMode is
@@ -423,7 +432,7 @@ const mcp = new Server(
'',
'Messages from Discord arrive as <channel source="discord" chat_id="..." message_id="..." user="..." ts="...">. If the tag has attachment_count, the attachments attribute lists name/type/size — call download_attachment(chat_id, message_id) to fetch them. Reply with the reply tool — pass chat_id back. Use reply_to (set to a message_id) only when replying to an earlier message; the latest message doesn\'t need a quote-reply, omit reply_to for normal responses.',
'',
- 'reply accepts file paths (files: ["/abs/path.png"]) for attachments. Use react to add emoji reactions, and edit_message to update a message you previously sent (e.g. progress → result).',
+ 'reply accepts file paths (files: ["/abs/path.png"]) for attachments. Use react to add emoji reactions, and edit_message for interim progress updates. Edits don\'t trigger push notifications — when a long task completes, send a new reply so the user\'s device pings.',
'',
"fetch_messages pulls real Discord history. Discord's search API isn't available to bots — if the user asks you to find an old message, fetch more history or ask them roughly when it was.",
'',
@@ -471,7 +480,7 @@ mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
},
{
name: 'edit_message',
- description: 'Edit a message the bot previously sent. Useful for progress updates (send "working…" then edit to the result).',
+ description: 'Edit a message the bot previously sent. Useful for interim progress updates. Edits don\'t trigger push notifications — send a new reply when a long task completes so the user\'s device pings.',
inputSchema: {
type: 'object',
properties: {
@@ -637,6 +646,25 @@ mcp.setRequestHandler(CallToolRequestSchema, async req => {
await mcp.connect(new StdioServerTransport())
+// When Claude Code closes the MCP connection, stdin gets EOF. Without this
+// the gateway stays connected as a zombie holding resources.
+let shuttingDown = false
+function shutdown(): void {
+ if (shuttingDown) return
+ shuttingDown = true
+ process.stderr.write('discord channel: shutting down\n')
+ setTimeout(() => process.exit(0), 2000)
+ void Promise.resolve(client.destroy()).finally(() => process.exit(0))
+}
+process.stdin.on('end', shutdown)
+process.stdin.on('close', shutdown)
+process.on('SIGTERM', shutdown)
+process.on('SIGINT', shutdown)
+
+client.on('error', err => {
+ process.stderr.write(`discord channel: client error: ${err}\n`)
+})
+
client.on('messageCreate', msg => {
if (msg.author.bot) return
handleInbound(msg).catch(e => process.stderr.write(`discord: handleInbound failed: ${e}\n`))
@@ -685,7 +713,7 @@ async function handleInbound(msg: Message): Promise<void> {
// forgeable by any allowlisted sender typing that string.
const content = msg.content || (atts.length > 0 ? '(attachment)' : '')
- void mcp.notification({
+ mcp.notification({
method: 'notifications/claude/channel',
params: {
content,
@@ -698,6 +726,8 @@ async function handleInbound(msg: Message): Promise<void> {
...(atts.length > 0 ? { attachment_count: String(atts.length), attachments: atts.join('; ') } : {}),
},
},
+ }).catch(err => {
+ process.stderr.write(`discord channel: failed to deliver inbound to Claude: ${err}\n`)
})
}
@@ -705,4 +735,7 @@ client.once('ready', c => {
process.stderr.write(`discord channel: gateway connected as ${c.user.tag}\n`)
})
-await client.login(TOKEN)
+client.login(TOKEN).catch(err => {
+ process.stderr.write(`discord channel: login failed: ${err}\n`)
+ process.exit(1)
+})