Estoy construyendo un bot de discordia usando discord.js. Todo mi código fuente proviene del sitio web oficial de la guía discord.js, y me pregunto cómo podría enumerar todos los comandos de barra inclinada declarados en un archivo JSON commands.json .
Aquí está mi código:
deploy_commands.js :
const { SlashCommandBuilder } = require('@discordjs/builders'); const { REST } = require('@discordjs/rest'); const { Routes } = require('discord-api-types/v9'); const { clientId, guildId, token } = require('./config.json'); const fs = require('node:fs'); const path = require('node:path'); const commands = []; const commandsPath = path.join(__dirname, 'commands'); const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); for (const file of commandFiles) { const filePath = path.join(commandsPath, file); const command = require(filePath); commands.push(command.data.toJSON()); } const rest = new REST({ version: '9' }).setToken(token); rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands }) .then(() => console.log('Successfully registered application commands.')) .catch(console.error); index.js :
const { Client, Collection, Intents } = require("discord.js"); const client = new Client({intents: [Intents.FLAGS.GUILDS]}); const config = require("./config.json"); const { guildId, clientId, token } = require('./config.json'); const fs = require('node:fs'); const path = require('node:path'); client.commands = new Collection(); const commandsPath = path.join(__dirname, 'commands'); const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); for (const file of commandFiles) { const filePath = path.join(commandsPath, file); const command = require(filePath); client.commands.set(command.data.name, command); } client.once('ready', () => { console.log(`user : ${client.user.tag}\nguildid : ${guildId}\nclientid : ${clientId}`); }); client.on('interactionCreate', async 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); await interaction.reply({content: 'Sorry, there was a problem while executing this command, maybe try again later?', ephemeral: true}); } }); client.login(token); deploy_commands.js es un archivo para implementar comandos, y lo que quiero hacer es guardar todos los comandos de barra inclinada declarados y transferirlos a un archivo JSON.
Personalmente, le sugiero que use map() para administrar la matriz donde almacena cada comando dentro deploy_commands.js .
A continuación puede encontrar una solución que funcionó para mí:
const fs = require('fs'); const commands = [...commandBuilders...].map(command => command.toJSON()); const commandsToString = JSON.stringify(commands); fs.writeFile('commands.json', commandsToString, (e, res) =>{ if (e) console.log('ERROR: ' + e); }