-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
223 lines (182 loc) · 6.79 KB
/
index.js
File metadata and controls
223 lines (182 loc) · 6.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
require('dotenv').config();
const { Client, GatewayIntentBits, Events } = require('discord.js');
const express = require('express');
const db = require('./db');
const { queryAgent } = require('./openclaw');
const telegram = require('./telegram');
const {
isOnCooldown,
markReplied,
randomGreeting,
shouldEscalate,
typingDelay,
sanitizeReply,
} = require('./utils');
const HELP_FORUM_CHANNEL_ID = process.env.HELP_FORUM_CHANNEL_ID;
const PORT = process.env.PORT || 3000;
// ── Discord Client ──────────────────────────────────────────────────────────
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
// ── Health Server ───────────────────────────────────────────────────────────
const app = express();
app.get('/health', (_req, res) => res.send('OK'));
// ── Helpers ─────────────────────────────────────────────────────────────────
function isHelpThread(channel) {
return channel.isThread() && channel.parentId === HELP_FORUM_CHANNEL_ID;
}
async function getThreadHistory(thread, limit = 10) {
const messages = await thread.messages.fetch({ limit });
return [...messages.values()]
.reverse()
.map((m) => ({
author: m.author.bot ? 'bot' : m.author.username,
content: m.content,
}));
}
async function handleMessage(message) {
// Ignore bots
if (message.author.bot) return;
// Must be in a help forum thread
const thread = message.channel;
if (!isHelpThread(thread)) return;
// Ignore very short messages
if (message.content.trim().length < 5) return;
// Anti-spam: 60s cooldown per thread
if (isOnCooldown(thread.id)) {
console.log(`[Bot] Cooldown active for thread ${thread.id}, skipping`);
return;
}
console.log(`[Bot] Processing message in thread ${thread.id}`);
try {
// Show typing indicator
await thread.sendTyping();
// Gather context
const [threadHistory, knowledgeSnippets] = await Promise.all([
getThreadHistory(thread),
db.searchKnowledge(message.content),
]);
// Call OpenClaw
const aiResponse = await queryAgent({
question: message.content,
threadHistory,
knowledgeSnippets,
});
// Human-like delay
await typingDelay();
const cleanAnswer = sanitizeReply(aiResponse.final_answer);
// Decide: escalate or reply directly
if (shouldEscalate(aiResponse, message.content)) {
console.log(`[Bot] Escalating thread ${thread.id} (confidence: ${aiResponse.confidence})`);
// Send placeholder to user
await thread.send(
'Got this — checking internally to give you the right answer \u{1F64F}'
);
// Send escalation to Telegram
await telegram.sendEscalation({
threadId: thread.id,
userQuestion: message.content,
botDraft: cleanAnswer,
missingInfo: aiResponse.escalation_question_for_aarav,
});
// Store escalation
await db.createEscalation(thread.id);
} else {
// Direct reply with a greeting
const greeting = randomGreeting();
await thread.send(`${greeting} ${cleanAnswer}`);
}
// Update tracking
markReplied(thread.id);
await db.upsertThread(thread.id, message.id);
} catch (err) {
console.error(`[Bot] Error handling message in ${thread.id}:`, err.message);
// If OpenClaw is down, escalate gracefully
if (!isOnCooldown(thread.id)) {
try {
await thread.send(
'Got this — checking internally to give you the right answer \u{1F64F}'
);
await telegram.sendEscalation({
threadId: thread.id,
userQuestion: message.content,
botDraft: '[OpenClaw unreachable]',
missingInfo: 'Bot failed to generate a response — needs manual reply.',
});
await db.createEscalation(thread.id);
markReplied(thread.id);
} catch (fallbackErr) {
console.error('[Bot] Fallback escalation failed:', fallbackErr.message);
}
}
}
}
// ── Events ──────────────────────────────────────────────────────────────────
client.on(Events.ThreadCreate, async (thread) => {
if (!isHelpThread(thread)) return;
console.log(`[Bot] New help thread created: ${thread.id}`);
// Wait for the first message to arrive
try {
const starter = await thread.fetchStarterMessage();
if (starter && !starter.author.bot) {
await handleMessage(starter);
}
} catch (err) {
console.error(`[Bot] Error handling new thread ${thread.id}:`, err.message);
}
});
client.on(Events.MessageCreate, async (message) => {
await handleMessage(message);
});
client.once(Events.ClientReady, () => {
console.log(`[Bot] Logged in as ${client.user.tag}`);
});
// ── Startup ─────────────────────────────────────────────────────────────────
async function start() {
// Validate env
const required = [
'DISCORD_TOKEN',
'TELEGRAM_TOKEN',
'TELEGRAM_CHAT_ID',
'OPENCLAW_URL',
'DATABASE_URL',
'HELP_FORUM_CHANNEL_ID',
];
const missing = required.filter((k) => !process.env[k]);
if (missing.length) {
console.error(`[Boot] Missing env variables: ${missing.join(', ')}`);
process.exit(1);
}
// Init DB schema
await db.initSchema();
// Start health server
app.listen(PORT, () => {
console.log(`[Health] Listening on port ${PORT}`);
});
// Give Telegram module access to Discord client for posting replies
telegram.setDiscordClient(client);
telegram.startPolling();
// Login to Discord
await client.login(process.env.DISCORD_TOKEN);
}
// ── Graceful Shutdown ───────────────────────────────────────────────────────
async function shutdown(signal) {
console.log(`[Bot] Received ${signal}, shutting down...`);
telegram.stopPolling();
client.destroy();
await db.shutdown();
process.exit(0);
}
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('unhandledRejection', (err) => {
console.error('[Bot] Unhandled rejection:', err);
});
start().catch((err) => {
console.error('[Boot] Fatal error:', err);
process.exit(1);
});