You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何将Discord斜杠命令限制为仅特定单个用户使用?

实现仅对单个特定用户开放的Discord斜杠命令

Discord官方没有提供直接指定单个用户可见斜杠命令的配置项,但可以通过命令权限隐藏+执行前ID校验的组合方式实现需求,具体操作如下:

  1. 保留setDefaultMemberPermissions(0)设置,让命令默认对所有用户不可见,不会出现在其他人的命令列表中
  2. 在命令执行逻辑最前端加入用户ID校验,仅允许指定ID的用户执行命令,其他用户直接拦截

修改后的完整代码示例

import { SlashCommandBuilder, ChatInputCommandInteraction, SlashCommandUserOption } from 'discord.js';

// 替换为你要授权的特定用户的Discord ID
const ALLOWED_USER_ID = "123456789012345678";

export const protectCommand = {
  data: new SlashCommandBuilder()
    .setName("protect")
    .setDescription("Protect a user from all visits")
    .setDefaultMemberPermissions(0) // 禁止所有用户默认看到此命令
    .addUserOption(
      (option): SlashCommandUserOption =>
        option.setName("target").setDescription("The user you wish to protect").setRequired(true),
    ),
  async execute(interaction: ChatInputCommandInteraction) {
    // 核心校验:仅指定用户可执行
    if (interaction.user.id !== ALLOWED_USER_ID) {
      // 回复仅用户可见的提示,避免公开暴露命令存在
      return await interaction.reply({ 
        content: "你无权使用此命令", 
        ephemeral: true 
      });
    }

    // 原命令业务逻辑
    const target = interaction.options.getUser("target");
    await interaction.reply(`你已选择保护 ${target?.username}!`);
  },
};

关键细节说明

  • 用户ID校验:直接通过interaction.user.id与预设的允许ID对比,无需依赖任何角色,完全保密
  • 命令隐藏setDefaultMemberPermissions(0)会让命令不在普通用户的命令菜单中显示,只有知道命令名的用户才能尝试触发
  • 隐蔽回复:使用ephemeral: true的回复仅触发者可见,不会在频道中留下痕迹,进一步强化命令的保密性

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

火山引擎 最新活动