I'm in the middle of (semi-successfully) learning how to use the new slash commands in Discord.js, a node.js module for interacting with Discord's bot API. As far as I can see, this is strictly a problem with the base Javascript code, and no knowledge of Discord.js is required to help my rather annoying little problem!
The code is for retrieving event files and executing them. The issue is that whenever the interactionCreate.js file is executed, the interaction argument seems to be undefined.
If needed, the file structure is as follows:
project-folder/
├── index.js
├── events/
└── interactionCreate.js
Here's index.js:
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
...and here's interactionCreate.js:
module.exports = {
name: 'interactionCreate',
async execute(client, interaction) {
if (!interaction.isCommand()) 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: 'There was an error while executing this command.', ephemeral: true });
}
},
};
I'm not entirely sure if this is relevant, but here's what the code looks like when it isn't in seperate modules. Of course, the event file retrieval isn't neccessary here.
index.js (before modularisation):
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) 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: 'There was an error while executing this command.', ephemeral: true });
}
});
Again, I'm unsure if this is needed, but here's one of the error messages I'd receive.
C:\path\to\files\project-folder\events\interactionCreate.js:4
if (!interaction.isCommand()) return;
^
TypeError: Cannot read properties of undefined (reading 'isCommand')
I'm not too experienced with asking questions on here, so if you need anything else, let me know! I'll happily either reply to your response or update the question. Thanks a lot!
Your declaration is like this:
async execute(client, interaction) {
//...
}
And the interactionCreate event only provides 1 parameter (interaction). If all your events would be in a client, rest, of, the, args parameter order, this would be the approach:
if (event.once) {
client.once(event.name, (...args) => event.execute(client, ...args));
} else {
client.on(event.name, (...args) => event.execute(client, ...args));
}