Estoy creando un bot de Discord usando el comando de barra diagonal, y estoy atascado en este punto. Aquí está el código de mi archivo index.js
const commands = [] const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); for (const file of commandFiles) { const command = require(`./commands/${file}`); commands.push(command.data.toJSON()); } const rest = new REST({ version: '9' }).setToken(token); (async () => { try { console.log('Started refreshing application (/) commands.'); await rest.put( Routes.applicationGuildCommands(clientId, guildId), { body: commands }, ); console.log('Successfully reloaded application (/) commands.'); } catch (error) { console.error(error); } })(); client.on('ready' , () => { console.log('I am online') client.user.setActivity('MUSIC 🎧', {type:'LISTENING'}) }) client.on('interactionCreate', async interaction => { if(!interaction.isCommand())return const command = interaction.commands.get(interaction.commandName); if(!command)return try { await command.execute(interaction) } catch (err) { console.error(err) await interaction.reply('There was an error trying to execute that command!') } })Y un archivo ping.js para enviar un mensaje PING-PONG simple.
const { SlashCommandBuilder } = require('@discordjs/builders') module.exports = { data: new SlashCommandBuilder() .setName("ping") .setDescription("PING-PONG"), async execute (interaction) { await interaction.reply("Pong!") } }ERROR es:
const command = interaction.commands.get(interaction.commandName); ^ TypeError: Cannot read properties of undefined (reading 'get') at Client.<anonymous> (C:\vs\Adele music bot\index.js:52:42) at Client.emit (node:events:520:28)Todo está bien, registra comandos de barra inclinada, pero tan pronto como uso /ping, solo muestra el error anterior.
Parece que ha copiado y pegado código de diferentes lugares y solo esperaba que funcionara. El error significa que los comandos de interaction.commands no están definidos, lo cual es cierto.
Por lo que puedo ver, querías una Discord.Collection con todos tus comandos de interacción dentro. A los efectos de esto, utilizaremos client.commands .
Ejemplo de código
/* Create the collection */ client.commands = new Discord.Collection() const commands = [] const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); for (const file of commandFiles) { const command = require(`./commands/${file}`); commands.push(command.data.toJSON()); /* Add data to the collection */ client.commands.set(command.name, command); } ... /* Get the command */ const command = client.commands.get(interaction.commandName);const {Collection} = require('discord.js');importar la colección del paquete discord.
entonces después de crear el cliente
client.commands = new Collection();usa el fragmento de arriba
después
const command = client.commands.get(interaction.commandName);escriba esta línea donde se origina el error.
básicamente, primero debe crear una nueva colección de comandos para el cliente. luego necesita agregar los datos para agregar datos a la colección pero usando el siguiente comando.
client.commands.set();luego, después de esto, solo puedes usar el comando get
client.commands.set();