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
|
import {
ChannelType,
Client,
CommandInteraction,
Events,
GatewayIntentBits,
REST,
Routes,
} from "discord.js";
import { buttonCommands, ensureUnsolvedTag, slashCommands, getCtfForum } from "./commands.ts";
function requireEnv(key: string): string {
let value = process.env[key];
if (!value) {
throw new Error(`Missing ${key} environment variable.`);
}
return value;
}
let token = requireEnv("DISCORD_TOKEN");
let clientId = requireEnv("DISCORD_CLIENT_ID");
let guildId = requireEnv("DISCORD_GUILD_ID");
let client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] });
let rest = new REST({ version: "10" }).setToken(token);
async function registerSlashCommands() {
await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
body: slashCommands.map(command => command.slashCommand.toJSON()),
});
}
client.once(Events.ClientReady, (readyClient) => {
console.log(`Logged in as ${readyClient.user.tag}`);
});
client.on(Events.InteractionCreate, async (interaction) => {
try {
if (interaction.isChatInputCommand()) {
for (let command of slashCommands) {
if (interaction.commandName === command.slashCommand.name) {
await command.handler(interaction);
break;
}
}
} else if (interaction.isButton()) {
for (let button of Object.values(buttonCommands)) {
if (interaction.customId.startsWith(button.prefix)) {
let id = interaction.customId.slice(button.prefix.length);
await button.handler(interaction, id);
break;
}
}
}
} catch (error) {
if (error === "done") return;
if (interaction instanceof CommandInteraction) {
console.error("Error while handling interaction", error);
if (interaction.deferred || interaction.replied) {
await interaction.followUp({
content: "Something went wrong! :(",
flags: "Ephemeral",
});
} else {
await interaction.reply({
content: "Something went wrong! :(",
flags: "Ephemeral",
});
}
}
}
});
client.on(Events.ThreadCreate, async (thread) => {
try {
let forum = await getCtfForum(thread);
if (thread.ownerId === client.user?.id)
return;
let tag = await ensureUnsolvedTag(forum);
if (thread.appliedTags.includes(tag.id))
return;
await thread.setAppliedTags([...thread.appliedTags, tag.id]);
} catch (error) {
if (error === "done") return;
console.error("Failed to auto-tag thread", error);
}
});
try {
await registerSlashCommands();
await client.login(token);
} catch (error) {
console.error("Discord bot failed to start", error);
process.exit(1);
}
|