aboutsummaryrefslogtreecommitdiff
path: root/src/tasks/feature/handleReminders.ts
blob: afe6dd6ca14406aa719ca2b36b18251bce2db98f (plain)
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
import { BotTask, dateDelta, format, Reminder, Time } from '#lib';
import { Op } from 'sequelize';

export default class HandlerRemindersTask extends BotTask {
	public constructor() {
		super('handlerReminders', {
			delay: 30 * Time.Second,
			runOnStart: true
		});
	}

	public async exec() {
		const expiredEntries = await Reminder.findAll({
			where: {
				expires: {
					[Op.lt]: new Date(Date.now() + 30 * Time.Second) // Find all rows with an expiry date before 30 seconds from now
				},
				notified: false
			}
		});

		void this.client.logger.verbose(
			`handlerReminders`,
			`Queried reminders, found <<${expiredEntries.length}>> expired reminders.`
		);

		for (const entry of expiredEntries) {
			setTimeout(() => {
				void this.client.users
					.send(
						entry.user,
						`The reminder you set ${dateDelta(entry.created)} ago has expired: ${format.bold(entry.content)}\n${entry.messageUrl}`
					)
					.catch(() => false);
				void entry.update({ notified: true });
			}, entry.expires.getTime() - new Date().getTime());
		}
	}
}