Skip to content

Instantly share code, notes, and snippets.

@Raay109
Created August 24, 2024 09:31
Index.js (DC Bot)
const { Client, REST, GatewayIntentBits, Routes, Events, Collection, ChannelType, PermissionsBitField } = require('discord.js');
const fs = require('node:fs');
const path = require('node:path');
const client = require('./commands/client.js');
const originalConsoleLog = console.log;
let lastLogMessage = '';
console.log = function(message) {
lastLogMessage = message;
originalConsoleLog.apply(console, arguments);
};
const rest = new REST({ version: '10' }).setToken(process.env.BOTTOKEN);
const commands = [];
client.commands = new Collection();
function getCommandFiles(dir) {
const files = fs.readdirSync(dir, { withFileTypes: true });
for (const file of files) {
const filePath = path.join(dir, file.name);
if (file.isDirectory()) {
getCommandFiles(filePath);
} else if (file.isFile() && file.name.endsWith('.js')) {
const command = require(filePath);
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}
}
getCommandFiles(path.join(__dirname, 'commands'));
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
const data = await rest.put(
Routes.applicationCommands(process.env.BOTCLIENTID),
{ body: commands },
);
console.log(`${data.length} syncronisirt`);
if (lastLogMessage === `${data.length} syncronisirt`) {
client.login(process.env.BOTTOKEN);
}
} catch (error) {
console.error(error);
}
})();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
} else {
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment