I want to use "client" in one or multiple "command "files aside my index.js, where client is defined.
//index.js
module.exports.Client = client
//command-file.js
const index = require(../../index)
const client = index.Client
//index.js
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(commandsPath)
for (const dir of commandFolders) {
const commandFiles = fs
.readdirSync(`${commandsPath}/${dir}`)
.filter((file) => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`${commandsPath}/${dir}/${file}`);
client.commands.set(command.data.name, command);
}
}
//ping.js
const { SlashCommandBuilder } = require('discord.js');
const WebSocketManager = require('@discordjs/ws')
const index = require("../../index")
const client = index.Client
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
await interaction.reply(`:ping_pong: Pong! ${client.ws.ping}ms`);
},
};
In my case I had the ping.js
command, which in the beginning texted some random things, so I didn't need client
. I wanted then some real numbers. The slash command was uploaded before so updating the file worked fine. Later though I tried to deploy another command and errors appeared.
client.commands.set(command.data.name, command);
^
TypeError: Cannot read properties of undefined (reading 'name')
at Object.<anonymous> (C:\mydir\index.js:46:42)
at Module._compile (node:internal/modules/cjs/loader:1126:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
at Module.load (node:internal/modules/cjs/loader:1004:32)
at Function.Module._load (node:internal/modules/cjs/loader:839:12)
at Module.require (node:internal/modules/cjs/loader:1028:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (C:\mydir\commands\fun\ping.js:3:13)
at Module._compile (node:internal/modules/cjs/loader:1126:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
Just to clarify index.js:16:42
is where my command handler is situated (first line of the error above)
ping.js:3:15 is
const index = require("../../index")
^
I tried to deploy another command and it worked just fine (client wasn't used)
I don't really know what you tryed to do there but I use in the main file global.client = new Client()
and works just fine, then you don't have to require it, just use it as client