Ask coding questions

← Back to all posts
How to make other files work?
SmartxGaming (0)

I am making a discord.js bot and my code is to big I want to categories the commands like different file for moderation commands and etc but how to do this?

Comments
hotnewtop
notGilbert (121)

You can use require to "import" functions from other files.

index.js

const exampleCommandHandler = require('./commands/example');

bot.on('message', message => {
  const command = 'example'; // implement your own command logic

  // this will get messy real fast
  // you can also just require(`./commands/${command}`) and handle errors
  switch (command) {
    case 'example':
      exampleCommandHandler(message);
      break;
    default:
      // handle invalid command
      break;
  }
})

./commands/example.js

// this will export a function
// that can be required
module.exports = message => {
  // do something with the message
  message.reply('you ran the command!');
}

you can play with the folder structure if you want more organization