Use different file for bot commands

2019-08-27 00:57发布

问题:

I want to keep my code clean looking and easier to understand, by putting all the longer stuff in another file. I have my main file (index.js):

 const discord = require('discord.js');
 require('dotenv').config()

 const token = process.env.botToken;
 const prefix = "s!";

 const cmds = require("./commands.js");

 var client = new discord.Client();

 client.on('ready', function(message) {});

 client.on('message', function(message) {
    if(message.author.equals(client.user) || !message.content.startsWith(prefix)) return;

    var args = message.content.substring(prefix.length).split(" ");

    switch (args[0].toLowerCase()) {
        case "help":
            cmds.help;
            break;
    }
 });

 client.login(token)

and my other folder (commands.js):

const discord = require('discord.js');
var client = new discord.Client();

    module.exports = {
        help: function(message) {
            var embed = new discord.RichEmbed()
                .addField("spyBot Commands", "If you get issues, dont be afraid to join us: http://discord.gg/3k6zGNF");
            message.channel.send(embed);
        }
    }

I would like it to send the embed, but when I put the command in, nothing happens and no errors are printed.

回答1:

I see two major things that need to be fixed:
1: the client in commands.js
2: the command function in the main file

1 - In commands.js, you created a new client. If you have only this command, it won't cause any problem since client is not used in your code, but when you'll need it that won't work since it has to be the same as in the main file. You have two possible solutions: setting your client as global or requiring the main module. If your bot doesn't have to be published in a public package then you can save global.client = client;, and then access it as client in every other file. The alternative is to export the client from the main module (module.exports = {client};) and then require the main file in commands.js (var {client} = require("./index.js");).

2 - In commands.js you're exporting a help function, so when you call it index.js you have to use parenthesis and pass the message as an argument. Try something like this:

//in the switch statement
case "help":
  cmds.help(message);
  break;

I hope this can help you, let me know if you have any further question.