Search code examples
javascriptnode.jsdiscorddiscord.jstypeerror

Discord.js Cannot read properties of undefined (reading 'execute')


my code in main file is this:

const { Client, IntentsBitField, Collection, intents, SlashCommandBuilder } = require('discord.js')
const { TOKEN, PREFIX } = require('./config.json')
const fs = require('fs');
const client = new Client({
    intents: [
        IntentsBitField.Flags.Guilds,
        IntentsBitField.Flags.GuildMembers,
        IntentsBitField.Flags.GuildMessages,
        IntentsBitField.Flags.MessageContent,
    ],
});

//Command Handler
const commands = new Collection();
const files = fs
    .readdirSync(`./commands`)
    .filter((file) => file.endsWith(".js"))
for (const file of files) {
    const command = require(`./commands/${file}`)
    commands.set(command.name, command);
}

//Online
client.on('ready', () => {
    console.log(`\n ======= "${client.user.tag}" is online`)
    console.log(` ======= Client ID : ${client.user.id}`)
})

//Message Events
client.on('messageCreate', message => {
    //PREFIX
    if (!message.content.startsWith(PREFIX) || message.author.bot) return;
    let args = message.content.substring(PREFIX.length).trim().split(" ")
    

    if (!args[0]) return;

    //Handling
    commands.get(args[0]).execute(message, args)
})

//Slash Command Events
client.on('interactionCreate', interaction => {
    if (!interaction.isCommand()) return;
    const { commandName } = interaction;

    //Send Message
    if (commandName === 'ping') {
        interaction.reply('pong')
    }
})
//Client Token
client.login(TOKEN)

place the error code:

//Message Events
client.on('messageCreate', message => {
    //PREFIX
    if (!message.content.startsWith(PREFIX) || message.author.bot) return;
    let args = message.content.substring(PREFIX.length).trim().split(" ")
    

    if (!args[0]) return;

    //Handling
    commands.get(args[0]).execute(message, args)
})

and output i get this error:

          commands.get(args[0]).execute(message, args)
                                   ^
TypeError: Cannot read properties of undefined (reading 'execute')

when I enter the prefix but the message content doesn't match what I made, it will error and close. I want to fix it and run normally can someone help with this code?

Details: Runtime: Node.JS v16.16.0 Discord.JS Version: 14.9.0


Solution

  • The issue here is with your guard statement, you're checking args[0] is defined before executing. But what you actually want is to check commands.get(args[0]).

    You can handle this by doing the following:

    const commandsToExec = commands.get(args[0]);
    
    if (!commandsToExec) return;
    
    //Handling
    commandsToExec.execute(message, args)
    

    This should safely not crash in the case that there aren't any correct args supplied.