// 注册 Chatwoot AgentBot:把 bridge 接成官方 AI(对标企业版 Captain)。 // 1. 创建 AgentBot(name + outgoing_url 指向 bridge 的 /agent-bot) // 2. 关联到 website inbox(set_agent_bot) // 3. 打印 secret(用于 bridge 的 HMAC 签名校验,设到 AGENT_BOT_SECRET 环境变量) // // 运行: node register_agent_bot.js // 幂等:已存在同名 bot 则复用并更新 outgoing_url。 const fs = require('fs'); const path = require('path'); const cw = JSON.parse(fs.readFileSync(path.join(__dirname, 'chatwoot.config.json'), 'utf8')); const BOT_NAME = 'Yehwang AI Bridge'; // Chatwoot 容器经 host.docker.internal 访问宿主上的 bridge;本地直连用 localhost const OUTGOING_URL = process.env.AGENT_BOT_OUTGOING_URL || 'http://host.docker.internal:4000/agent-bot'; const headers = () => ({ 'api_access_token': cw.accessToken, 'Content-Type': 'application/json' }); const apiBase = `${cw.baseURL}/api/v1/accounts/${cw.accountId}`; async function main() { // 1. 列出现有 agent_bots,找同名复用 const listResp = await fetch(`${apiBase}/agent_bots`, { headers: headers() }); const listData = await listResp.json(); const existing = (listData.payload || listData || []).find((b) => b.name === BOT_NAME); let bot = existing; const payload = { name: BOT_NAME, description: 'AI sales+service bridge (RAG + tool-use)', outgoing_url: OUTGOING_URL, bot_type: 'webhook' }; if (existing) { const r = await fetch(`${apiBase}/agent_bots/${existing.id}`, { method: 'PATCH', headers: headers(), body: JSON.stringify(payload) }); bot = await r.json(); console.log(`[update] 复用 AgentBot #${existing.id}`); } else { const r = await fetch(`${apiBase}/agent_bots`, { method: 'POST', headers: headers(), body: JSON.stringify(payload) }); bot = await r.json(); console.log(`[create] 新建 AgentBot #${bot.id}`); } console.log(' bot:', JSON.stringify({ id: bot.id, name: bot.name, outgoing_url: bot.outgoing_url, secret: bot.secret })); // 2. 关联到 inbox(set_agent_bot) const inboxId = cw.inboxId; const setResp = await fetch(`${apiBase}/inboxes/${inboxId}/set_agent_bot`, { method: 'POST', headers: headers(), body: JSON.stringify({ agent_bot: bot.id }), }); console.log(`[inbox] 关联 inbox ${inboxId} -> ${setResp.status} ${setResp.ok ? 'OK' : 'FAIL'}`); // 3. 打印要配置的环境变量 console.log('\n=== 配置 bridge 容器环境变量 ==='); console.log(`AGENT_BOT_SECRET=${bot.secret}`); console.log('(写入 docker-compose.yml bridge.environment 或 .env,然后 docker compose up -d bridge)'); console.log('\nChatwoot 后台「Inbox → 设置 → Bot」应能看到该 AgentBot 已关联。'); } main().catch((e) => { console.error('ERR', e.message); process.exit(1); });