在Discord.js中运行多个文件?

时间:2018-02-02 21:19:25

标签: node.js discord.js

请原谅我,如果这看起来很愚蠢或者其他什么,我已经尝试过寻找地方了,而且我不知道这是否适合放置它或其他任何东西

所以我想制作一个不和谐机器人,我有一个脚本和一切,但问题是,我只有一个脚本。我不知道如何使用其他脚本,但我认为我不是唯一一个遇到此问题的人,因为如果有人使用两种语言,那么它需要两个文件,但我不知道如何制作第二个文件运行。

1 个答案:

答案 0 :(得分:0)

Don't worry, this is as good a spot as any to post this question. Basically what you'll need to do, is something like this:

In a separate file where you want to store your admin commands (I named this file adminCmds.js), set up a module.exports variable that points to an object with your admin commands. In my example, my adminCmds.js file is in the same directory as index.js.

Try something like this:

// inside adminCmds.js
function admin1() {
    console.log('in admin 1 command');
    // your command code here
}

function admin2() {
    console.log('in admin 2 command');
    // your command code here
}

module.exports = {
    checkAdminCmd: function(message) {
        let command = message.content, found = false;

        switch(command) {
            // your first admin command (can be whatever you want)
            case '?admin1':
                // set found equal to true so your index.js file knows
                //   to not try executing 'other' commands
                found = true;
                // execute function associated with this command
                admin1();
                break;

            // your second admin command (similar setup as above)
            case '?admin2':
                found = true;
                admin2();
                break;

            // ... more admin commands
        }

        // value of 'found' will be returned in index.js
        return found;
    }
};

In your main index.js file, set up your main message listener like this:

// get admin commands from other file
const adminCmds = require('./adminCmds');

// set message listener 
client.on('message', message => {
    let command = message.content;

    // execute admin commands
    // -> if function checkAdminCmd returns false, move on to checking 'other' commands
    if ( adminCmds.checkAdminCmd(message) )
        return;

    // execute other commands
    else {
        switch(command) {
            case '?PING':
                message.reply('pong');
                break;

            // ... other commands here
        }
    }
});

I'd highly recommend looking at some Node.js tutorials before using Discord.js - it'll help out a lot. But if you run into any troubles in the meantime, I'd be glad to try to help.