如何在 Discord.js v13 中删除斜杠命令

6

const { glob } = require("glob");
const { promisify } = require("util");
const { Client } = require("discord.js");
const mongoose = require("mongoose");

const globPromise = promisify(glob);

/**
 * @param {Client} portle
 */
module.exports = async (portle) => {
    const commandFiles = await globPromise(`${process.cwd()}/commands/**/*.js`);
    commandFiles.map((value) => {
        const file = require(value);
        const splitted = value.split("/");
        const directory = splitted[splitted.length - 2];

        if (file.name) {
            const properties = { directory, ...file };
            portle.commands.set(file.name, properties);
        }
    });

    const eventFiles = await globPromise(`${process.cwd()}/events/*.js`);
    eventFiles.map((value) => require(value));

    const slashCommands = await globPromise(
        `${process.cwd()}/slash-cmds/*/*.js`
    );

    const arrayOfSlashCommands = [];
    slashCommands.map((value) => {
        const file = require(value);
        if (!file?.name) return;
        portle.slashCommands.set(file.name, file);

        if (["MESSAGE", "USER"].includes(file.type)) delete file.description;
        arrayOfSlashCommands.push(file);
    });

    portle.on("ready", async () => {
        await portle.guilds.cache
            .get("884380331170484244")
            .commands.set(arrayOfSlashCommands);
    });

    const mongooseURI = process.env.URI;
    if (!mongooseURI) throw new Error("Unspecified mongoose connection string!");

    mongoose.connect(mongooseURI).then(() => console.log('Connected to mongodb'));
};

我刚开始学习如何创建斜杠命令,当我创建一个后,我重启了我的机器人 我的命令截图 ,现在我的一条斜杠命令被复制了。 我该如何删除重复的命令?

下面是命令和事件处理程序代码,我在YouTube教程中找到的。


2
欢迎来到SO。请包含实际代码。 - ewokx
2个回答

9

我猜想如果你按照他们的教程操作,你想直接通过 REST 客户端来完成这个操作 - 这里有一种方法可以删除特定服务器中所有斜杠命令。

require('dotenv').config();

const { SlashCommandBuilder } = require('@discordjs/builders');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');

const token = process.env.TOKEN;
const clientId = process.env.CLIENT_ID;
const guildId = process.env.TEST_GUILD_ID;
    
const rest = new REST({ version: '9' }).setToken(token);
rest.get(Routes.applicationGuildCommands(clientId, guildId))
    .then(data => {
        const promises = [];
        for (const command of data) {
            const deleteUrl = `${Routes.applicationGuildCommands(clientId, guildId)}/${command.id}`;
            promises.push(rest.delete(deleteUrl));
        }
        return Promise.all(promises);
    });

要对全局命令执行此操作,只需使用 Routes.applicationCommands(clientId) 而不是 Routes.applicationGuildCommands(clientId, guildId)


请注意,Promise.all 通常不适合使用,但在测试目的下可以使用 - 如果您要将其集成到构建流程中,则需要进行改进。 - Jordan
为什么Promise.all不好? - LuisAFK
我猜在这里和许多应用程序中使用@LuisAFK是可以的,但我倾向于节约使用它,通常只用于读操作,因为它在第一次失败时返回并且不等待其余结果,导致您可能处于未知状态。如果在数据库事务内发生这种情况,您将无法轻松处理故障,因为回滚很可能会失败,因为其他操作仍在进行中。 - Jordan

5
你可以直接使用ApplicationCommand#delete方法来删除你的斜线命令。如何操作呢?首先,让我们获取command/ApplicationCommand对象:

    client.application.commands.fetch('123456789012345678') // id of your command
      .then( (command) => {
    console.log(`Fetched command ${command.name}`)
    // further delete it like so:
    command.delete()
    console.log(`Deleted command ${command.name}`)
    }).catch(console.error);

这个也可以使用ApplicationCommandManager#delete方法来实现,这种方法更加简单!你只需要获取到命令的ID,并像下面这样将其传递给该管理器的方法:

<guild>.commands.delete('123456789012345678')

3
我该如何获取斜杠命令的ID? - Lumins
1
@Lumins 这是一个映射函数,但你可以这样做:guild.commands.cache.forEach((value, key) => {})key 就是你的 id 或者 value.id - Lars Rijnen
1
嗨,我使用这个库来获取命令ID https://www.npmjs.com/package/discord-slash-commands-client - Marco Chavez
最佳答案,我认为是: - Brandon
1
要获取斜杠命令的ID,可以使用interaction.commandId - Brandon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接