Exporting/importing 在 node.js / discord.js

Exporting/importing in node.js / discord.js

我目前正在用 discord.js 制作一个不和谐的机器人,因为在我发现使用多个 js 文件非常困难之前,我没有在没有 html 文件的情况下进行编程。起初我以为使用 imports 和 exports 会起作用,但 Node 还不支持它。我做了一些窥探,这就是我决定做的事情:

Index.js

const commandFunctions = require('./commands.js')();
const botconfig = require('./botconfig.json');

bot.on('message', async message => {
    if (message.author.bot) { return; }
    if (message.channel.type === 'dm') { return; }

    messageArray = message.content.split(' ');
    cmd = messageArray[0];
    arg = messageArray.slice(1);

    if (cmd.charAt(0) === prefix) {
        checkCommands(message);
    } else {
        checkForWord(message);
    }
});

function checkCommands(message) {
    botconfig.commands.forEach(command => {
        if (arg === command) {
            commandFunctions.ping();
        }
    });
}

commands.js

module.exports = function() {
    this.botinfo = function(message, bot) {
        let bicon = bot.user.displayAvatarURL;
        let botembed = new Discord.RichEmbed()
        .setColor('#DE8D9C')
        .setThumbnail(bicon)
        .addField('Bot Name', bot.user.username)
        .addField('Description', 'Inject the memes into my bloodstream')
        .addField('Created On', bot.user.createdAt.toDateString());
        return message.channel.send(botembed);
    } 

    this.roll = function(message) {
        let roll = Math.floor(Math.random() * 6) + 1;
        return message.channel.send(`${message.author.username} rolled a ${roll}`);
    }

    this.ping = function() {
        return message.channel.send('pong');
    }
}

botconfig.json

"prefix": "+",
"commands": [
     "botinfo",
     "roll",
     "ping"
]

我的目标是使代码具有适应性,只需向 json 文件添加一个词,并在 commands.js 中添加一个与之相关的函数。在 checkCommand 函数中,它还应该触发与命令同名的函数,现在我已经将它设置为触发 ping,无论我使用什么命令,因为我在参数方面遇到了一些麻烦。问题是命令函数根本没有被触发,很确定是 checkCommand 函数出错了。

对于 this 指向函数内的返回对象,您必须使用 new 运算符调用它:

 const commandFunctions = new require('./commands.js')();

然而这是非常违反直觉的,所以你 migut 只是从 "commands.js":

导出一个对象
module.exports = {
  ping: function() { /*...*/ }
  //...
};

然后可以轻松导入:

const commandFunctions = require('./commands.js');
commandFunctions.ping();

要执行命令,不需要加载json,只需检查命令对象中是否存在属性,:

 const commands = require('./commands.js');

 function execCommand(command) {
   if(commands[command]) {
     commands[command]();
  } else {
     commands.fail();
 }
}

PS: 全局变量 (cmd, arg) 是一个非常非常糟糕的主意,相反你应该将值作为参数传递。