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

Discord.js注册的Slash Command未在Discord命令UI显示求助

Discord.js 斜杠命令无法在服务器UI中显示的问题排查与解决

问题描述

使用Discord.js开发Discord机器人,已将机器人以管理员权限邀请至服务器,代码中注册了简单的ping斜杠命令,但该命令未在Discord的命令UI中显示。相关代码如下:

import "dotenv/config";

import { Client, GatewayIntentBits, SlashCommandBuilder } from "discord.js";

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
  ],
});

client.on("ready", () => {
  console.log("Bot is ready!");

  const ping = new SlashCommandBuilder()
    .setName("ping")
    .setDescription("Using this command will ping!");

  client.application.commands
    .create(ping)
    .then(() => console.log("Done registering commands"))
    .catch((error) => console.log(error));
});

client.on("messageCreate", (message) => {
  const isSelfMessaged = message.author.id === client.user.id;
  if (isSelfMessaged) return;

  message.reply("Hello there!");
});

client.on("interactionCreate", (interaction) => {
  if (!interaction.isChatInputCommand()) return;
  if (interaction.commandName === "ping") {
    interaction.channel.send(`Pong! ${interaction.user}`);
  }
});

client.login(process.env.TOKEN);

期望ping命令能像其他机器人(如Fredbot)的命令一样在UI中显示,但目前仅能看到其他机器人的命令,自己的机器人命令未出现。

解决方案

1. 优先使用服务器级命令测试(即时生效)

当前代码使用client.application.commands.create()注册的是全局命令,全局命令需要Discord跨服务器同步,生效时间通常在1小时以上。测试阶段建议改用服务器级命令,注册后立即生效:

client.on("ready", () => {
  console.log("Bot is ready!");
  const targetGuildId = "你的目标服务器ID"; // 替换为实际服务器ID
  const ping = new SlashCommandBuilder()
    .setName("ping")
    .setDescription("Using this command will ping!");

  // 注册到指定服务器
  client.guilds.cache.get(targetGuildId)?.commands
    .create(ping)
    .then(() => console.log("服务器命令注册完成"))
    .catch((error) => console.log(error));
});

2. 确认邀请链接包含applications.commands权限

邀请机器人时,链接必须包含applications.commands权限,否则机器人无法在服务器内注册和显示斜杠命令。正确的邀请链接参数需包含:

  • scope=bot+applications.commands
  • permissions=8(8代表管理员权限)
    如果之前的邀请链接缺少该权限,需重新生成链接并邀请机器人。

3. 检查命令注册的错误日志

查看控制台输出,若client.application.commands.create()执行时抛出错误,会直接打印在控制台,可根据错误信息排查问题(比如权限不足、命令名称不符合Discord规范等)。

4. 修正交互响应逻辑

当前代码中用interaction.channel.send()响应斜杠命令会触发错误,斜杠命令必须使用interaction.reply()来响应:

client.on("interactionCreate", (interaction) => {
  if (!interaction.isChatInputCommand()) return;
  if (interaction.commandName === "ping") {
    interaction.reply(`Pong! ${interaction.user}`);
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 00:51:08