-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiscord-bot.js
More file actions
246 lines (202 loc) · 7.32 KB
/
Copy pathdiscord-bot.js
File metadata and controls
246 lines (202 loc) · 7.32 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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
#!/usr/bin/env node
/**
* Discord Bot for Formulo
*
* Uses the SAME /api/solve endpoint as the web UI.
* No direct LLM or SymPy calls. Single pipeline for both consumers.
*
* Environment variables:
* DISCORD_TOKEN - Bot token from Discord Developer Portal (required)
* DISCORD_CHANNEL_ID - Channel ID to monitor (required)
* FORMULO_API_URL - Base URL of the Formulo server (default: http://localhost:5000)
*/
import { Client, GatewayIntentBits } from 'discord.js';
// ── Configuration ────────────────────────────────────────────────────────────
const DISCORD_TOKEN = process.env.DISCORD_TOKEN;
const DISCORD_CHANNEL_ID = process.env.DISCORD_CHANNEL_ID;
const API_BASE = process.env.FORMULO_API_URL || `http://localhost:${process.env.PORT || 5000}`;
if (!DISCORD_TOKEN) {
console.error('[discord-bot] DISCORD_TOKEN is required');
process.exit(1);
}
if (!DISCORD_CHANNEL_ID) {
console.error('[discord-bot] DISCORD_CHANNEL_ID is required');
process.exit(1);
}
// ── API helpers ──────────────────────────────────────────────────────────────
/**
* Call /api/solve (SSE) and collect the final result.
* Guardrail runs as the first step inside the pipeline.
* Calls onStep for each progress event so the bot can update its message.
* Returns the final result object from the 'done' event.
*/
async function callSolve(message, sessionId, onStep) {
const res = await fetch(`${API_BASE}/api/solve`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message, sessionId }),
signal: AbortSignal.timeout(120000),
});
if (!res.ok) {
const text = await res.text();
throw new Error(`/api/solve returned ${res.status}: ${text}`);
}
// Parse SSE stream
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let result = null;
let lastError = null;
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
// Process complete SSE events (separated by double newline)
let boundary;
while ((boundary = buffer.indexOf('\n\n')) >= 0) {
const rawEvent = buffer.slice(0, boundary);
buffer = buffer.slice(boundary + 2);
let eventType = 'message';
let eventData = '';
for (const line of rawEvent.split('\n')) {
if (line.startsWith('event: ')) {
eventType = line.slice(7);
} else if (line.startsWith('data: ')) {
eventData += line.slice(6);
}
}
if (!eventData) continue;
try {
const parsed = JSON.parse(eventData);
if (eventType === 'step' && onStep) {
onStep(parsed);
} else if (eventType === 'done') {
result = parsed;
} else if (eventType === 'error') {
lastError = parsed.error || 'Unknown error';
}
} catch {
// Ignore malformed SSE data
}
}
}
if (lastError && !result) {
throw new Error(lastError);
}
return result;
}
// ── Discord Bot ──────────────────────────────────────────────────────────────
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
client.once('ready', () => {
console.log(`[discord-bot] Logged in as ${client.user.tag}`);
console.log(`[discord-bot] Monitoring channel: ${DISCORD_CHANNEL_ID}`);
console.log(`[discord-bot] API base: ${API_BASE}`);
});
/**
* Split a long string into chunks ≤ maxLen characters, breaking on newlines.
*/
function splitMessage(text, maxLen = 1990) {
if (text.length <= maxLen) return [text];
const chunks = [];
let remaining = text;
while (remaining.length > maxLen) {
let splitAt = remaining.lastIndexOf('\n', maxLen);
if (splitAt <= 0) splitAt = maxLen;
chunks.push(remaining.slice(0, splitAt));
remaining = remaining.slice(splitAt).trimStart();
}
if (remaining.length > 0) chunks.push(remaining);
return chunks;
}
client.on('messageCreate', async (message) => {
if (message.author.bot) return;
if (message.channelId !== DISCORD_CHANNEL_ID) return;
// Only respond when the bot is mentioned
if (!message.mentions.has(client.user)) return;
// Strip the mention from the message to get the actual problem
const problem = message.content.replace(/<@!?\d+>/g, '').trim();
if (!problem) return;
console.log(`[discord-bot] Received: ${problem.slice(0, 100)}`);
let progressMsg;
try {
progressMsg = await message.channel.send('Przetwarzam zadanie...');
} catch (err) {
console.error('[discord-bot] Failed to send initial message:', err);
return;
}
const updateProgress = async (text) => {
try {
await progressMsg.edit(text);
} catch {
// Ignore edit errors (rate limits, etc.)
}
};
try {
await updateProgress('Rozwiazuję zadanie...');
const sessionId = `discord-${message.author.id}-${Date.now()}`;
const result = await callSolve(problem, sessionId, (step) => {
// Update progress message with the latest step
if (step.content && step.agentName) {
updateProgress(`${step.agentName}: ${step.content.slice(0, 150)}`);
}
});
if (!result || !result.success) {
if (result?.blocked) {
await progressMsg.edit(result.reason || 'To zapytanie nie dotyczy matematyki.');
} else {
await progressMsg.edit('Nie udalo sie rozwiazac zadania.');
}
return;
}
// Delete progress message and send results
try {
await progressMsg.delete();
} catch {
// Ignore
}
// Handle different result types
if (result.type === 'generator' || result.type === 'arithmetic') {
// Generator tasks or arithmetic scheme: single content block
for (const chunk of splitMessage(result.content)) {
await message.channel.send(chunk);
}
} else {
// Solve pipeline result
if (result.classification) {
const classType = result.classification.type || 'general';
const conf = Math.round((result.classification.confidence || 0) * 100);
await message.channel.send(`**Klasyfikacja:** ${classType} (${conf}%)`);
}
if (result.sympyResult) {
for (const chunk of splitMessage(`**Wynik SymPy:**\n${result.sympyResult}`)) {
await message.channel.send(chunk);
}
}
if (result.summary) {
for (const chunk of splitMessage(result.summary)) {
await message.channel.send(chunk);
}
}
}
} catch (err) {
console.error('[discord-bot] Pipeline error:', err);
try {
await progressMsg.edit(`Blad: ${err.message}`);
} catch {
// Ignore
}
}
});
console.log('[discord-bot] Attempting login...');
console.log(`[discord-bot] DISCORD_CHANNEL_ID: ${DISCORD_CHANNEL_ID}`);
console.log(`[discord-bot] API_BASE: ${API_BASE}`);
client.login(DISCORD_TOKEN).catch((err) => {
console.error('[discord-bot] Login failed:', err.message);
process.exit(1);
});