summaryrefslogtreecommitdiff
path: root/index.ts
blob: 09e635787079cc8c0ec8af3927b0bfbb4957ccce (plain) (blame)
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
import {
    Client,
    DiscordAPIError,
    Events,
    GatewayIntentBits,
    PermissionFlagsBits,
    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;
}

function getInteractionErrorMessage(error: unknown): string {
    let fallback = "Something went wrong! :(";
    if (error instanceof DiscordAPIError) {
        let rawMessage = "";
        if (error.rawError &&
            typeof error.rawError === "object" &&
            "message" in error.rawError &&
            typeof (error.rawError as { message?: unknown }).message === "string"
        ) {
            rawMessage = error.rawError.message.trim();
        } else if (error.message) {
            rawMessage = error.message.trim();
        }
        if (rawMessage && error.code) {
            return `Something went wrong: ${rawMessage} (Discord code ${error.code})`;
        }
        if (rawMessage) {
            return `Something went wrong: ${rawMessage}`;
        }
        if (error.status) {
            return `Something went wrong: Discord API responded with status ${error.status}`;
        }
        return fallback;
    }
    if (error instanceof Error && error.message.trim()) {
        return `Something went wrong: ${error.message.trim()}`;
    }
    if (typeof error === "string" && error.trim()) {
        return `Something went wrong: ${error.trim()}`;
    }
    return fallback;
}

let clientId = requireEnv("DISCORD_CLIENT_ID");
let token = requireEnv("DISCORD_TOKEN");
let activity = requireEnv("ACTIVITY");
export let celebrationMessage = requireEnv("CELEBRATION_MESSAGE");

let client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] });

let rest = new REST({ version: "10" }).setToken(token);

client.once(Events.ClientReady, (c) => {
    console.log(`Logged in as ${c.user.tag}`);
});

client.on(Events.GuildAvailable, guild => {
    console.log(`Available in Guild: ${guild.name}`);
    let role = guild.roles.botRoleFor(guild.client.user);
    if (!role) {
        console.error(`Bot has no role in ${guild.name}`);
        return;
    }
    for (let permission of [
        PermissionFlagsBits.ViewChannel,
        PermissionFlagsBits.ManageChannels,
        PermissionFlagsBits.ManageRoles,
        PermissionFlagsBits.SendMessages,
        PermissionFlagsBits.SendMessagesInThreads,
        PermissionFlagsBits.CreatePublicThreads,
        PermissionFlagsBits.CreatePrivateThreads,
        PermissionFlagsBits.ManageThreads,
    ]) {
        if (!role.permissions.has(permission)) {
            console.error(`Bot is missing permission ${permission} in ${guild.name}`);
        }
    }
});

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;
        console.error("Error while handling interaction", error);
        let userMessage = getInteractionErrorMessage(error);
        if (interaction.isChatInputCommand() || interaction.isButton()) {
            if (interaction.deferred || interaction.replied) {
                await interaction.followUp({
                    content: userMessage,
                    flags: "Ephemeral",
                });
            } else {
                await interaction.reply({
                    content: userMessage,
                    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);
    }
});

await rest.put(Routes.applicationCommands(clientId), {
    body: slashCommands.map(command => command.slashCommand.toJSON()),
});

await client.login(token);

client.user?.setActivity(activity);