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