Home > Mobile >  Client.guilds is not defined discord.js
Client.guilds is not defined discord.js

Time:08-17

I'm trying to create a discord bot. When run console.log(client.guilds) from the ping.js it returns undefined. But when I run console.log(client.guilds) from the index.js it returns an array. My file structure looks like this:

  • discord-bot/index.js
  • discord-bot/commands/ping.js

File contents ping.js:

const { SlashCommandBuilder } = require('discord.js');
module.exports = {
        data: new SlashCommandBuilder()
                .setName('ping')
                .setDescription('Replies with Pong!'),
        async execute(interaction) {
        client = require('./../index.js');
console.log(client.guilds);
        
        }
};

CodePudding user response:

I don't destructure the imported object { clientThe answer:

const { client } = require('./../index.js');

Thanks Zsolt Meszaros.

CodePudding user response:

It is possible that no guilds are cached in the export state ( you should either consider exporting your client after the ready event is triggered or fetch all guilds )

client.guilds.fetch() 

fetches all your guilds and caches them, you can incorporate the snippet in your code like so:

const { SlashCommandBuilder } = require('discord.js'),
client = require('./../index.js');
module.exports = {
        data: new SlashCommandBuilder()
                .setName('ping')
                .setDescription('Replies with Pong!'),
        async execute(interaction) {
        client.guilds.fetch().then( ( guilds ) => console.log(guilds))
        }
};

another friendly approach to a slash command handler usually is declaring client as a formal parameter in your execute function and call the function in your interactionCreate which is chained to your index.js file, further handling all the events by binding it directly to the client instead of exporting it like so:

index.js

// file being the individual file ( you can loop through your events folder 
const event = require(`./events_dir/${file}`),
eventName = file.split(".")[0];
client.on(eventName, event.bind(null, client));

interactionCreate.js

// command representing the individual command from your commands collection
module.exports = (client, interaction) => {
command.execute(client, interaction);
}

ping.js

execute(client, interaction) {
console.log(client.guilds);
}
  • Related