typescriptdiscorddiscord.js

How can I limit a slash command to only one, specific user?


I'm writing a Discord bot using TypeScript and Discord.js to implement a game.

As part of the game, I would like certain commands to be secret - they should be restricted to one user only, and the user should not have a role to indicate they have access to this command. I cannot find anything in the guide or the docs about how to accomplish this, or if it is possible.

Here is an example slash command, which is visible only to admins. This works, but I do not know how to make it work for only a specific user.

{
  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) {
    const target = interaction.options.getUser("target");
    await interaction.reply(`You have selected ${target?.username}!`);
  },
}

Solution

  • Turns out there is a way to do this using the Discord app itself.

    1. Set your command to be invisible to all members except admins by adding .setDefaultMemberPermissions(0) to its data property, e.g.
    {
      data: new SlashCommandBuilder()
        .setName("protect")
        .setDescription("Protect a user from all visits")
        .setDefaultMemberPermissions(0)
        ),
      async execute(interaction: ChatInputCommandInteraction) {
        // action execution code...
      },
    }
    
    1. Go into your Server Settings and select the 'Integrations' panel.
    2. Select your bot, and you will see a 'Commands' section.
    3. Click on the command you want to customise. You will now see a panel where you can configure overrides.
    4. Select 'Add roles or members', then select the member you want to give access to. You can now see the user listed under 'Role & member overrides'.

    I do not believe there is a way to do this in a programmatic manner using Discord.js, but this option fits my use case.