reminderService.ts

1import { Client, TextChannel } from 'discord.js'
2import { supabase } from '@/configs/supabase'
3import Logger from '@/classes/logger'
4
5export class ReminderService {
6	private client: Client
7	private interval: NodeJS.Timeout | null = null
8
9	constructor(client: Client) {
10		this.client = client
11	}
12
13	start() {
14		// Check for reminders every minute
15		this.interval = setInterval(() => this.checkReminders(), 60000)
16		Logger.log('info', 'Reminder service started', 'ReminderService')
17	}
18
19	async checkReminders() {
20		const { data: reminders, error } = await supabase
21			.from('reminders')
22			.select('*')
23			.lte('remind_at', new Date().toISOString())
24
25		if (error) {
26			Logger.log(
27				'error',
28				`Failed to fetch reminders: ${error.message}`,
29				'ReminderService',
30			)
31			return
32		}
33
34		for (const reminder of reminders) {
35			try {
36				const channel = (await this.client.channels.fetch(
37					reminder.channel_id,
38				)) as TextChannel
39				await channel.send({
40					content: `<@${reminder.user_id}>, here's your reminder: ${reminder.message}`,
41				})
42
43				// Delete the reminder after sending
44				await supabase.from('reminders').delete().eq('id', reminder.id)
45			} catch (error: any) {
46				Logger.log(
47					'error',
48					`Failed to send reminder: ${error.message}`,
49					'ReminderService',
50				)
51			}
52		}
53	}
54
55	stop() {
56		if (this.interval) {
57			clearInterval(this.interval)
58			this.interval = null
59			Logger.log('info', 'Reminder service stopped', 'ReminderService')
60		}
61	}
62}
63