Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
152 lines (136 loc) · 5.28 KB
/
Copy pathindex.js
File metadata and controls
152 lines (136 loc) · 5.28 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
const path = require("path");
const fs = require("fs");
const discord = require("discord.js");
require("dotenv").config();
const prisma = require("./utils/prisma.js");
const api = require("./api/api.js");
const client = new discord.Client({
intents: [
discord.GatewayIntentBits.Guilds,
discord.GatewayIntentBits.GuildMembers,
discord.GatewayIntentBits.GuildMessages,
discord.GatewayIntentBits.MessageContent,
],
});
const commands = [];
const buttons = [];
const modals = [];
function loadModules(dir) {
return fs
.readdirSync(path.join(__dirname, dir))
.filter((file) => file.endsWith(".js"))
.map((file) => ({ file, data: require(path.join(__dirname, dir, file)) }));
}
for (const { data: event } of loadModules("event")) {
console.log(new Date().toLocaleString(), `Event registriert: ${event.name}`);
const listener = (...args) =>
Promise.resolve(event.execute(...args)).catch((err) =>
console.error(`Fehler im Event ${event.name}:`, err)
);
if (event.once) client.once(event.name, listener);
else client.on(event.name, listener);
}
// "ready" on older discord.js versions, "clientReady" on newer ones
client.once(discord.Events.ClientReady, async () => {
console.log(new Date().toLocaleString(), "Ready!");
// Columns added after the initial schema; the start script only runs `prisma generate`
for (const statement of [
`ALTER TABLE "Build" ADD COLUMN IF NOT EXISTS "reference_type" TEXT;`,
`ALTER TABLE "Build" ADD COLUMN IF NOT EXISTS "reference_link" TEXT;`,
`ALTER TABLE "Build" ADD COLUMN IF NOT EXISTS "judge_details" JSONB;`,
`ALTER TABLE "Build" ADD COLUMN IF NOT EXISTS "extra_info" TEXT;`,
// Omitted list columns are stored as NULL, which breaks `judges = '{}'` and cardinality() checks
`ALTER TABLE "Build" ALTER COLUMN "judges" SET DEFAULT '{}';`,
`ALTER TABLE "Build" ALTER COLUMN "images" SET DEFAULT '{}';`,
`UPDATE "Build" SET "judges" = '{}' WHERE "judges" IS NULL;`,
`UPDATE "Build" SET "images" = '{}' WHERE "images" IS NULL;`,
`CREATE TABLE IF NOT EXISTS "Activity" (
"id" SERIAL PRIMARY KEY,
"created_at" TIMESTAMPTZ(1) NOT NULL DEFAULT now(),
"type" TEXT NOT NULL,
"build_id" INTEGER,
"user_id" BIGINT,
"actor" TEXT,
"points" DOUBLE PRECISION,
"details" TEXT
);`,
]) {
await prisma.$executeRawUnsafe(statement).catch((err) =>
console.error("Fehler bei der Datenbank-Migration:", err.message)
);
}
for (const { data } of loadModules("commands")) commands.push(data);
// Bulk overwrite, so removed commands also disappear from Discord
try {
await client.application.commands.set(commands.map((c) => c.command));
console.log(
new Date().toLocaleString(),
`Commands registriert: ${commands.map((c) => `/${c.command.name}`).join(", ")}`
);
} catch (err) {
console.error("Fehler beim Registrieren der Commands:", err);
}
for (const { data } of loadModules("buttons")) buttons.push(data);
for (const { data } of loadModules("modals")) modals.push(data);
for (const { file, data } of loadModules("schedule")) {
console.log(
new Date().toLocaleString(),
`Schedule registriert: ${file} (${data.time}ms)`
);
const run = () =>
Promise.resolve(data.run(client, prisma)).catch((err) =>
console.error(`Fehler im Schedule ${file}:`, err)
);
run();
setInterval(run, data.time);
}
// A failing API (e.g. port in use) must not take the bot down with it
await api.start().catch((err) => console.error("Fehler beim Starten der API:", err));
});
async function replyWithError(interaction, content) {
try {
if (interaction.deferred || interaction.replied) {
await interaction.followUp({ content, ephemeral: true });
} else {
await interaction.reply({ content, ephemeral: true });
}
} catch (err) {
console.error("Fehlermeldung konnte nicht gesendet werden:", err.message);
}
}
client.on("interactionCreate", async (interaction) => {
if (interaction.isAutocomplete()) {
const command = commands.find(
(c) => c.command.name === interaction.commandName
);
if (!command || !command.autocomplete) return;
try {
await command.autocomplete(client, interaction, prisma);
} catch (error) {
console.error(error);
}
return;
}
let handler;
let errorMessage;
if (interaction.isChatInputCommand()) {
handler = commands.find((c) => c.command.name === interaction.commandName);
errorMessage = "Beim Ausführen dieses Befehls ist ein Fehler aufgetreten!";
} else if (interaction.isButton()) {
handler = buttons.find((b) => interaction.customId.startsWith(b.button.name));
errorMessage = "Beim Ausführen dieser Schaltfläche ist ein Fehler aufgetreten!";
} else if (interaction.isModalSubmit()) {
handler = modals.find((m) => interaction.customId.startsWith(m.modal.name));
errorMessage = "Beim Ausführen dieses Formulars ist ein Fehler aufgetreten!";
}
if (!handler) return;
try {
await handler.run(client, interaction, prisma);
} catch (error) {
console.error(error);
await replyWithError(interaction, errorMessage);
}
});
// Log instead of crashing the whole bot
process.on("unhandledRejection", (err) => console.error("Unbehandelter Fehler:", err));
client.login(process.env.BOT_TOKEN);