forked from stack-auth/stack-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiscord-webhook.ts
More file actions
448 lines (394 loc) · 14.1 KB
/
discord-webhook.ts
File metadata and controls
448 lines (394 loc) · 14.1 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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
/**
* Discord Bot API implementation with session threading support
*/
interface DiscordMessage {
id: string;
channel_id: string;
content: string;
timestamp: string;
thread?: {
id: string;
name: string;
};
}
interface DiscordThread {
id: string;
name: string;
parent_id: string;
}
export async function sendToDiscordWebhook(data: {
message: string;
username?: string;
metadata?: {
sessionId?: string;
messageNumber?: number;
pathname?: string;
timestamp?: string;
userAgent?: string;
messageType?: string;
timeOnPage?: number;
isFollowUp?: boolean;
};
}) {
const botToken = process.env.DISCORD_BOT_TOKEN;
const channelId = process.env.DISCORD_CHANNEL_ID;
if (!botToken || !channelId) {
console.warn('Discord bot token or channel ID not configured');
return;
}
try {
const { message, metadata } = data;
// Format message with clean text structure
const sessionPrefix = metadata?.sessionId ? metadata.sessionId.slice(-8) : 'unknown';
const messageNumber = metadata?.messageNumber || 1;
const messageType = metadata?.messageType === 'starter-prompt' ? '🟢' : '🔵';
const timeOnPage = metadata?.timeOnPage ? formatTime(metadata.timeOnPage) : 'N/A';
const browserInfo = extractBrowserInfo(metadata?.userAgent || '');
const page = formatPagePath(metadata?.pathname || '/');
// Check if an existing thread exists for this session
const existingThreadId = await findExistingThread(channelId, sessionPrefix);
if (existingThreadId) {
// Send to existing thread
await sendToThread(existingThreadId, message, {
messageNumber,
messageType,
page,
timeOnPage,
browserInfo
});
} else {
// Create new thread for first message
await createNewThread(channelId, message, {
sessionPrefix,
messageNumber,
messageType,
page,
timeOnPage,
browserInfo
});
}
} catch (error) {
if (error instanceof TypeError) {
// Network errors, CORS issues, or malformed URLs
console.error('Network error sending message to Discord:', error.message);
} else if (error instanceof SyntaxError) {
// JSON parsing errors
console.error('JSON parsing error in Discord webhook:', error.message);
} else if (error instanceof Error) {
// General errors with message
console.error('Error sending message to Discord:', error.message);
} else {
// Unknown error types
console.error('Unknown error sending message to Discord:', error);
}
}
}
export async function sendLLMResponseToDiscord(data: {
response: string;
metadata?: {
sessionId?: string;
model?: string;
};
}) {
const botToken = process.env.DISCORD_BOT_TOKEN;
const channelId = process.env.DISCORD_CHANNEL_ID;
if (!botToken || !channelId) {
console.warn('Discord bot token or channel ID not configured');
return;
}
try {
const { response, metadata } = data;
const sessionId = metadata?.sessionId || 'unknown';
const sessionPrefix = sessionId.slice(-8);
// Find the existing thread for this session
const existingThreadId = await findExistingThread(channelId, sessionPrefix);
if (!existingThreadId) {
console.warn(`No thread found for session ${sessionId}`);
return;
}
await sendResponseToThread(existingThreadId, response, {
model: metadata?.model
});
} catch (error) {
if (error instanceof TypeError) {
// Network errors, CORS issues, or malformed URLs
console.error('Network error sending LLM response to Discord:', error.message);
} else if (error instanceof SyntaxError) {
// JSON parsing errors
console.error('JSON parsing error in Discord LLM response:', error.message);
} else if (error instanceof Error) {
// General errors with message
console.error('Error sending LLM response to Discord:', error.message);
} else {
// Unknown error types
console.error('Unknown error sending LLM response to Discord:', error);
}
}
}
async function findExistingThread(channelId: string, sessionPrefix: string): Promise<string | null> {
const botToken = process.env.DISCORD_BOT_TOKEN;
if (!botToken) {
return null;
}
try {
// Get recent messages from the channel to find existing threads
const response = await fetch(`https://discord.com/api/v10/channels/${channelId}/messages?limit=50`, {
headers: {
'Authorization': `Bot ${botToken}`,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
const errorText = await response.text();
console.error(`Failed to fetch recent messages (${response.status}):`, errorText);
return null;
}
const messages: DiscordMessage[] = await response.json();
// Look for a message that contains our session prefix and has an associated thread
for (const message of messages) {
if (message.content.includes(`\`${sessionPrefix}\``) && message.thread) {
console.log(`Found existing thread for session ${sessionPrefix}: ${message.thread.id}`);
return message.thread.id;
}
}
return null;
} catch (error) {
if (error instanceof TypeError) {
// Network errors, invalid URL, or connection issues
console.error('Network error finding existing thread:', error.message);
} else if (error instanceof SyntaxError) {
// JSON parsing errors from Discord API response
console.error('JSON parsing error in Discord API response:', error.message);
} else if (error instanceof Error) {
// General errors with message
console.error('Error finding existing thread:', error.message);
} else {
// Unknown error types
console.error('Unknown error finding existing thread:', error);
}
return null;
}
}
async function createNewThread(
channelId: string,
message: string,
context: {
sessionPrefix: string;
messageNumber: number;
messageType: string;
page: string;
timeOnPage: string;
browserInfo?: string;
}
): Promise<void> {
const botToken = process.env.DISCORD_BOT_TOKEN;
try {
// Clean, readable format
const initialMessage = `💬 ${message}
\`${context.sessionPrefix}\` ${context.messageType} • ${context.page} • Page time: ${context.timeOnPage}${context.browserInfo ? ` • ${context.browserInfo}` : ''}`;
const messageResponse = await fetch(`https://discord.com/api/v10/channels/${channelId}/messages`, {
method: 'POST',
headers: {
'Authorization': `Bot ${botToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: initialMessage,
}),
});
if (!messageResponse.ok) {
const errorText = await messageResponse.text();
console.error(`Failed to send initial message (${messageResponse.status}):`, errorText);
return;
}
const messageData: DiscordMessage = await messageResponse.json();
// Create a thread from this message
const threadName = `${context.sessionPrefix}: ${extractQuestionSummary(message)}`;
const threadResponse = await fetch(`https://discord.com/api/v10/channels/${messageData.channel_id}/messages/${messageData.id}/threads`, {
method: 'POST',
headers: {
'Authorization': `Bot ${botToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: threadName.slice(0, 100), // Discord thread names have a 100 character limit
auto_archive_duration: 1440, // 24 hours
}),
});
if (!threadResponse.ok) {
const errorText = await threadResponse.text();
console.error(`Failed to create thread (${threadResponse.status}):`, errorText);
return;
}
const threadData: DiscordThread = await threadResponse.json();
console.log(`Created new thread: ${threadData.name} (${threadData.id})`);
} catch (error) {
if (error instanceof TypeError) {
// Network errors, invalid URL, or connection issues
console.error('Network error creating new thread:', error.message);
} else if (error instanceof SyntaxError) {
// JSON parsing errors from Discord API response
console.error('JSON parsing error creating thread:', error.message);
} else if (error instanceof Error) {
// General errors with message
console.error('Error creating thread:', error.message);
} else {
// Unknown error types
console.error('Unknown error creating thread:', error);
}
}
}
async function sendToThread(
threadId: string,
message: string,
context: {
messageNumber: number;
messageType: string;
page: string;
timeOnPage: string;
browserInfo?: string;
}
): Promise<void> {
const botToken = process.env.DISCORD_BOT_TOKEN;
try {
// Clean follow-up format
const formattedMessage = `🔄 **${message}**
${context.messageType} • ${context.page} • Page time: ${context.timeOnPage}${context.browserInfo ? ` • ${context.browserInfo}` : ''}`;
const response = await fetch(`https://discord.com/api/v10/channels/${threadId}/messages`, {
method: 'POST',
headers: {
'Authorization': `Bot ${botToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: formattedMessage,
}),
});
if (!response.ok) {
const errorText = await response.text();
console.error(`Failed to send message to thread (${response.status}):`, errorText);
// If thread doesn't exist anymore, log it but continue
if (response.status === 404) {
console.warn(`Thread ${threadId} no longer exists`);
}
} else {
console.log(`Sent follow-up message to thread ${threadId}`);
}
} catch (error) {
if (error instanceof TypeError) {
// Network errors, invalid URL, or connection issues
console.error('Network error sending message to thread:', error.message);
} else if (error instanceof SyntaxError) {
// JSON parsing errors
console.error('JSON parsing error sending to thread:', error.message);
} else if (error instanceof Error) {
// General errors with message
console.error('Error sending message to thread:', error.message);
} else {
// Unknown error types
console.error('Unknown error sending message to thread:', error);
}
}
}
async function sendResponseToThread(
threadId: string,
response: string,
context: {
model?: string;
}
): Promise<void> {
const botToken = process.env.DISCORD_BOT_TOKEN;
try {
const model = context.model || 'N/A';
// Truncate response if too long for Discord (2000 char limit)
const truncatedResponse = response.length > 1500 ? response.slice(0, 1500) + '...' : response;
const formattedResponse = `🤖 **AI Response**
\`\`\`
${truncatedResponse}
\`\`\`
${model}`;
const discordResponse = await fetch(`https://discord.com/api/v10/channels/${threadId}/messages`, {
method: 'POST',
headers: {
'Authorization': `Bot ${botToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: formattedResponse,
}),
});
if (!discordResponse.ok) {
const errorText = await discordResponse.text();
console.error(`Failed to send response to thread (${discordResponse.status}):`, errorText);
// If thread doesn't exist anymore, log it but continue
if (discordResponse.status === 404) {
console.warn(`Thread ${threadId} no longer exists for AI response`);
}
} else {
console.log(`Sent AI response to thread ${threadId}`);
}
} catch (error) {
if (error instanceof TypeError) {
// Network errors, invalid URL, or connection issues
console.error('Network error sending response to thread:', error.message);
} else if (error instanceof SyntaxError) {
// JSON parsing errors
console.error('JSON parsing error sending response to thread:', error.message);
} else if (error instanceof Error) {
// General errors with message
console.error('Error sending response to thread:', error.message);
} else {
// Unknown error types
console.error('Unknown error sending response to thread:', error);
}
}
}
function extractQuestionSummary(message: string): string {
// Extract first few words of the question for thread naming
const words = message.split(' ').slice(0, 6).join(' ');
return words.length > 40 ? words.slice(0, 37) + '...' : words;
}
function formatPagePath(pathname: string): string {
// Simplify common paths for better readability
if (pathname === '/') return 'Home';
if (pathname.startsWith('/docs/')) {
const path = pathname.replace('/docs/', '');
if (path === '') return 'Docs';
// Show only the last part of the path for brevity
const parts = path.split('/');
return parts[parts.length - 1] || 'Docs';
}
return pathname.length > 20 ? '...' + pathname.slice(-17) : pathname;
}
function formatTime(seconds: number): string {
if (seconds < 60) return `${seconds}s`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
return `${Math.floor(seconds / 3600)}h`;
}
/**
* Extract browser and OS info from user agent
*/
function extractBrowserInfo(userAgent: string): string | undefined {
if (!userAgent) return undefined;
// Browser detection patterns (order matters - Chrome must come before Safari)
const browserPatterns = [
{ pattern: 'Edge/', name: 'Edge' },
{ pattern: 'Chrome/', name: 'Chrome' },
{ pattern: 'Firefox/', name: 'Firefox' },
{ pattern: 'Safari/', name: 'Safari' },
];
// OS detection patterns
const osPatterns = [
{ pattern: 'Windows NT', name: 'Windows' },
{ pattern: 'Mac OS X', name: 'macOS' },
{ pattern: 'iPhone', name: 'iOS' },
{ pattern: 'iPad', name: 'iOS' },
{ pattern: 'Android', name: 'Android' },
{ pattern: 'Linux', name: 'Linux' },
];
// Find browser
const browser = browserPatterns.find(({ pattern }) => userAgent.includes(pattern))?.name || 'Unknown';
// Find OS
const os = osPatterns.find(({ pattern }) => userAgent.includes(pattern))?.name || 'Unknown';
return `${browser} on ${os}`;
}