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

Discord.js斜杠命令推送失败求助:命令未加载且报错

问题解决:Discord斜杠命令推送失败与Chalk报错

1. 修复chalk.blue is not a function报错

Chalk v5+版本为ES模块,动态import后需解构默认导出,或改用CommonJS的require方式适配现有代码:

方案一:改用CommonJS引入

删除原动态import代码,替换为:

const chalk = require('chalk');

方案二:正确使用动态import

若坚持ES模块方式,需解构获取默认导出:

import('chalk').then(({ default: chalk }) => {
  // 后续逻辑不变
});

2. 修复异步遍历导致的命令未推送问题

fs.readdirSync(...).forEach(async dir => {})中,forEach不会等待异步操作完成,导致slashCommands数组未填充完毕就执行推送请求,Discord接收空/不完整数组。改用同步遍历:

// 替换原forEach代码块
const dirs = fs.readdirSync('/home/container/src/slashCommands/');
for (const dir of dirs) {
  const files = fs.readdirSync(`/home/container/src/slashCommands/${dir}/`).filter(file => file.endsWith('.js'));
  for (const file of files) {
    const slashCommand = require(`/home/container/src/slashCommands/${dir}/${file}`);
    slashCommands.push({
      name: slashCommand.name,
      description: slashCommand.description,
      options: slashCommand.options ?? [], // 用空数组替代null,符合API规范
      default_member_permissions: slashCommand.default_member_permissions ? PermissionsBitField.resolve(slashCommand.default_member_permissions).toString() : null
    });

    if (slashCommand.name) {
      client.slashCommands.set(slashCommand.name, slashCommand);
      table.addRow(file.split('.js')[0], '✅');
    } else {
      table.addRow(file.split('.js')[0], '⛔');
    }
  }
}

3. 移除废弃API字段

default_permission字段在Discord API v9中已废弃,直接从推送对象中删除该属性,避免API报错。

4. 确保机器人权限与推送范围

  • 机器人邀请链接必须包含applications.commands权限,否则无法显示斜杠命令徽章及使用命令
  • 若使用服务器专属命令(指定GUILD_ID),需确保机器人已加入目标服务器,且你拥有服务器管理员权限

修正后的完整代码

module.exports = (client) => {
    const fs = require('fs');
    const chalk = require('chalk');

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

    const AsciiTable = require('ascii-table');
    const table = new AsciiTable().setHeading('Slash Commands', 'Stats').setBorder('|', '=', "0", "0");

    const TOKEN = process.env.BOT_TOKEN;
    const CLIENT_ID = process.env.CLIENT_ID;

    const rest = new REST({ version: '9' }).setToken(TOKEN);

    const slashCommands = []; 
    const dirs = fs.readdirSync('/home/container/src/slashCommands/');
    
    for (const dir of dirs) {
        const files = fs.readdirSync(`/home/container/src/slashCommands/${dir}/`).filter(file => file.endsWith('.js'));
        for (const file of files) {
            const slashCommand = require(`/home/container/src/slashCommands/${dir}/${file}`);
            slashCommands.push({
                name: slashCommand.name,
                description: slashCommand.description,
                options: slashCommand.options ?? [],
                default_member_permissions: slashCommand.default_member_permissions ? PermissionsBitField.resolve(slashCommand.default_member_permissions).toString() : null
            });

            if (slashCommand.name) {
                client.slashCommands.set(slashCommand.name, slashCommand);
                table.addRow(file.split('.js')[0], '✅');
            } else {
                table.addRow(file.split('.js')[0], '⛔');
            }
        }
    }

    console.log(chalk.blue(table.toString()));

    (async () => {
        try {
            await rest.put(
                process.env.GUILD_ID ?
                Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID) :
                Routes.applicationCommands(CLIENT_ID), 
                { body: slashCommands }
            );
            console.log(chalk.green('Successfully registered application commands.'));
        } catch (error) {
            console.error(error);
        }
    })();
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 00:30:55