Discord bot to open dong files
1import {
2 ChatInputCommandInteraction,
3 Client,
4 Collection,
5 Events,
6 GatewayIntentBits,
7 MessageFlags,
8 type Interaction,
9} from "discord.js";
10// import { Glob } from "bun";
11import { glob } from "glob";
12import "dotenv/config";
13import path from "node:path";
14
15console.log(process.env)
16
17const token = process.env.token;
18if (!token) throw new Error("Token required. Please fill in TOKEN in .env");
19console.log("Token Valid!");
20
21const __dirname = import.meta.dirname;
22
23// client typing
24export type customClient = Client & {
25 // add command typing
26 commands: Collection<
27 string,
28 {
29 data: { name: string };
30 execute: (
31 interaction: ChatInputCommandInteraction & { client: customClient }
32 ) => Promise<void>;
33 }
34 >;
35};
36// new client
37const client: customClient = new Client({
38 intents: [GatewayIntentBits.Guilds],
39 // as customclient as i cannot add .commands till this is done
40}) as customClient;
41
42// setup commands
43client.commands = new Collection();
44// const commandGlob = new Glob("**/*.ts");
45for (const file of await glob("src/commands/**/*.ts", {
46 ignore: "node_modules",
47})) {
48 const command = await import("file:///" + path.join(__dirname, "..", file));
49 // check command contains all required properties
50 if (
51 "data" in command &&
52 "execute" in command &&
53 typeof command.data === "object" &&
54 command.data !== null &&
55 "name" in command.data &&
56 typeof command.data.name === "string"
57 ) {
58 client.commands.set(command.data.name, command);
59 console.log("[loaded]", file);
60 } else {
61 // log missing features
62 console.log(`[WARNING] ${file} is not a valid command!`, command);
63 }
64}
65
66// when client is ready do this once
67client.once(Events.ClientReady, (ready) => {
68 console.log(`Ready! Logged in as ${ready.user.tag}`);
69});
70
71// _interaction so we can cast types properly
72// we need access to client.commands
73// we could just do it as a global but this makes it go wherever the command goes soooo
74client.on(Events.InteractionCreate, async (_interaction) => {
75 const interaction = _interaction as Interaction & { client: customClient };
76 if (!interaction.isChatInputCommand()) return;
77 const command = interaction.client.commands.get(interaction.commandName);
78 if (!command) {
79 console.error(`No command ${interaction.commandName}`);
80 return;
81 }
82
83 try {
84 await command.execute(interaction);
85 } catch (e) {
86 console.error(e);
87 if (interaction.replied || interaction.deferred) {
88 await interaction.followUp({
89 content: "There was an error while executing this command!",
90 flags: MessageFlags.Ephemeral,
91 });
92 } else {
93 await interaction.reply({
94 content: "There was an error while executing this command!",
95 flags: MessageFlags.Ephemeral,
96 });
97 }
98 }
99});
100
101client.login(token);