在node.js / discord.js中导出/导入

时间:2018-05-19 15:01:41

标签: javascript node.js discord discord.js

我目前正在使用discord.js制作一个discord bot,因为在我发现使用几个js文件之前我没有编写html文件非常困难。起初我认为使用导入和导出是可行的,但Node尚不支持。我做了一些窥探,这就是我决定做的事情:

Index.js

document.getElementsByClassName()[0].childNodes[1]

commands.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();
        }
    });
}

botconfig.json

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');
    }
}

我的目标是通过在json文件中添加一个单词以及在commands.js中连接到它的函数来使代码适应。在checkCommand函数中,它还应该触发与命令同名的函数,现在我将其设置为触发ping,无论我使用什么命令,因为我对参数有些麻烦。问题是命令函数根本没有被触发,非常确定checkCommand函数是出错的地方。

1 个答案:

答案 0 :(得分:0)

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

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

然而,这是违反直觉的,所以你只需从“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:全局变量(cmdarg)是一个非常糟糕的主意,相反,你应该将这些值作为参数传递。

相关问题