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