-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathreminders.ts
More file actions
94 lines (84 loc) · 2.44 KB
/
reminders.ts
File metadata and controls
94 lines (84 loc) · 2.44 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
import {
default as CookiecordClient,
Module,
command,
listener,
} from 'cookiecord';
import { Column, Entity, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
import parse from 'parse-duration';
import { Message } from 'discord.js';
import { getDB } from '../db';
import prettyMs from 'pretty-ms';
import { setTimeout } from 'timers';
import { Reminder } from '../entities/Reminder';
import { invalidDuration, okHand, syntaxWarning } from './msg';
export class ReminderModule extends Module {
constructor(client: CookiecordClient) {
super(client);
}
@listener({ event: 'ready' })
async loadPrevReminders() {
const reminders = await Reminder.find();
for (const rem of reminders) {
setTimeout(
() =>
this.sendReminder(rem).catch(err => {
throw err;
}),
rem.date - Date.now(),
);
}
}
@command({
single: true,
description: 'Get me to remind you about anything in the future',
})
async remind(msg: Message, args: string) {
// cookiecord can't have args with spaces in them (yet)
const splitArgs = args.split(' ').filter(x => x.trim().length !== 0);
if (splitArgs.length == 0) return await msg.channel.send(syntaxWarning);
const maxDur = parse('10yr');
const dur = parse(splitArgs.shift()!); // TS doesn't know about the length check
if (!dur || !maxDur || dur > maxDur)
return await msg.channel.send(invalidDuration);
const reminder = new Reminder();
reminder.userID = msg.author.id;
reminder.date = Date.now() + dur;
reminder.message = splitArgs.join('');
await reminder.save();
if (splitArgs.length == 0) {
await msg.channel.send(
`${okHand} set a reminder for ${prettyMs(dur)}.`,
);
} else {
await msg.channel.send(
`${okHand} set a reminder for ${prettyMs(
dur,
)} to remind you about "${splitArgs.join('')}".`,
);
}
// set the timeout, bot will take all the reminders from the DB on init if interrupted while a reminder is still pending
setTimeout(
() =>
this.sendReminder(reminder).catch(err => {
throw err;
}),
dur,
);
}
async sendReminder(rem: Reminder) {
const user = await this.client.users.fetch(rem.userID);
try {
if (rem.message.length == 0) {
user.send(':clock1: hey! you asked me to remind you.');
} else {
user.send(
`:clock1: hey! you asked me to remind you about "${rem.message}"`,
);
}
} catch (e) {
// Fail silently, as the user might have their DMs off.
}
await rem.remove();
}
}