Discord.js 14 Slash Commands дублированыJavascript

Форум по Javascript
Ответить
Anonymous
 Discord.js 14 Slash Commands дублированы

Сообщение Anonymous »

Не совсем уверен, почему, но, кажется, что мои команды Slash регистрируются дважды. Я пробовал различные методы, да, используя CHATGPT, но до сих пор у всех результатов есть дубликаты. < /P>
Есть предложения? (Помимо прекращения использования CHATGPT, так как он помогает мне научиться делать это). < /P>
Насколько я могу судить, он должен регистрироваться только один раз, так что не совсем уверен, куда идти отсюда. < /P>
// Initialize your commands collection
client.commands = new Collection();

// Read command files from ./commands/
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

// Array to hold slash command definitions for registration
const slashCommandsData = [];

// Load each command file
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const commandModule = require(filePath);

// If a module exports multiple slash definitions:
if (Array.isArray(commandModule.data)) {
for (const slashDef of commandModule.data) {
if (!slashDef.name) continue; // Skip invalid definitions
slashCommandsData.push(slashDef.toJSON());
client.commands.set(slashDef.name, commandModule);
}
} else {
// Single slash command export
const { data } = commandModule;
if (!data.name) continue; // Skip if missing name
slashCommandsData.push(data.toJSON());
client.commands.set(data.name, commandModule);
}
}

console.log(`Total commands loaded: ${client.commands.size}`);

// Register slash commands for a specific guild after the client is ready
client.once('ready', async () => {
try {
const guildId = '1134123338734764072';
const guild = client.guilds.cache.get(guildId);
if (!guild) throw new Error(`Guild with ID ${guildId} not found`);

console.log(`Clearing existing commands for guild ${guildId}...`);
// Clear all existing commands for this guild
await guild.commands.set([]);
console.log('Existing commands cleared.');

console.log(`Now registering (/) commands for guild ${guildId}...`);
const rest = new REST({ version: '10' }).setToken(BOT_TOKEN);
const result = await rest.put(
Routes.applicationGuildCommands(DISCORD_CLIENT_ID, guildId),
{ body: slashCommandsData }
);
console.log(`Successfully registered ${result.length} slash command(s) for the guild.`);
} catch (error) {
console.error('Error during command registration:', error);
}
});

// Listen for slash command interactions
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 executing command:', error);
if (!interaction.replied && !interaction.deferred) {
await interaction.reply({ content: 'There was an error executing this command!', ephemeral: true });
} else {
await interaction.followUp({ content: 'There was an error executing this command!', ephemeral: true });
}
}
});


Подробнее здесь: https://stackoverflow.com/questions/795 ... duplicated
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»