-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
638 lines (566 loc) · 22.9 KB
/
app.js
File metadata and controls
638 lines (566 loc) · 22.9 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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
import 'dotenv/config';
import express from 'express';
import {
InteractionResponseFlags,
InteractionResponseType,
InteractionType,
verifyKeyMiddleware,
} from 'discord-interactions';
import { createClient } from "@libsql/client";
import { Client, GatewayIntentBits, Partials, ActivityType } from 'discord.js';
// --- Discord.js client for DMs ---
const botClient = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.DirectMessages],
partials: [Partials.Channel],
});
botClient.once('ready', () => {
console.log(`Logged in as ${botClient.user.tag}!`);
botClient.user.setActivity({
name: 'Manage your objectives at https://taskerbot-dashboard.vercel.app/',
type: ActivityType.Custom,
});
});
botClient.login(process.env.DISCORD_TOKEN);
// --- Express app setup ---
const app = express();
const PORT = process.env.PORT || 3000;
// --- SQLite setup ---
const client = createClient({
url: process.env.TURSO_DATABASE_URL,
authToken: process.env.TURSO_AUTH_TOKEN,
});
await client.execute(`
CREATE TABLE IF NOT EXISTS objectives (
userId TEXT,
name TEXT,
frequency TEXT,
lastSubmitted INTEGER,
streak INTEGER,
lastStreakDay TEXT,
lastReminded INTEGER,
PRIMARY KEY (userId, name)
)
`);
await client.execute(`
CREATE TABLE IF NOT EXISTS user_settings (
userId TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT,
PRIMARY KEY (userId, key)
)
`);
// --- Helper functions ---
async function getObjectives(userId) {
const result = await client.execute({
sql: 'SELECT * FROM objectives WHERE userId = ?',
args: [userId],
});
return result.rows;
}
async function getObjective(userId, name) {
const result = await client.execute({
sql: 'SELECT * FROM objectives WHERE userId = ? AND name = ?',
args: [userId, name],
});
return result.rows[0];
}
async function upsertObjective(obj) {
await client.execute({
sql: `
INSERT INTO objectives (userId, name, frequency, lastSubmitted, streak, lastStreakDay, lastReminded)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(userId, name) DO UPDATE SET
frequency=excluded.frequency,
lastSubmitted=excluded.lastSubmitted,
streak=excluded.streak,
lastStreakDay=excluded.lastStreakDay,
lastReminded=excluded.lastReminded
`,
args: [
obj.userId,
obj.name,
obj.frequency,
obj.lastSubmitted,
obj.streak,
obj.lastStreakDay,
obj.lastReminded,
],
});
}
async function createObjective(obj) {
await client.execute({
sql: `
INSERT INTO objectives (userId, name, frequency, lastSubmitted, streak, lastStreakDay, lastReminded)
VALUES (?, ?, ?, NULL, 0, NULL, NULL)
`,
args: [obj.userId, obj.name, obj.frequency],
});
}
async function deleteObjective(userId, name) {
await client.execute({
sql: 'DELETE FROM objectives WHERE userId = ? AND name = ?',
args: [userId, name],
});
}
async function renameObjective(userId, currentName, newName) {
await client.execute({
sql: 'UPDATE objectives SET name = ? WHERE userId = ? AND name = ?',
args: [newName, userId, currentName],
});
}
/**
* Gets the visibility setting for a user. Defaults to 'ephemeral'.
* @param {string} userId - The user's Discord ID.
* @returns {Promise<'ephemeral' | 'public'>}
*/
async function getUserVisibility(userId) {
const result = await client.execute({
sql: 'SELECT value FROM user_settings WHERE userId = ? AND key = ?',
args: [userId, 'visibility'],
});
const setting = result.rows[0];
return setting ? setting.value : 'ephemeral';
}
async function setUserVisibility(userId, visibility) {
await client.execute({
sql: 'INSERT INTO user_settings (userId, key, value) VALUES (?, ?, ?) ON CONFLICT(userId, key) DO UPDATE SET value=excluded.value',
args: [userId, 'visibility', visibility],
});
}
/**
* Returns the next allowed submission timestamp for an objective.
* @param {object} obj - The objective object from the DB.
* @returns {number} - Timestamp in ms when the window opens.
*/
function getNextAllowedTime(obj) {
if (!obj.lastSubmitted) return Date.now(); // Window is open now if never submitted
if (obj.frequency === 'daily') {
return obj.lastSubmitted + 22 * 60 * 60 * 1000;
}
if (obj.frequency === 'weekly') {
return obj.lastSubmitted + (7 * 24 - 6) * 60 * 60 * 1000;
}
if (obj.frequency === 'monthly') {
return obj.lastSubmitted + (30 * 24 - 6) * 60 * 60 * 1000;
}
return Date.now();
}
// Helper for ephemeral error responses
function sendEphemeral(res, content) {
return res.send({
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
content,
flags: InteractionResponseFlags.EPHEMERAL,
},
});
}
/**
* Sends a response that respects the user's visibility setting.
* @param {object} res - The Express response object.
* @param {string} userId - The user's Discord ID.
* @param {object} data - The response data payload (content, embeds, etc.).
*/
async function sendResponse(res, userId, data) {
const visibility = await getUserVisibility(userId);
if (visibility === 'ephemeral') {
data.flags = InteractionResponseFlags.EPHEMERAL;
}
return res.send({
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data,
});
}
// --- 24h Reminder Job ---
setInterval(async () => {
const now = Date.now();
const result = await client.execute('SELECT * FROM objectives');
const objectives = result.rows;
for (const obj of objectives) {
const windowOpen = getNextAllowedTime(obj);
// Only remind if:
// - The window has been open for more than 24h
// - The user hasn't been reminded since the window opened
// - The user hasn't submitted since the window opened
if (
now > windowOpen + 24 * 60 * 60 * 1000 &&
(!obj.lastReminded || obj.lastReminded < windowOpen)
) {
try {
const user = await botClient.users.fetch(obj.userId);
if (user) {
await user.send(
`⏰ Reminder: You haven't submitted your objective "**${obj.name}**" since it became available over 24 hours ago. Don't forget to keep your streak going!`
);
await client.execute({
sql: `UPDATE objectives SET lastReminded = ? WHERE userId = ? AND name = ?`,
args: [now, obj.userId, obj.name],
});
}
} catch (err) {
// Handle specific Discord API errors
if (err.code === 50007) {
// Cannot send messages to this user (DMs disabled or blocked)
console.log(`User ${obj.userId} has DMs disabled or blocked the bot. Skipping reminder for objective "${obj.name}".`);
// Mark as reminded to prevent spam attempts
await client.execute({
sql: `UPDATE objectives SET lastReminded = ? WHERE userId = ? AND name = ?`,
args: [now, obj.userId, obj.name],
});
} else if (err.code === 10013) {
// Unknown user (user account deleted or invalid)
console.log(`User ${obj.userId} not found (account may be deleted). Skipping reminder for objective "${obj.name}".`);
// Mark as reminded to prevent future attempts
await client.execute({
sql: `UPDATE objectives SET lastReminded = ? WHERE userId = ? AND name = ?`,
args: [now, obj.userId, obj.name],
});
} else {
// Other errors - log but don't mark as reminded to retry later
console.error(`Failed to send DM to user ${obj.userId} for objective "${obj.name}":`, err.message);
}
}
}
}
}, 60 * 60 * 1000); // Check every hour
// --- Express route for interactions ---
app.post('/interactions', verifyKeyMiddleware(process.env.PUBLIC_KEY), async function (req, res) {
const { id, type, data } = req.body;
if (type === InteractionType.PING) {
return res.send({ type: InteractionResponseType.PONG });
}
if (type === InteractionType.MESSAGE_COMPONENT) {
const userId = req.body.member?.user?.id || req.body.user?.id;
const { custom_id } = data;
if (custom_id.startsWith('visibility_')) {
const newVisibility = custom_id.split('_')[1]; // 'public' or 'ephemeral'
await setUserVisibility(userId, newVisibility);
// Update the original message in place
const currentVisibility = newVisibility;
const otherVisibility = currentVisibility === 'ephemeral' ? 'public' : 'ephemeral';
return res.send({
type: InteractionResponseType.UPDATE_MESSAGE,
data: {
embeds: [{
title: 'Settings',
description: 'Manage your bot preferences here.',
color: 0x5865F2, // Discord blurple
fields: [
{
name: 'Message Visibility',
value: `Your responses are currently set to **${currentVisibility}**.`,
},
],
}],
components: [{
type: 1, // Action Row
components: [{
type: 2, // Button
style: 2, // Secondary (grey)
label: `Switch to ${otherVisibility.charAt(0).toUpperCase() + otherVisibility.slice(1)}`,
custom_id: `visibility_${otherVisibility}`,
}],
}],
flags: InteractionResponseFlags.EPHEMERAL,
},
});
}
return res.sendStatus(400);
}
if (type === InteractionType.APPLICATION_COMMAND_AUTOCOMPLETE) {
const { name, options } = data;
if (name === 'submit' || name === 'delete_objective' || name === 'rename') {
const focusedOption = options.find((opt) => opt.focused);
const userId = req.body.member?.user?.id || req.body.user?.id;
if (
(name === 'submit' && focusedOption.name === 'objective') ||
(name === 'delete_objective' && focusedOption.name === 'name') ||
(name === 'rename' && focusedOption.name === 'current_name')
) {
const objectives = await getObjectives(userId);
const filtered = objectives.filter((obj) =>
obj.name.toLowerCase().includes(focusedOption.value.toLowerCase())
);
return res.send({
type: InteractionResponseType.APPLICATION_COMMAND_AUTOCOMPLETE_RESULT,
data: {
choices: filtered.map((obj) => ({ name: obj.name, value: obj.name })).slice(0, 25),
},
});
}
}
return res.send({
type: InteractionResponseType.APPLICATION_COMMAND_AUTOCOMPLETE_RESULT,
data: {
choices: [],
},
});
}
if (type === InteractionType.APPLICATION_COMMAND) {
const { name } = data;
if (name === 'submit') {
const userId = req.body.member?.user?.id || req.body.user?.id;
const imageOption = data.options.find(opt => opt.name === 'image');
const objectiveOption = data.options.find(opt => opt.name === 'objective');
const objective = objectiveOption?.value?.trim();
// Try to find the attachment in all possible locations
let attachment = null;
if (imageOption?.value && typeof imageOption.value === 'object' && imageOption.value.url) {
attachment = imageOption.value;
} else if (imageOption?.value && data.resolved && data.resolved.attachments) {
attachment = data.resolved.attachments[imageOption.value];
} else if (imageOption?.value && req.body.attachments) {
attachment = req.body.attachments.find(att => att.id === imageOption.value);
}
// Error handling
if (!attachment && !objective) {
return await sendResponse(res, userId, { content: 'Missing both image and objective.' });
}
if (!attachment) {
return await sendResponse(res, userId, { content: 'Missing image.' });
}
if (!objective) {
return await sendResponse(res, userId, { content: 'Missing objective.' });
}
// Find the objective object in the database
let obj = await getObjective(userId, objective);
if (!obj) {
return await sendResponse(res, userId, { content: `Objective "${objective}" not found. Please create it first with /create_objective.` });
}
// Frequency check
const now = Date.now();
const nextAllowed = getNextAllowedTime(obj);
if (obj.lastSubmitted && now < nextAllowed) {
const discordTs = `<t:${Math.floor(nextAllowed / 1000)}:R>`; return await sendResponse(res, userId, { content: `You have already submitted **${objective}**. Try again ${discordTs}.` });
}
// Mark as submitted
obj.lastSubmitted = now;
// Streak logic
const today = new Date();
const lastStreakDay = obj.lastStreakDay ? new Date(obj.lastStreakDay) : null;
let isConsecutive = false;
if (lastStreakDay) {
// Check if last streak day was yesterday (for daily), last week (for weekly), last month (for monthly)
if (obj.frequency === 'daily') {
const diff = Math.floor((today - lastStreakDay) / (24 * 60 * 60 * 1000));
isConsecutive = diff === 1;
} else if (obj.frequency === 'weekly') {
const diff = Math.floor((today - lastStreakDay) / (7 * 24 * 60 * 60 * 1000));
isConsecutive = diff === 1;
} else if (obj.frequency === 'monthly') {
isConsecutive = (today.getMonth() === lastStreakDay.getMonth() + 1) &&
(today.getFullYear() === lastStreakDay.getFullYear());
}
}
if (isConsecutive) {
obj.streak = (obj.streak || 0) + 1;
} else {
obj.streak = 1;
}
obj.lastStreakDay = today.toISOString().split('T')[0]; // Store as YYYY-MM-DD
await upsertObjective(obj);
// Calculate next allowed submission time for response (AFTER updating lastSubmitted)
const nextAllowedAfter = getNextAllowedTime(obj);
const discordTs = `<t:${Math.floor(nextAllowedAfter / 1000)}:R>`;
const userMention = `<@${userId}>`;
const responseData = {
embeds: [
{
description: `Objective '${objective}' completed!` +
(obj.streak > 3 ? `\nStreak: ${obj.streak} 🔥` : ''),
image: { url: attachment.url },
},
{
description: `${userMention} will be able to submit this objective again ${discordTs}`,
},
],
};
return await sendResponse(res, userId, responseData);
}
// "create_objective" command
if (name === 'create_objective') {
const userId = req.body.member?.user?.id || req.body.user?.id;
const nameOption = data.options.find(opt => opt.name === 'name');
const freqOption = data.options.find(opt => opt.name === 'frequency');
const objectiveName = nameOption?.value?.trim();
const frequency = freqOption?.value;
if (!objectiveName || !frequency) {
return await sendResponse(res, userId, { content: 'Objective name and frequency are required.' });
}
// Check if already exists
if (await getObjective(userId, objectiveName)) {
return await sendResponse(res, userId, { content: `Objective "${objectiveName}" already exists.` });
}
await createObjective({
userId,
name: objectiveName,
frequency,
});
return await sendResponse(res, userId, { content: `Objective "${objectiveName}" (${frequency}) created!` });
}
// "list_objectives" command
if (name === 'list_objectives') {
const userId = req.body.member?.user?.id || req.body.user?.id;
const objectives = await getObjectives(userId);
if (objectives.length === 0) {
return await sendResponse(res, userId, { content: 'You have no objectives.' });
}
const now = Date.now();
const lines = objectives.map(obj => {
const nextAllowed = getNextAllowedTime(obj);
let timeStr = '';
if (!obj.lastSubmitted) {
timeStr = 'Available now';
} else if (now >= nextAllowed) {
timeStr = 'Available now';
} else {
timeStr = `<t:${Math.floor(nextAllowed / 1000)}:R>`;
}
return `- *${obj.name}* (${obj.frequency}) - ${timeStr}` +
(obj.streak > 3 ? ` | Streak: ${obj.streak} 🔥` : '');
});
return await sendResponse(res, userId, { content: `Your objectives:\n${lines.join('\n')}` });
}
// "delete_objective" command
if (name === 'delete_objective') {
const userId = req.body.member?.user?.id || req.body.user?.id;
const nameOption = data.options.find(opt => opt.name === 'name');
const objectiveName = nameOption?.value?.trim();
if (!objectiveName) {
return await sendResponse(res, userId, { content: 'Objective name is required.' });
}
if (!await getObjective(userId, objectiveName)) {
return await sendResponse(res, userId, { content: `Objective "${objectiveName}" not found.` });
}
await deleteObjective(userId, objectiveName);
return await sendResponse(res, userId, { content: `Objective "${objectiveName}" has been deleted forever.` });
}
// "rename" command
if (name === 'rename') {
const userId = req.body.member?.user?.id || req.body.user?.id;
const currentNameOption = data.options.find(opt => opt.name === 'current_name');
const newNameOption = data.options.find(opt => opt.name === 'new_name');
const currentName = currentNameOption?.value?.trim();
const newName = newNameOption?.value?.trim();
if (!currentName || !newName) {
return await sendResponse(res, userId, { content: 'Both current name and new name are required.' });
}
if (!await getObjective(userId, currentName)) {
return await sendResponse(res, userId, { content: `Objective "${currentName}" not found.` });
}
if (await getObjective(userId, newName)) {
return await sendResponse(res, userId, { content: `An objective with the name "${newName}" already exists.` });
}
await renameObjective(userId, currentName, newName);
return await sendResponse(res, userId, { content: `Objective "${currentName}" has been renamed to "${newName}".` });
}
// "help" command
if (name === 'help') {
const userId = req.body.member?.user?.id || req.body.user?.id;
const commandOption = data.options.find(opt => opt.name === 'command');
const commandName = commandOption?.value;
let title = '';
let description = '';
let image = null;
let url = null;
switch (commandName) {
case 'submit':
title = '`/submit`';
description = 'Submit a picture for one of your objectives. You must provide the image and the name of an objective you have already created.';
image = { url: 'https://i.imgur.com/UAbUQ28.gif' };
break;
case 'create_objective':
title = '`/create_objective`';
description = 'Create a new objective. You need to provide a unique name and select a frequency (daily, weekly, or monthly).';
image = { url: 'https://i.imgur.com/Z936pXa.gif' };
break;
case 'list_objectives':
title = '`/list_objectives`';
description = 'Lists all of your current objectives, their frequency, and when you can next submit them.';
image = { url: 'https://i.imgur.com/ANsLTEk.gif' };
break;
case 'delete_objective':
title = '`/delete_objective`';
description = 'Permanently delete one of your objectives. You must provide the name of the objective to delete.';
image = { url: 'https://i.imgur.com/Oi7NVT7.gif' };
break;
case 'rename':
title = '`/rename`';
description = 'Rename one of your existing objectives. You must provide the current name and the new name.';
image = { url: 'https://i.imgur.com/G7rsDSJ' };
break;
case 'settings':
title = '`/settings`';
description = 'Adjust your bot preferences, such as message visibility (ephemeral or public).';
image = { url: 'https://i.imgur.com/fMPyBjF.gif' };
break;
case 'help':
title = '`/help`';
description = 'Get detailed information about how to use each of the bot commands.';
image = { url: 'https://i.imgur.com/wAn5Xiq' };
break;
case 'GitHub':
title = 'GitHub Repository';
description = 'Check out the source code for this bot on [GitHub](https://github.com/rsomonte/taskerbot)!';
url = 'https://github.com/rsomonte/taskerbot';
break;
case 'Dashboard':
title = 'Tasker Bot Dashboard';
description = 'Manage your objectives from the official website: https://taskerbot-dashboard.vercel.app/!';
url = 'https://taskerbot-dashboard.vercel.app/';
break;
}
const embed = {
title: title,
description: description,
color: 0x5865F2, // Discord blurple
};
if (image) {
embed.image = image;
}
if (url) {
embed.url = url;
}
return await sendResponse(res, userId, { embeds: [embed] });
}
// settings command
if (name === 'settings') {
const userId = req.body.member?.user?.id || req.body.user?.id;
const currentVisibility = await getUserVisibility(userId);
const otherVisibility = currentVisibility === 'ephemeral' ? 'public' : 'ephemeral';
return res.send({
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: {
embeds: [{
title: 'Settings',
description: 'Manage your bot preferences here.',
color: 0x5865F2, // Discord blurple
fields: [
{
name: 'Message Visibility',
value: `Your responses are currently set to **${currentVisibility}**.`,
},
],
}],
components: [{
type: 1, // Action Row
components: [{
type: 2, // Button
style: 2, // Secondary (grey)
label: `Switch to ${otherVisibility.charAt(0).toUpperCase() + otherVisibility.slice(1)}`,
custom_id: `visibility_${otherVisibility}`,
}],
}],
flags: InteractionResponseFlags.EPHEMERAL,
},
});
}
console.error(`unknown command type: ${type}`);
return res.sendStatus(400);
}
res.sendStatus(404);
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});