【问题标题】:Exporting/importing in node.js / discord.js在 node.js / discord.js 中导出/导入
【发布时间】:2018-05-19 23:56:04
【问题描述】:

我目前正在使用 discord.js 制作一个不和谐的机器人,因为在我发现使用多个 js 文件非常困难之前,我还没有在没有 html 文件的情况下进行编程。起初我认为使用导入和导出会起作用,但 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 函数是它出错的地方。

【问题讨论】:

  • 什么??它们是受支持的......您实际上也在给定的代码中使用它们

标签: javascript node.js discord discord.js


【解决方案1】:

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

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

然而这很违反直觉,所以你只需要从“commands.js”中导出一个对象:

module.exports = {
  ping: function() { /*...*/ }
  //...
};

然后可以轻松导入:

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

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

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

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

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

【讨论】:

  • 这解决了我的第一个问题,但现在我收到错误“无法读取未定义的属性“通道””,即使我将消息作为参数传递。
  • @dubster 你必须在这里传递它commands[command](whatever);,但是没有代码很难说。
  • 我正在这样做,按顺序传递消息和机器人,然后在 command.ping() 函数中添加消息。
  • 没关系,我不知道问题是什么,但我设法以某种方式解决了它,也许是一个错字。感谢您的帮助!
  • @dubster 很高兴为您提供帮助 :)
猜你喜欢
  • 2021-08-14
  • 1970-01-01
  • 2017-12-23
  • 1970-01-01
  • 1970-01-01
  • 2015-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多