You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js如何删除斜杠命令响应 能否设置斜杠命令冷却

删除斜杠命令响应的实现方法

你当前使用type:4返回的是交互的原始回复,可通过调用webhook消息删除接口实现删除,示例如下:

client.ws.on('INTERACTION_CREATE', async interaction => {
    const command = interaction.data.name.toLowerCase();
    const args = interaction.data.options;

    if (command === 'test'){ 
        console.log("Test executed")
        
        await client.api.interactions(interaction.id, interaction.token).callback.post({
            data: {
                type: 4,
                data: {
                    content: "Check"
                }
            }
        })

        // 新增以下代码实现3秒后自动删除响应,不需要延迟就去掉setTimeout直接调用delete方法
        setTimeout(async () => {
            await client.api.webhooks(client.user.id, interaction.token).messages('@original').delete();
        }, 3000)
    }
});
斜杠命令冷却时间的实现方法

可以通过Map缓存用户的冷却状态实现,不需要依赖额外工具包,完整代码示例如下:

// 全局初始化冷却缓存,不要放在事件监听内部
const cooldowns = new Map();
// 自定义test命令冷却时长,单位为秒
const TEST_COOLDOWN = 10;

client.ws.on('INTERACTION_CREATE', async interaction => {
    const command = interaction.data.name.toLowerCase();
    const args = interaction.data.options;

    if (command === 'test'){ 
        // 冷却校验逻辑
        if (!cooldowns.has('test')) {
            cooldowns.set('test', new Map());
        }
        const currentUserCooldown = cooldowns.get('test');
        const now = Date.now();
        const userId = interaction.member.user.id;

        if (currentUserCooldown.has(userId)) {
            const expireTime = currentUserCooldown.get(userId);
            if (now < expireTime) {
                const leftTime = ((expireTime - now) / 1000).toFixed(1);
                // 返回冷却提示,flags:64表示仅触发命令的用户可见该提示
                return client.api.interactions(interaction.id, interaction.token).callback.post({
                    data: {
                        type: 4,
                        data: {
                            content: `请等待${leftTime}秒后再使用test命令`,
                            flags: 64
                        }
                    }
                })
            }
        }

        // 写入冷却记录
        currentUserCooldown.set(userId, now + TEST_COOLDOWN * 1000);
        // 冷却到期自动清除记录
        setTimeout(() => currentUserCooldown.delete(userId), TEST_COOLDOWN * 1000);

        // 原有执行逻辑
        console.log("Test executed")
        await client.api.interactions(interaction.id, interaction.token).callback.post({
            data: {
                type: 4,
                data: {
                    content: "Check"
                }
            }
        })

        // 之前的删除响应逻辑
        setTimeout(async () => {
            await client.api.webhooks(client.user.id, interaction.token).messages('@original').delete();
        }, 3000)
    }
});

内容的提问来源于stack exchange,提问作者Clementinise

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 18:48:03