Home > Blockchain >  How can I call Discord.js functions from a lib.js file into index.js?
How can I call Discord.js functions from a lib.js file into index.js?

Time:12-20

I am trying to have a separate class full of my functions so index.js doesn't get cluttered up. The problem I encountered is that my new lib.js file cannot work with discord.js. I am planning on adding multiple, more complex functions, so replacing lib.start() with msg.channel.send('Game Started') won't fix my issue. Is there a way I can get discord.js commands to work in lib.js so I can call them into index.js?

index.js

const Discord = require('discord.js')
const client = new Discord.Client();

const lib = require("./classes/lib");

const { token } = require('./Data/config.json');

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
})

client.on('message', async msg => {
  if(msg.content.startsWith("m!")) {
    const command = msg.content.substring(2)

    switch(command) {
      
      //Calling 'start()'
      case "start game" : lib.start(); break;
    
      default: msg.channel.send('Unknown Command');
    
    }
  } 
})

client.login(token)

lib.js

function start() {
    msg.channel.send('Game Started');   //Trying to get this to work
}

module.exports = {start};

CodePudding user response:

Pass in a reference to message in the function

client.on('message', async msg => {
  if(msg.content.startsWith("m!")) {
    const command = msg.content.substring(2)

    switch(command) {
      
      //Calling 'start()'
      case "start game" : lib.start(msg); break;
    
      default: msg.channel.send('Unknown Command');
    
    }
  } 
})
function start(msg) {
    msg.channel.send('Game Started');
}

module.exports = {start};

You probably also want to make start and further functions async, just remember to await them when they're called.

  • Related