Error with multifolder command handler

#1

Hello. I was trying to create a multifolder command handler, when I got thir error:
error

Here is server.js code:

const botconfig = require("./botconfig.json");
const Discord = require("discord.js");
const fs = require("fs");
const bot = new Discord.Client({disableEveryone: true});
bot.commands = new Discord.Collection();

//Express
const http = require('http');
const express = require('express');
const app = express();
app.get("/", (request, response) => {
  console.log(Date.now() + " Ping Recebido");
  response.sendStatus(200);
});
app.listen(process.env.PORT);
setInterval(() => {
  http.get(`http://${process.env.PROJECT_DOMAIN}.glitch.me/`);
}, 280000);


bot.commands = new Discord.Collection();
bot.aliases = new Discord.Collection();

// Now Comes the command handler 
const loadCommands = module.exports.loadCommands = (dir = "./commands/") => {
    fs.readdir(dir, (error, files) => {                   // Reading the Dir
        if (error) return console.log(error);                    

        files.forEach((file) => {                       // reading Files from each dir
            if (fs.lstatSync(dir + file).isDirectory()) {
                loadCommands(dir + file + "/");
                return;
            }

            delete require.cache[require.resolve(`${dir}${file}`)];

            let props = require(`${dir}${file}`); // defining props for each file for each dir

            bot.commands.set(props.command.name, props); // giving name to the command

            if (props.command.aliases)  props.command.aliases.forEach(alias => { 
                bot.aliases.set(alias, props.command.name); // giving aliases to the command [second name]
            });
        });
    });
};
loadCommands(); // loading the commands 


bot.on("ready", async () => {
  console.log(`${bot.user.username} está online em ${bot.guilds.size} servers!`);
  bot.user.setActivity("⚒️ MANUTENÇÃO ⚒️", {type: "STREAMING"});

});

//bot.on("message", async message => {
//  if(message.author.bot) return;
//  if(message.channel.type === "dm") return;
  
//  let prefix = (botconfig.prefix)
//  let messageArray = message.content.split(" ");
//  let cmd = messageArray[0];
//  let args = messageArray.slice(1);
//  let commandfile = bot.commands.get(cmd.slice(prefix.length));
//  if(commandfile) commandfile.run(bot,message,args);

//});

bot.on("message", async message => {
  let prefix = (botconfig.prefix)
  let args = message.content.slice(prefix.length).trim().split(/ +/g);
let cmd = args.shift().toLowerCase();
let command;

if (bot.commands.has(cmd)) {
    command = bot.commands.get(cmd);
} else if (bot.aliases.has(cmd)) {
    command = bot.commands.get(bot.aliases.get(cmd));
}

    if (!message.content.startsWith(prefix)) return;

    if (command) {
    // The Below line will check if the command is enabled or else it will give a message that command is disabled and the user cannot use it 
        if (message.author.id !== "472720369346936842" && !command.command.enabled) return message.channel.send(`${message.author.username} Desculpa. O comando foi desativado!!`);
    }
try {
    command.run(bot, message, args);

} catch (e) {
}
}),

bot.login(botconfig.token)

#2

I’m wondering if one of your files in ./commands/ isn’t exporting the command as expected. If I were troubleshooting this I’d console.log( props ) right before bot.commands.set() and see what was returned right before that error was thrown.

#3

@cori It gave me this:

{ run: [AsyncFunction],

  command: { name: 'manualoverridecommand' } }

{ run: [Function],

  command: 

   { name: 'reload',

     descrription: 'Reinicia algum comando sem reiniciar o bot todo.',

     usage: [ 's!reload' ] } }

{ run: [AsyncFunction],

  command: 

   { name: 'setplay',

     descripton: 'seta o jogo do bot',

     usage: [ 's!setplay <texto>' ] } }

{ run: [Function], command: { name: 'testcommand179324865' } }

{ run: [AsyncFunction],

  command: 

   { name: 'buy',

     description: 'Compra itens.',

     usage: 's!buy <item>' } }

{ run: [AsyncFunction],

  command: 

   { name: 'daily',

     description: 'Pegue sua recompensa diária',

     usage: 's!daily' } }

{ run: [AsyncFunction],

  command: 

   { name: 'dar',

     description: 'Comando para dar moons, apenas BotOwner',

     usage: 's!dar [moons] [user]' } }

{ run: [AsyncFunction],

  command: 

   { name: 'moons',

     description: 'Numero de moons que você tem',

     usage: 's!moons' } }

{ run: [AsyncFunction],

  command: 

   { name: 'pay',

     description: 'Pague ou ofereça moons',

     arg: '``s!pay [moons] [user]``' } }

{ run: [AsyncFunction],

  command: 

   { name: 'set',

     description: 'Comando para setar moons, apenas BotOwner',

     usage: 's!set [moons] [user]' } }

{ run: [AsyncFunction],

  command: 

   { name: 'remove',

     description: 'Comando para retirar moons de um usuário',

     usage: 's!remove [moons] [user]' } }

{ run: [AsyncFunction],

  command: 

   { name: 'work',

     description: 'Parte em trabalho para planetas à procura de moons',

     usage: 's!work' } }

{ run: [AsyncFunction],

  command: 

   { name: 'roleta',

     descrription: 'Tente a sua sorte,e ganha (ou perde) moons!',

     usage: [ 's!roleta' ] } }

{ run: [AsyncFunction],

  command: 

   { name: 'slots',

     description: 'Aposta na slotmachine do server e ganha moons!',

     usage: [ 's!slots <quantia>' ] } }

EDIT: Now I see that the command help isn’t even recognised…

@cori What’s happening?

1 Like
#4

Nevermind that ^^^^^^^^^ I’ve already fixed it. But now when I try to run my help code, it shows me this error:

Here is my help.js code:

//module.exports = {
//  run: (client, message, args) => {
 
//   let embed = {
//      color: 0xB1103C,
//      title: 'Lista de Comandos S1mple',     
//      description: '**Esses são todos os comandos disponíveis do S1mple**.',
//      footer: {
//        text: 'Não se esqueça de votar no S1mple ajudando nossa divulgação.'
//      },
//      fields: []
//    }

   
//    client.commands.forEach(command => {
//      embed.fields.push(
//        {
//        name: `**${command.help.name}**`,
//        value: `**Descrição**: ${command.help.description}\n**Como Usar**: ${command.help.usage}`
//        }
//      )
//    })

 
//    message.author.send({ embed: embed })
//      .then(() => message.react(':white_check_mark:'))
//      .catch(() => message.reply('Enviei na sua DM. :envelope_with_arrow:'))
//  }
//}

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

exports.run = async (bot, message, args, tools, con) => {
    let help = new Discord.RichEmbed()
        .setAuthor("Lista de comandos")
        .setColor(0x703817)
        .addField("Economia", `${bot.commands.filter(cmd => cmd.help.category === 'economia').map(cmd => `\`${cmd.help.name}\``).join(", ")}`, true)
        .addField("Diversão", `${bot.commands.filter(cmd => cmd.help.category === 'fun').map(cmd => `\`${cmd.help.name}\``).join(", ")}`, true)
        .addField("Sistema", `${bot.commands.filter(cmd => cmd.help.category === 'sistema').map(cmd => `\`${cmd.help.name}\``).join(", ")}`, true);
    message.channel.send(help)
}


 module.exports.command = {
    name: 'help',
    description: 'Todos os comandos disponiveis',
    category: "sistema",
    usage: 's!help'
}
#5

Can you try removing .help after each cmd and see if that helps!

2 Likes
#6

Thanks. It helped. I put command insted of help and it worked.

2 Likes