简体   繁体   中英

Trying to have multiple command files for Discord bot

Question: Is there any way to have multiple command files for a discord bot?

What I mean by "command file" is the file that contains the if/else statements and commands for the users to actually interact with.

What I mean by "multiple files" is making more than one of these "command files" that can respond to commands.

I'm trying to split my fun and admin commands into 2 separate files but currently only one is working. I know that one of the problems lie in the package.json file where it says: "main": "index.js",

{
  "name": "n00bly783",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
  "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "discord.js": "^11.2.1",
    "discord.js-commando": "^0.9.0"
  }
}

Is there a way to connect a single package.json file to multiple other .js files? And if so, is that all I need to do to get multiple discord bot .js files to start working?

You don't necessarily need to edit the package .json.

To use multiple files, you can simply do the following:

(commandfile1.js)

module.exports = {
  commandName: {
    variableToCallToRunFunction: (arguments) => { //usually called run
      //the command
    }
  }
}

(mainfile.js)

commandfile1 = require('./commandfile1.js') //if commandfile1 is in the same folder as this file
yourBot.on('message', msg => {
  if (msg.content.startsWith(yourPrefix){
    cmdmsg = msg.content.replace(yourprefix, '')
    for (command in commandfile1){
      if (cmdmsg.startsWith(commandfile1[command])){
        commandfile1[command].variableToCallToRunFunction(arguments) //usually just .run()
      } 
    }
  }
}

This is one way to do it, all you have to do is export the separate command file as an object, and make every command a separate entry in the object. Then every time a message is sent with your bots' prefix in front of it, cycle through all of the commands and run the one the user specified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM