Discord.js v14斜杠命令异常:加载错误目录下的命令
问题:Discord.js 斜杠命令部署与执行目录不符的错误
我多次尝试解决这个问题都没成功,情况如下:
部署代码
const { REST, Routes } = require('discord.js'); const fs = require('node:fs'); const { client_id } = require('./config.json') const commands = []; // Grab all the command files from the commands directory you created earlier const commandFiles = fs.readdirSync('./slashCommands').filter(file => file.endsWith('.js')); // Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment for (const file of commandFiles) { const command = require(`./slashCommands/${file}`); commands.push(command.data.toJSON()); } // Construct and prepare an instance of the REST module const rest = new REST({ version: '10' }).setToken(process.env.TOKEN); // and deploy your commands! (async () => { try { console.log(`Started refreshing ${commands.length} application (/) commands.`); // The put method is used to fully refresh all commands in the guild with the current set const data = await rest.put( Routes.applicationCommands(client_id), { body: commands }, ); console.log(`Successfully reloaded ${data.length} application (/) commands.`); } catch (error) { // And of course, make sure you catch and log any errors! console.error(error); } })();
执行错误
运行node deploy-commands.js后显示部署成功,但调用斜杠命令/ping时触发以下错误:
/home/runner/Nocinel/commands/ping.js:8 message.reply('🏓 **Ball is going over the net...**').then(m => { m.edit(`**🏓 Pong!\n:stopwatch: Uptime: ${Math.round(message.client.uptime / 60000)} minutes\n:sparkling_heart: Websocket Heartbeat: ${message.client.ws.ping}ms\n:round_pushpin: Rountrip Latency: ${m.createdTimestamp - message.createdTimestamp}ms**`) }); ^ TypeError: m.edit is not a function at /home/runner/Nocinel/commands/ping.js:8:73 repl process died unexpectedly: exit status 1
核心问题
错误显示程序正在执行commands目录下的ping.js,但我的部署代码明确指定从slashCommands目录加载命令。我已经尝试过重启程序、删除冗余文件、等待超过一小时并多次测试,结果完全一致,找不到代码里的问题。
解决方案
检查客户端命令加载逻辑:部署脚本仅负责把命令注册到Discord服务器,实际执行命令的是你的Discord客户端程序。要确认客户端代码是否错误加载了
commands目录的文件,而非slashCommands。比如客户端里可能存在以下错误逻辑:// 错误路径,需改为./slashCommands const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));修正斜杠命令代码逻辑:旧版
message对象的逻辑不适用于斜杠命令,slashCommands/ping.js需改用interaction对象编写,示例如下:const { SlashCommandBuilder } = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('ping') .setDescription('Replies with Pong!'), async execute(interaction) { await interaction.reply('🏓 **Ball is going over the net...**'); await interaction.editReply(`**🏓 Pong!\n:stopwatch: Uptime: ${Math.round(interaction.client.uptime / 60000)} minutes\n:sparkling_heart: Websocket Heartbeat: ${interaction.client.ws.ping}ms\n:round_pushpin: Rountrip Latency: ${Date.now() - interaction.createdTimestamp}ms**`); }, };清理旧命令残留:若之前部署过
commands目录的旧命令,需重新运行部署脚本覆盖,或在Discord开发者门户手动删除冗余命令。
内容的提问来源于stack exchange,提问作者Lenin
相关产品推荐
相关产品推荐

