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