-
Notifications
You must be signed in to change notification settings - Fork 11
/
discord.ts
303 lines (267 loc) · 8.02 KB
/
discord.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import { load } from "https://deno.land/[email protected]/dotenv/mod.ts";
import {
Bot,
createBot,
Intents,
PresenceStatus,
} from "npm:@discordeno/[email protected]";
interface ServerStats {
lastStatsHeartbeat: number;
clientSHAs: Record<string, boolean>;
onlineCount: number;
gamesCompleted: number;
pid: number;
}
enum ActivityState {
OnlinePlayers,
UniquePlayers,
GamesCompleted,
}
const env = await load();
let botReady = false;
let anchorOnline = false;
let restarting = false;
let bot: Bot;
let activtiyState = ActivityState.OnlinePlayers;
let stats: ServerStats = {
lastStatsHeartbeat: 0,
clientSHAs: {},
onlineCount: 0,
gamesCompleted: 0,
pid: 0,
};
(async () => {
try {
if (!env.TOKEN) {
console.warn("No bot token provided, continuing without bot");
return;
}
bot = createBot({
token: env.TOKEN,
intents: Intents.GuildPresences | Intents.Guilds,
events: {
ready: () => {
console.log("Bot online");
botReady = true;
},
},
});
bot.transformers.desiredProperties.message.id = true;
bot.transformers.desiredProperties.user.id = true;
bot.transformers.desiredProperties.channel.id = true;
bot.transformers.desiredProperties.message.author = true;
bot.transformers.desiredProperties.message.editedTimestamp = true;
bot.transformers.desiredProperties.message.thread = true;
await bot.start();
} catch (error) {
console.warn("An error occured while starting the bot", error);
console.warn("Continuing without bot functionality");
}
})();
(async function refreshStats() {
try {
const statsString = await Deno.readTextFile("./stats.json");
stats = JSON.parse(statsString);
} catch (error) {
console.error("An error occured while reading stats.json", error);
}
setTimeout(refreshStats, 1000 * 5);
})();
(async function refreshStatus() {
activtiyState += 1;
if (activtiyState > ActivityState.GamesCompleted) {
activtiyState = ActivityState.OnlinePlayers;
}
if (!botReady) {
return setTimeout(refreshStatus, 1000 * 10);
}
try {
let status: keyof typeof PresenceStatus = "online";
let activtiy = "";
switch (activtiyState) {
case ActivityState.OnlinePlayers:
activtiy = `/ ${stats.onlineCount} Online Now`;
break;
case ActivityState.UniquePlayers:
activtiy = `/ ${Object.keys(stats.clientSHAs).length} Unique Players`;
break;
case ActivityState.GamesCompleted:
default:
activtiy = `/ ${stats.gamesCompleted} Games Complete`;
break;
}
if (restarting) {
status = "idle";
activtiy = "/ Restarting";
} else if (!anchorOnline) {
status = "dnd";
activtiy = "/ Offline";
}
await bot!.gateway.editBotStatus({
status: status,
activities: [
{
name: activtiy,
type: 0,
},
],
});
} catch (error) {
console.error("An error occured while refreshing the bot status", error);
}
setTimeout(refreshStatus, 1000 * 10);
})();
(async function autoRestart() {
try {
// Heartbeat occured in last 30 seconds
if (stats.lastStatsHeartbeat > Date.now() - 1000 * 30) {
if (restarting) {
console.log("Server is back online");
if (botReady && env.RESTART_CHANNEL) {
try {
bot!.helpers.sendMessage(env.RESTART_CHANNEL, {
content: "Anchor server back online!",
});
} catch (error) {
console.error("An error occured while notifying of restart", error);
}
}
}
anchorOnline = true;
restarting = false;
return setTimeout(autoRestart, 1000 * 10);
}
if (restarting) {
console.log("Server is restarting, waiting for it to come back up");
return setTimeout(autoRestart, 1000 * 10);
}
anchorOnline = false;
restarting = true;
console.log("Server is down, notifying and restarting");
if (botReady && env.RESTART_CHANNEL) {
try {
let message = "Anchor server is down, attempting to restart...";
if (env.RESTART_MENTION) {
message += ` CC <@${env.RESTART_MENTION}>`;
}
bot!.helpers.sendMessage(env.RESTART_CHANNEL, {
content: message,
});
} catch (error) {
console.error("An error occured while notifying of restart", error);
}
}
try {
// Write screen config so that it uses a fresh log file
await Deno.writeTextFile(
"./.screenrc",
`logfile "logs/${
new Date().toLocaleString().replace(/[\s,:/]/g, "-")
}.log"
deflog on
logfile flush 1`,
);
} catch (error) {
console.error("An error occured while writing screen config", error);
}
if (stats.pid) {
try {
Deno.kill(stats.pid, "SIGINT");
} catch (_) {
console.log("Failed to kill server, probably already dead");
}
}
const command = new Deno.Command(
"screen",
{
args: [
"-c",
"./.screenrc",
"-dmLS",
"anchor",
"deno",
"run",
"--allow-all",
"mod.ts",
],
env: {
QUIET: "TRUE",
},
stdout: "null",
stderr: "null",
stdin: "null",
},
);
const process = command.spawn();
process.unref();
} catch (error) {
console.error("An error occured while attempting to restart server", error);
}
setTimeout(autoRestart, 1000 * 10);
})();
// This channel is made up of messages that have thread channels associated with them
// If a message has not been sent in the last 6 hours, the thread channel is deleted
(async function pruneLFGChannel() {
if (!env.LFG_CHANNEL) {
console.warn("No LFG channel provided, not beginning pruning process");
return;
}
if (!botReady) {
return setTimeout(pruneLFGChannel, 1000 * 60);
}
try {
const channel = await bot!.helpers.getChannel(env.LFG_CHANNEL);
if (!channel) {
console.warn("LFG channel does not exist, not beginning pruning process");
return;
}
const lfgMessages = await bot!.helpers.getMessages(env.LFG_CHANNEL, {
limit: 100,
});
lfgMessages.forEach(async (lfgMessage) => {
// Ignore messages that are not 5 minutes old yet or that are the info message
if (
lfgMessage.timestamp > Date.now() - 1000 * 60 * 5 ||
lfgMessage.id.toString() === env.LFG_INFO_MESSAGE
) {
return;
}
// If the user has not created the thread yet, delete the message
if (!lfgMessage.thread?.id) {
await bot!.helpers.deleteMessage(env.LFG_CHANNEL, lfgMessage.id);
return;
}
// fetch the last 2 messages in the thread
const threadMessages = await bot!.helpers.getMessages(
lfgMessage.thread!.id,
{ limit: 2 },
);
// Filter out messages from the bot
const lastThreadMessage = threadMessages.find((m) =>
m.author.id !== bot!.id
);
// If there is no message, or the last message was sent more than 6 hours ago, delete the original message and thread
if (
!lastThreadMessage ||
lastThreadMessage.timestamp < Date.now() - 1000 * 60 * 60 * 6
) {
await bot!.helpers.deleteMessage(env.LFG_CHANNEL, lfgMessage.id);
await bot!.helpers.deleteChannel(lfgMessage.thread!.id);
return;
}
// If the message is more than 5 hours old, and the bot didn't send the last message, warn the user that the thread will be deleted soon
if (
lastThreadMessage.timestamp < Date.now() - 1000 * 60 * 60 * 5 &&
threadMessages[0].author.id !== bot!.id
) {
await bot!.helpers.sendMessage(lfgMessage.thread!.id, {
content:
"This thread will be deleted in 1 more hour of inactivity. Please reply to this thread to keep it alive.",
});
}
});
} catch (error) {
console.error("An error occured while pruning LFG channel", error);
}
setTimeout(pruneLFGChannel, 1000 * 60);
})();