Event handling

Added the event handling from the discord.js guide to a more organized and dynamic bot.
This commit is contained in:
Gustavo
2021-08-16 21:05:23 -03:00
parent e0afd91470
commit deca5e8d31
3 changed files with 46 additions and 19 deletions

6
events/client/ready.js Normal file
View File

@@ -0,0 +1,6 @@
module.exports = {
name: 'ready',
async execute() {
console.log('bot ready!');
},
};

View File

@@ -0,0 +1,23 @@
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
if (!interaction.isCommand() || !client.commands.has(interaction.commandName)) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
}
catch (error) {
console.error(error);
await interaction.reply({
content: 'A error occur while trying to execute the command.\n```' + error + '```',
ephemeral: true,
});
}
},
};

View File

@@ -23,8 +23,8 @@ for (const folder of commandFolders) {
for (const file of commandFiles) {
const cmd = require(`./commands/${folder}/${file}`);
commands.push(cmd.data.toJSON());
const command = require(`./commands/${folder}/${file}`);
commands.push(command.data.toJSON());
}
}
@@ -46,30 +46,28 @@ const rest = new REST({ version: '9' }).setToken(token);
catch (error) {
console.error(error);
}
})();
client.on('ready', async () => {
const eventFolders = fs.readdirSync('./events');
console.log('Bot ready!');
for (const folder of eventFolders) {
});
const eventFiles = fs.readdirSync(`./events/${folder}`).filter(file => file.endsWith('.js'));
client.login(token);
for (const file of eventFiles) {
client.on('interactionCreate', async interaction => {
const event = require(`./events/${folder}/${file}`);
if (!interaction.isCommand() || !client.commands.has(interaction.commandName)) return;
if(event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
}
else {
client.on(event.name, (...args) => event.execute(...args, client));
}
const command = client.commands.get(interaction.commandName);
if(!command) return;
try {
await command.execute(interaction);
}
catch (error) {
console.error(error);
await interaction.reply({ content: 'A error occur while trying to execute the command.\n```' + error + '```', ephemeral: true });
}
});
}
client.login(token);