|
| 1 | +/** |
| 2 | + * n8n-claw Discord Bridge |
| 3 | + * |
| 4 | + * Connects to Discord's Gateway as a bot, forwards incoming channel messages |
| 5 | + * to n8n's webhook adapter, and exposes a /reply endpoint so n8n can send |
| 6 | + * replies back through the same bot (no duplicate bot token in n8n). |
| 7 | + * |
| 8 | + * Enabled only when COMPOSE_PROFILES=discord and DISCORD_BOT_TOKEN is set. |
| 9 | + */ |
| 10 | + |
| 11 | +const express = require('express'); |
| 12 | +const { Client, GatewayIntentBits, ChannelType } = require('discord.js'); |
| 13 | + |
| 14 | +const BOT_TOKEN = process.env.DISCORD_BOT_TOKEN; |
| 15 | +const N8N_WEBHOOK_URL = process.env.N8N_WEBHOOK_URL || 'http://n8n:5678/webhook/adapter'; |
| 16 | +const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET || ''; |
| 17 | +const BRIDGE_PORT = parseInt(process.env.BRIDGE_PORT || '3300', 10); |
| 18 | + |
| 19 | +if (!BOT_TOKEN) { |
| 20 | + console.error('[discord-bridge] DISCORD_BOT_TOKEN not set — exiting'); |
| 21 | + process.exit(1); |
| 22 | +} |
| 23 | + |
| 24 | +const client = new Client({ |
| 25 | + intents: [ |
| 26 | + GatewayIntentBits.Guilds, |
| 27 | + GatewayIntentBits.GuildMessages, |
| 28 | + GatewayIntentBits.MessageContent, |
| 29 | + GatewayIntentBits.DirectMessages, |
| 30 | + ], |
| 31 | +}); |
| 32 | + |
| 33 | +const recentIds = new Map(); |
| 34 | +setInterval(() => { |
| 35 | + const cutoff = Date.now() - 30000; |
| 36 | + for (const [id, ts] of recentIds) if (ts < cutoff) recentIds.delete(id); |
| 37 | +}, 30000); |
| 38 | + |
| 39 | +client.once('ready', () => { |
| 40 | + console.log(`[discord-bridge] logged in as ${client.user.tag}`); |
| 41 | +}); |
| 42 | + |
| 43 | +client.on('messageCreate', async (message) => { |
| 44 | + if (message.author.bot) return; |
| 45 | + if (message.webhookId) return; |
| 46 | + if (!message.content || !message.content.trim()) return; |
| 47 | + if (recentIds.has(message.id)) return; |
| 48 | + recentIds.set(message.id, Date.now()); |
| 49 | + |
| 50 | + try { |
| 51 | + const resp = await fetch(N8N_WEBHOOK_URL, { |
| 52 | + method: 'POST', |
| 53 | + headers: { |
| 54 | + 'Content-Type': 'application/json', |
| 55 | + 'X-API-Key': WEBHOOK_SECRET, |
| 56 | + }, |
| 57 | + body: JSON.stringify({ |
| 58 | + message: message.content, |
| 59 | + user_id: message.author.id, |
| 60 | + session_id: `discord:${message.channel.id}`, |
| 61 | + source: 'discord', |
| 62 | + metadata: { |
| 63 | + _responseChannel: 'discord', |
| 64 | + channelId: message.channel.id, |
| 65 | + messageId: message.id, |
| 66 | + guildId: message.guild ? message.guild.id : null, |
| 67 | + authorName: message.author.username, |
| 68 | + }, |
| 69 | + }), |
| 70 | + }); |
| 71 | + if (!resp.ok) { |
| 72 | + console.error(`[discord-bridge] n8n returned ${resp.status}`); |
| 73 | + } |
| 74 | + } catch (e) { |
| 75 | + console.error(`[discord-bridge] forward error: ${e.message}`); |
| 76 | + } |
| 77 | +}); |
| 78 | + |
| 79 | +client.on('error', (e) => console.error(`[discord-bridge] client error: ${e.message}`)); |
| 80 | + |
| 81 | +client.login(BOT_TOKEN).catch((e) => { |
| 82 | + console.error(`[discord-bridge] login failed: ${e.message}`); |
| 83 | + process.exit(1); |
| 84 | +}); |
| 85 | + |
| 86 | +const app = express(); |
| 87 | +app.use(express.json({ limit: '1mb' })); |
| 88 | + |
| 89 | +app.post('/reply', async (req, res) => { |
| 90 | + const { channelId, content } = req.body || {}; |
| 91 | + if (!channelId || typeof content !== 'string') { |
| 92 | + return res.status(400).json({ error: 'channelId + content (string) required' }); |
| 93 | + } |
| 94 | + try { |
| 95 | + const channel = await client.channels.fetch(channelId); |
| 96 | + if (!channel || !channel.isTextBased || !channel.isTextBased()) { |
| 97 | + return res.status(404).json({ error: 'channel not found or not text-based' }); |
| 98 | + } |
| 99 | + const chunks = []; |
| 100 | + for (let i = 0; i < content.length; i += 1900) chunks.push(content.slice(i, i + 1900)); |
| 101 | + if (chunks.length === 0) chunks.push(''); |
| 102 | + for (const chunk of chunks) await channel.send(chunk); |
| 103 | + return res.json({ ok: true, chunks: chunks.length }); |
| 104 | + } catch (e) { |
| 105 | + console.error(`[discord-bridge] reply error: ${e.message}`); |
| 106 | + return res.status(500).json({ error: e.message }); |
| 107 | + } |
| 108 | +}); |
| 109 | + |
| 110 | +app.get('/health', (_req, res) => { |
| 111 | + res.json({ ok: client.isReady(), bot: client.user ? client.user.tag : null }); |
| 112 | +}); |
| 113 | + |
| 114 | +app.listen(BRIDGE_PORT, () => { |
| 115 | + console.log(`[discord-bridge] http listening on :${BRIDGE_PORT}`); |
| 116 | +}); |
0 commit comments