调用

时间:2019-08-30 11:46:18

标签: node.js function discord.js

我有一个名为index.js的主代码文件,该文件将用户命令映射到存储在名为/commands的子文件夹中的其他代码文件中的功能。其中之一是match.js,它处理命令“!match”。 !match命令的功能将导出到一个对象中,并在index.js中调用,但是我无法使其正常工作。

我正在关注this关于动态命令处理的教程。

我尝试以几种不同的方式存储execute()函数:

module.exports = {
    ...,
    execute(message, args) {
        ...
    },
}

module.exports = {
    ...,
    execute: function execute(message, args) {
        ...
    },
}

module.exports = {
    ...,
    execute: function(message, args) {
        ...
    },
}

我有这段代码可以处理index.js中的传入用户命令。

...

client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
    const command = require('./commands/' + file);
    client.commands.set(command.name, command);
}

...

client.on('message', message => {
    if (!message.content.startsWith('!') || message.author.bot) return;

    // Remove ! and split into args
    const args = message.content.slice(1).split(/ +/);
    // Get main command and remove from start of args
    const command = args.shift().toLowerCase();

    // If command not found, exit
    if (!client.commands.has(command)) return;

    try {
        console.log("Command: " + command);
        console.log(client.commands.get(command));
        console.log("Name: " + client.commands.get(command).name);
        console.log("Description: " + client.commands.get(command).description);
        client.commands.get(command).execute(message, args);
    }
    catch (e) {
        console.error(e);
        message.reply('Error in executing command.');
    }
    return;
});

这是match.js的内容(此代码曾经驻留在index.js中,并且没有错误地工作)

const sheet = require('./../sheet');

module.exports = {
    name: 'match',
    description: 'Returns next match.',
    // eslint-disable-next-line no-unused-vars
    execute: function(message, args) {
        console.log('executing match.js');
        sheet()
            .then(
                result => {
                    message.reply(
                        '\n' +
                        'Teams: ' + result[0].home + ' vs ' + result[0].away + '\n' +
                        'Time: ' + result[0].date + ' ' + result[0].time + '\n' +
                        'Competition: ' + result[0].competition + '\n' +
                        'Channel: ' + result[0].channel
                    );
                },
                err => {
                    console.log(err);
                }
            );
    },
};

在index.js中以console.log开头的调试语句导致以下输出:

Command: match
{ name: 'match',
  description: 'Returns next match.',
  execute: [Function: execute] }
Name: match
Description: Returns next match.

因此,输入被映射到包含execute函数的正确命令对象。但是,当在下一行调用execute时,什么也没有发生。没有错误消息,并且不会调用match.js中的console.log语句。

1 个答案:

答案 0 :(得分:0)

我最终通过在新目录中逐行逐行重写整个项目文件来解决了该问题。我认为缓存导出的模块肯定存在一些问题,但是我不知道这与节点还是我自己的文件系统有关。