Home > OS >  Why is the command handler in discord.js not working?
Why is the command handler in discord.js not working?

Time:06-28

So, I was developing a Discord Bot and wanted to use the Command Handler but there is something wrong with the for cycle.

Index.js code:

client.commands = new Collection();

const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

for(const file of commandFiles){
    const command = require(`./commands/${file}`);
    client.commands.set(command.data.name, command)
}

And this is the command code:

module.export = {
    data: {
        name: "ban",
        description: "Ban an user"
    },
    async execute(interaction){
        //Code
    }
}

The error tells me:

client.commands.set(command.data.name, command)
                                     ^

TypeError: Cannot read properties of undefined (reading 'name')
    at Object.<anonymous> (/Users/yihanzhou/Desktop/LavaBot/index.js:13:38)
    at Module._compile (node:internal/modules/cjs/loader:1112:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1166:10)
    at Module.load (node:internal/modules/cjs/loader:988:32)
    at Module._load (node:internal/modules/cjs/loader:834:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

what's wrong with this code?

CodePudding user response:

It's because of an error:

you typed module.export = {

instead of module.exports = {

here it is !

  • Related