-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathapp.ts
More file actions
242 lines (204 loc) · 8.6 KB
/
app.ts
File metadata and controls
242 lines (204 loc) · 8.6 KB
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
import { GatewayIntentBits, Partials, Client } from "discord.js";
import * as sentry from "@sentry/node";
import { readConfig, databasePath, args } from "#/service/config.ts";
import log from "#log";
import * as kysely from "#/storage/db/db.ts";
import type { ReactionHandler } from "#/handler/ReactionHandler.ts";
import messageDeleteHandler from "#/handler/messageDeleteHandler.ts";
import { woisVoteReactionHandler } from "#/commands/woisvote.ts";
import * as voiceStateService from "#/service/voiceState.ts";
import roleAssignerHandler from "#/handler/reaction/roleAssignerHandler.ts";
import pollReactionHandler from "#/handler/reaction/pollReactionHandler.ts";
import logEmotesReactionHandler from "#/handler/reaction/logEmotesReactionHandler.ts";
import quoteReactionHandler from "#/handler/reaction/quoteHandler.ts";
import {
handleInteractionEvent,
loadCommands,
messageCommandHandler,
registerAllApplicationCommandsAsGuildCommands,
} from "#/handler/commandHandler.ts";
import * as guildMemberHandler from "#/handler/guildMemberHandler.ts";
import deleteThreadMessagesHandler from "#/handler/messageCreate/deleteThreadMessagesHandler.ts";
import { handlePresenceUpdate } from "#/handler/presenceHandler.ts";
import { createBotContext, type BotContext } from "#/context.ts";
import { ehreReactionHandler } from "#/commands/ehre.ts";
import * as terminal from "#/utils/terminal.ts";
import * as dateUtils from "#/utils/dateUtils.ts";
import * as cronService from "#/service/cron.ts";
const env = process.env;
const release =
env.RELEASE_IDENTIFIER && env.BUILD_NUMBER
? `csz-bot@0.0.0-build.${env.BUILD_NUMBER}+commit.${env.RELEASE_IDENTIFIER}`
: undefined;
{
const prodMode = env.NODE_ENV === "production" ? terminal.highlightWarn(" prod mode ") : "";
const cszBot = terminal.highlight(" CSZ Bot ");
const year = dateUtils.zonedNow().year;
console.log();
console.log(" ┌───────────┐");
console.log(` │ ${cszBot} │ Copyright (c) ${year} Users of the CSZ`);
console.log(" └───────────┘");
console.log(` ${prodMode} ${release ? `(${release})` : ""} log level: ${log.level}`);
}
log.info(`Bot starting up...${release ? ` (release: ${release})` : ""}`);
const config = await readConfig();
if (config.sentry?.dsn) {
sentry.init({
dsn: config.sentry.dsn,
environment: env.NODE_ENV,
release,
tracesSampleRate: config.sentry?.tracesSampleRate ?? 1,
});
}
if (!config.auth.clientId || !config.auth.token) {
log.error(
"No bot token found in config. Make sure to set `auth.clientId` and `auth.token` in `config.json`",
);
process.exit(1);
}
await kysely.connectToDb(databasePath);
const client = new Client({
partials: [Partials.Message, Partials.Reaction, Partials.User],
allowedMentions: {
parse: ["users"],
repliedUser: true,
},
intents: [
GatewayIntentBits.DirectMessages,
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildModeration,
GatewayIntentBits.GuildExpressions,
GatewayIntentBits.GuildIntegrations,
GatewayIntentBits.GuildInvites,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMessageTyping,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildWebhooks,
],
});
/**
* All of them will be executed in the given order, regardless of their result or if they throw an error.
*/
const reactionHandlers: ReactionHandler[] = [
pollReactionHandler,
logEmotesReactionHandler,
quoteReactionHandler,
ehreReactionHandler,
woisVoteReactionHandler,
roleAssignerHandler,
];
process.on("unhandledRejection", err => log.error(err, "Unhandled rejection"));
process.on("uncaughtException", (err, origin) =>
log.error(err, `Uncaught exception (origin: ${origin})`),
);
process.once("SIGTERM", signal => {
log.fatal(`Received SIGTERM: ${signal}`);
process.exit(1);
});
process.once("exit", code => {
const _ = client.destroy();
const __ = kysely.disconnectFromDb();
log.warn(`Process exited with code: ${code}`);
});
let botContext: BotContext;
login().then(
async client => {
log.info(`Logged in as ${client.user.tag}`);
log.info(
`Got ${client.users.cache.size} users, in ${client.channels.cache.size} channels of ${client.guilds.cache.size} guilds`,
);
log.info(`Prefixes: "${config.prefix.command}" and "${config.prefix.modCommand}"`);
client.user.setActivity(config.activity);
try {
botContext = await createBotContext(client);
await loadCommands(botContext);
await cronService.schedule(botContext);
// When the application is ready, slash commands should be registered
await registerAllApplicationCommandsAsGuildCommands(botContext);
} catch (err) {
sentry.captureException(err);
log.error(err, "Error in `ready` handler");
process.exit(1);
}
log.info("Registering main event handlers...");
client.on("messageCreate", m => messageCommandHandler(m, botContext));
client.on("messageCreate", m => deleteThreadMessagesHandler(m, botContext));
client.on("guildMemberAdd", m => guildMemberHandler.added(botContext, m));
client.on("guildMemberRemove", m => guildMemberHandler.removed(botContext, m));
client.on("interactionCreate", i => handleInteractionEvent(i, botContext));
client.on("voiceStateUpdate", (old, next) =>
voiceStateService.checkVoiceUpdate(old, next, botContext),
);
client.on("messageDelete", async message => {
if (!message.inGuild()) {
return;
}
await messageDeleteHandler(message, botContext).catch(err => {
log.error(err, `[messageDelete] Error for ${message.id}`);
sentry.captureException(err);
});
});
log.info("Bot successfully started");
if (args.values["dry-run"]) {
log.info("--dry-run was specified, shutting down");
process.exit(0);
}
if (botContext.sendWelcomeMessage) {
await botContext.textChannels.hauptchat.send(
`Hallo, ich wurde gerade gestartet!\nMeine Präfixe sind: \`${botContext.prefix.command}\`/\`${botContext.prefix.modCommand}\``,
);
log.info("Sent welcome message");
}
},
err => {
log.error(err, "Token login was not successful");
log.error("Shutting down due to incorrect token...");
process.exit(1);
},
);
client.on("guildCreate", guild =>
log.info(`New guild joined: ${guild.name} (id: ${guild.id}) with ${guild.memberCount} members`),
);
client.on("guildDelete", guild => log.info(`Deleted from guild: ${guild.name} (id: ${guild.id}).`));
client.on("error", e => log.error(e, "Discord Client Error"));
client.on("warn", w => log.warn(`Discord Client Warning: "${w}"`));
client.on("rateLimit", d => log.error(d, "Discord client rate limit reached"));
client.on("invalidated", () => log.debug("Client invalidated"));
client.on("messageReactionAdd", async (event, user) => {
const [entireEvent, entireUser] = await Promise.all([event.fetch(), user.fetch()]);
for (const handler of reactionHandlers) {
await handler.execute(entireEvent, entireUser, botContext, false).catch(err => {
log.error(err, `Handler "${handler.displayName}" failed during "messageReactionAdd".`);
sentry.captureException(err);
});
}
});
client.on("messageReactionRemove", async (event, user) => {
const [entireEvent, entireUser] = await Promise.all([event.fetch(), user.fetch()]);
for (const handler of reactionHandlers) {
await handler.execute(entireEvent, entireUser, botContext, true).catch(err => {
log.error(
err,
`Handler "${handler.displayName}" failed during "messageReactionRemove".`,
);
sentry.captureException(err);
});
}
});
client.on("presenceUpdate", async (oldPresence, newPresence) => {
try {
await handlePresenceUpdate(botContext, oldPresence, newPresence);
} catch (cause) {
log.warn(cause, "Exception during `presenceUpdate`.");
}
});
function login() {
return new Promise<Client<true>>(resolve => {
client.once("clientReady", resolve);
return client.login(config.auth.token);
});
}