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

discord.js机器人Slashcommands斜杠命令无响应无报错技术求助

问题根因及修复方案

1. 命令目录读取规则错误

你在index.js中读取命令目录时错误过滤了.js后缀,commands目录下存储的是分类文件夹而非js文件,过滤规则会导致无法读取到任何命令分类。
同时你调用handleEvents、handleCommands两个方法时参数完全传反,路径匹配失效。

2. 命令序列化错误

handleCommands.js中向注册队列推送命令时,没有调用toJSON()方法,仅传入了函数本身,导致向Discord接口提交的命令格式错误。

3. 路径不统一

你的项目结构中业务代码存放在public目录,但代码中读取的是src目录,需要先统一目录命名,建议将public重命名为src和代码路径保持一致。


修正后的核心代码

index.js

const { Client, Intents, Collection } = require('discord.js');
const fs = require('fs');
require('dotenv').config();

const client = new Client({ intents:[Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

client.commands = new Collection();

const functions = fs.readdirSync('./src/functions').filter(file => file.endsWith('.js'));
// 去掉js后缀过滤,读取分类文件夹
const commandsFolder = fs.readdirSync('./src/commands');
const eventFiles = fs.readdirSync('./src/events').filter(file => file.endsWith('.js'));

client.once('ready', () => {
    client.user.setPresence({ activities: [{ name: 'i am stuck ' }], status: 'dnd' });
});

(async () => {
    for (const file of functions) {
        require(`./src/functions/${file}`)(client);
    }
    // 修正参数传递顺序
    client.handleEvents(eventFiles);
    client.handleCommands(commandsFolder, './src/commands');
    client.login(process.env.token);
})();

functions/handleCommands.js

// 仅展示需要修改的片段
for (const file of commandFiles) {
    const command = require(`../commands/${folder}/${file}`);
    client.commands.set(command.data.name, command);
    // 调用toJSON()方法序列化命令
    client.commandArray.push(command.data.toJSON());
}

修复完成后重启机器人,等待1-2分钟待Discord服务器刷新命令列表,即可正常使用/ping命令。
内容的提问来源于stack exchange,提问作者MunJitso

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 11:06:01