-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdefer.ts
99 lines (95 loc) · 2.64 KB
/
defer.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
import { Client, MessageEmbed, Snowflake } from 'discord.js';
import { Model } from 'objection';
import { v4 as uuidv4 } from 'uuid';
import Discord from 'discord.js';
import * as Utils from './util_functions.js';
interface SendCancelledMessage {
type: 'SendCancelledMessage';
channel: string;
}
interface SendMessage {
type: 'SendMessage';
channel: string;
content: Discord.MessageOptions;
}
interface UpdateTmpDeletionMessage {
type: 'UpdateTmpDeletionMessage';
channel: string;
message: string;
deletionTime: string;
}
export type DeferrableAction =
| SendCancelledMessage
| UpdateTmpDeletionMessage
| SendMessage;
export class Defer extends Model {
id!: string;
data!: string;
static get tableName(): string {
return 'defers';
}
get json(): DeferrableAction {
return JSON.parse(this.data);
}
public async cancel(): Promise<void> {
await Defer.query().delete().where('id', this.id);
}
public cancelIn(ms: number): void {
setTimeout(async () => {
await Defer.query().delete().where('id', this.id);
}, ms);
}
public static async add(action: DeferrableAction): Promise<Defer> {
return await Defer.query().insert({
id: uuidv4(),
data: JSON.stringify(action),
});
}
}
export async function processDeferredOnStart(client: Client): Promise<void> {
for (const def of await Defer.query()) {
try {
const json = def.json;
if (json.type === 'SendCancelledMessage') {
(
client.channels.cache.get(
json.channel as Snowflake
) as Discord.TextChannel
).send(
Utils.embed(
'This action has been cancelled due to a bot restart, please try again',
'warning',
'Cancelled'
)
);
} else if (json.type === 'SendMessage') {
(
client.channels.cache.get(
json.channel as Snowflake
) as Discord.TextChannel
).send(json.content);
} else if (json.type === 'UpdateTmpDeletionMessage') {
(
await (
client.channels.cache.get(
json.channel as Snowflake
) as Discord.TextChannel
).messages.fetch(json.message as Snowflake)
).edit({
embeds: [
new MessageEmbed().setDescription(
`This channel will be deleted ${json.deletionTime} after this message was sent`
),
],
});
} else {
console.warn(`Unknown defer found: ${JSON.stringify(json, null, 4)}`);
}
} catch (e) {
console.error(e);
}
try {
await Defer.query().delete().where('id', def.id);
} catch {}
}
}