user13937476
user13937476

Reputation:

How to run commands from different files discord.js

So I am making a discord bot, and I want to run commands in different files. in my index I have

Fs.readdir("./commands/", (_err, files) => {
    files.forEach((file) => {
        if (!file.endsWith(".js")) return;
        let props = require(`./commands/${file}`);
        let commandName = file.split(".")[0];
        client.commands.set(commandName, props);
        console.log(`šŸ‘Œ Command loaded: ${commandName}`);
    });
});

And In my /commands/help.js I have

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

exports.run = async (client, message, args, prefix) => {
    
    if (args[0] == 'hi') {
        message.channel.send
    }
}

and it doesent do anything. In my console it says

ļæ½ Command loaded: help

I dont know what I am doing wrong. Can you help?

Upvotes: 0

Views: 2864

Answers (2)

Lioness100
Lioness100

Reputation: 8402

Although you are adding the command to the client.commands collection, you're never actually executing it. I'd recommend defining module.exports as an object with command details, as well as the actual function. For example:


help.js

module.exports = {
 name: 'help',
 // any other details you might like, such as:
 description: 'See all the commands!',
 execute(client, message, args, prefix) {
  // the actual function

  if (args[0] == 'hi') {
   message.channel.send;
  }
 },
};

index.js

Fs.readdir('./commands/', (_err, files) => {
 files.forEach((file) => {
  if (!file.endsWith('.js')) return;
  let command = require(`./commands/${file}`); // access all details though this variable
  client.commands.set(command.name, command);
  console.log(`šŸ‘Œ Command loaded: ${command.name}`);
 });
});

In your message event, when you want to trigger your command:

client.on('message', (message) => {
 // your code

 // get the command and execute the function
 client.commands.get('Command Name').execute(client, message, args, prefix);
});

Upvotes: 1

Vinicius
Vinicius

Reputation: 324

It seems you're not sending anything when you use the help command, you should have it like this:

if(args[0] == 'hi') {
  message.channel.send('Hello!');
}

Upvotes: 0

Related Questions