Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

241
Visualizações
Discord.JS Command Handler not working or updating

I am trying to add a command handler to my bot, however, only one command is working and no matter how I change the command, it does not update. Here is my code.

This is at the top underneath the packages and above the on ready code.

fs.readdir('./commands/', (_err, files) => {
 files.forEach((file) => {
  if (!file.endsWith('.js')) return;
   bot.commands = new Discord.Collection()
  let command = require(`./commands/${file}`); // access all details though this variable
  bot.commands.set(command.name, command);
  console.log(`👌 Command loaded: ${command.name}`);
 });
});

This is in the resources command

const Discord = require("discord.js")
const fs = require("fs")

module.exports = {
 name: 'resources',
 // any other details you might like, such as:
 description: 'Shows resources',
 execute(bot, message, args, prefix) {
  // the actual function
    let resourceText = fs.readFileSync('txtfiles/resources.txt', 'utf8')
    message.suppressEmbeds(true)
    message.channel.send(resourceText)
    
 }
 }

The resources command works just fine, but the ship command does not.

const Discord = require("discord.js")
const fs = require("fs")

module.exports = {
 name: 'ship',
 // any other details you might like, such as:
 description: 'ships people',
 execute(bot, message, args, prefix) {
  // the actual function
    message.channel.send("please work")
    
 }
 }

And this is in the "on messageCreate" thing

if(cmd===`${prefix}resources`){bot.commands.get('resources').execute(bot, message, args, prefix);}

if(cmd===`${prefix}ship`){bot.commands.get('ship').execute(bot, message, args, prefix);}

I have tried putting these underneath the packages

delete require.cache['./index.js'];
delete require.cache[require.resolve('./index.js')]

However, I am getting this error message Unhandled promise rejection: TypeError: Cannot read properties of undefined (reading 'execute')

The resources command works just fine, even if we delete all the code in the file, and the ship command does not work at all.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

So rather than put an if (cmd === block for every command, try using a dynamic one that won't require you to update your messageCreate section, every time you add a new command or delete one.

messageCreate section:

bot.on('messageCreate', async message => {
    if (message.author.bot) return
    if (!message.content.startsWith(config.prefix)) return
    const args = message.content.slice(config.prefix.length).trim().split(/ +/)
    const command = args.shift().toLowerCase()
    const cmd = bot.commands.get(command)

    if (!cmd) {
        console.log("Unknown command")
        return
    } else {
        cmd.run(bot, message, args)
    }
})

Then you'll have to update your existing command that does work to match this style but just make any new ones like this:

module.exports = {
    name: 'Command Name',
    description: 'Command description',
    run: async (bot, message, args) => {
        // the actual function
    }
}

So your ships command would look like this

module.exports = {
    name: 'ships',
    description: 'ships people',
    run: async (bot, message, args) => {
        message.channel.send({
            content: 'Please work'
        })
    }
}

I'd change your command collection to this

bot.commands = new Discord.Collection()
const commandList = []

const commands = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'))
for (const file of commands) {
    const command = require(`./commands/${file}`)
    commandList.push(`${file.split('.'[0])}`)
    bot.commands.set(command.name, command)
}
 console.log(`👌 Commands loaded: ${commandList}`)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda