Home > Back-end >  Making discord client object accessible in event files?
Making discord client object accessible in event files?

Time:01-22

I'm new to using Discord.js, and after looking through the basic guide/docs, I'm still somehow confused as to how to allow event and/or command files to access the main client instance. For example, I may want to call client.database within an event file in order to make use of CRUD operations.

I did some digging on my own, and I saw that someone had implemented this by getting rid of the .execute function in each of the event files, and passing in event.bind(null, client) to client.on(). I don't really understand it though:

https://github.com/KSJaay/Alita/blob/fe2faf3c684227e29fdef228adaae2ee1c87065b/Alita.js https://github.com/KSJaay/Alita/blob/master/Events/guildMemberRemove.js

My Main File:

require("dotenv").config();
const fs = require('fs');
util = require('util');
readdir = util.promisify(fs.readdir);
const { Client, Collection, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const mongoose = require('mongoose');

client.events = new Collection();
client.commands = new Collection();
//client.database = require('./src/db/index.js')

async function init() {
    const eventFiles = fs.readdirSync('./src/discord/events').filter(file => file.endsWith('.js'));
    for (const file of eventFiles) {
        const event = require(`./events/${file}`);
        const eventName = file.split(".")[0];
        if (event.once) {
            client.once(eventName, (...args) => event.execute(...args));
        } else {
            client.on(eventName, (...args) => event.execute(...args));
        }
    }
    
    const commandFiles = await readdir('./src/discord/commands')
    commandFiles.filter(file => file.endsWith('.js'));
    for (const file of commandFiles) {
        const command = require(`./commands/${file}`);
        client.commands.set(command.data.name, command);
    }

    mongoose.connect(process.env.DB_CONNECT, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    }).then(() => {
        console.log('Connected to MongoDB')
    }).catch((err) => {
        console.log('Unable to connect to MongoDB Database.\nError: '   err)
    })

    await client.login(process.env.TOKEN);
}

init();

My Sample Event:

module.exports = {
    name: 'interactionCreate',
    async execute(interaction) {
        console.log(`${interaction.user.tag} in #${interaction.channel.name} triggered an interaction.`);

        if (!interaction.isCommand()) return;

        const command = client.commands.get(interaction.commandName);

        if (!command) return;

        try {
            await command.execute(interaction);
        } catch (error) {
            console.error(error);
            return interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
        }
    },
};

CodePudding user response:

Get the client using .client on an object, an Interaction in this case

const command = interaction.client.commands.get(interaction.commandName)
  •  Tags:  
  • Related