-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathschedule.ts
124 lines (99 loc) · 2.63 KB
/
schedule.ts
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
import { database } from './firebase'
import Commando from 'discord.js-commando';
import dayjs from 'dayjs';
import CONSTANTS from './constants';
import EventEmmiter from 'eventemitter3'
import * as chrono from 'chrono-node'
import { TextChannel } from 'discord.js';
type Timeout = ReturnType<typeof setTimeout>
interface Schedule {
message: string;
schedule: Date;
timer: Timeout | undefined;
ref: string;
channel: string;
}
class Scheduler extends EventEmmiter {
static instance: Scheduler
schedules: Schedule[] = [];
client: Commando.CommandoClient | undefined;
constructor() {
super()
}
setClient(client: Commando.CommandoClient) {
this.client = client
}
getInstance() {
return Scheduler.instance
}
recalculate() {
this.schedules.forEach((schedule) => {
schedule.timer = setTimeout(async () => {
if (this.client) {
console.log('schedule.channel', schedule.channel)
const channel = this.client.channels.cache.get(schedule.channel) as TextChannel
try {
await channel.send(schedule.message)
await database.ref(`schedules/${schedule.ref}`).remove()
} catch (e) {
console.error(e)
}
}
}, dayjs(schedule.schedule).diff(dayjs(), 'milliseconds'))
})
}
clearAll() {
this.schedules.forEach((schedule) => {
if (schedule.timer) {
clearTimeout(schedule.timer)
}
})
}
async fetchSchedules() {
database.ref('schedules').on('value', (snapshot) => {
const schedules = snapshot.val();
this.clearAll()
if (!schedules) {
this.schedules = []
return
}
const scheds = Object.entries(schedules)
this.schedules = []
scheds.forEach(([key, sched]: [string, any]) => {
console.log('Found schedule on ' + dayjs(sched.schedule).format('DD/MM/YYYY HH:mm:ss'))
this.schedules.push({
message: sched.message,
schedule: dayjs(sched.schedule).toDate(),
timer: undefined,
ref: key,
channel: sched.channel
})
})
this.recalculate()
})
}
async add(schedule: string, message: string, channel: string): Promise<{ date: Date, id: string}> {
const date = chrono.parseDate(schedule)
if (!date) {
throw new Error('Invalid date')
}
if (dayjs(date).isBefore(dayjs())) {
throw new Error('Date is in the past')
}
const ref = database.ref('schedules')
var newChildRef = await ref.push();
const setData = {
schedule: date.getTime(),
message,
channel
}
console.log('setData', setData)
await newChildRef.set(setData);
return { date, id: newChildRef.key }
}
remove(id: string) {
return database.ref('schedules/' + id).remove()
}
}
const _scheduler = new Scheduler()
export const scheduler = _scheduler