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

Discord.js命令启停功能异常:MongoDB未正确生效问题排查

Discord.js命令禁用功能失效问题排查与修复

问题根源分析

  1. 事件监听未触发:你定义的事件名称是interactionCreate1,但Discord.js的官方交互事件名是interactionCreate,这个自定义名称不会被Bot触发,导致你的禁用逻辑完全没在运行,原命令依然正常执行。
  2. 服务器ID查询错误:代码里用guild.message.id作为查询条件,但guild参数传递大概率有误,而且交互对象本身自带interaction.guildId属性,这才是正确的服务器唯一标识。错误的查询条件导致无法匹配到数据库中存储的禁用命令记录,判断逻辑形同虚设。
  3. 冗余代码:重复引入了同一个MongoDB模型(db和schema),属于不必要的冗余。

修复后的代码

const client = require("../../index");
const { ChatInputCommandInteraction } = require('discord.js');
const db = require("../../models/salvage/command");

module.exports = {
    name: "interactionCreate", // 修正事件名称
    /**
     * 
     * @param {ChatInputCommandInteraction} interaction 
     */
    async execute(interaction, client) { // 移除多余的guild参数,直接从interaction获取服务器信息
        if(!interaction.isChatInputCommand()) return;
        const command = client.commands.get(interaction.commandName);
        if (!command) return; // 增加命令存在性判断,避免报错

        // 使用正确的服务器ID查询数据库
        const check = await db.findOne({ Guild: interaction.guildId });
        if(check) {
            // 检查当前命令是否在禁用列表中
            if(check.Cmds.includes(interaction.commandName)) {
                return interaction.reply({content: "Comando desactivado!", ephemeral: true}); // 建议添加ephemeral:true,只有用户自己能看到提示
            }
            command.execute(interaction, client);
        } else {
            command.execute(interaction, client);
        }
    }
}

验证步骤

  1. 确保事件文件放在Bot的事件加载目录下,Bot启动时能正确加载这个interactionCreate事件。
  2. 执行禁用命令后,查看MongoDB中对应服务器的文档,确认Cmds数组里已经添加了目标命令名称。
  3. 重启Bot,测试禁用的命令,此时应该只会收到提示,命令不会执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:30:48