skip to Main Content

I am currently working on a bot discord developed with Node.js.
I have correctly split my project by separating the different parts in associated folders.
My project folder
I have a problem though, because I need to use the client I created in the index in my guildMemberAdd.js and other files, but I don’t know how to pass it correctly.
index.js

I tried to put my client variable in global variable but it creates an error.
index.js
cmd

2

Answers


  1. you can add this code to your index.js file to export the Client variable

    module.exports = {client};
    

    And then, you need to call the variable from the files that you want to use the variable in them using a destructor like this:

    const {client} = require(relativePathOfIndexFile);
    
    Login or Signup to reply.
  2. You don’t need to pass down the instantiated client to every file as it’s available from the callback functions.

    For example, if you want to get the client in the guildMemberAdd event, you can grab it from the GuildMember (which is the first parameter):

    // guildMemberAdd.js 
    module.exports = {
      // ...
      async execute(member) {
        const { client } = member
    
        // you can use the client now :)
      }
    }
    

    It will work with other events too. Some examples below:

    // messageCreate.js
    async execute(message) {
      const { client } = message
    }
    
    // channelCreate.js
    async execute(channel) {
      const { client } = channel
    }
    
    // interactionCreate.js
    async execute(interaction) {
      const { client } = interaction
    }
    

    If you still want to pass the client, you can pass it as the last parameter:

    for (const file of eventFiles) {
      const filePath = path.join(eventsPath, file);
      const event = require(filePath);
    
      if (event.once) {
        client.once(event.name, (...args) => event.execute(...args, client));
      } else {
        client.on(event.name, (...args) => event.execute(...args, client));
      }
    }
    

    This way client is the last argument:

    // guildMemberAdd.js 
    module.exports = {
      // ...
      async execute(member, client) {
        // ...
      }
    }
    

    However, this way you will have to include every argument. For example, in roleUpdate:

    // roleUpdate.js 
    module.exports = {
      // ⛔️ this won't work
      async execute(oldRole, client) {
        // client is a Role, not the Client
      
      // ✅ only this one will work
      async execute(oldRole, newRole, client) {
        // ...
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search