Search code examples
javascriptnode.jsdiscord.jsbots

How to use client of my index in other files in discord.js?


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


Solution

  • 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) {
        // ...
      }
    }