Search code examples
discordpermissionsbotslimitdsharp+

What's the best way to restrict bot commands to a certain role/user in DSharpPlus?


I'm using DSharpPlus to build a Discord bot. I want some commands, such as !status to be available to everyone / all roles. But I want other commands, like !start to be limited to certain roles/users.

I found this article which discusses it a little bit. If I use AddRoleAsync will it save the permissions to the Discord server? How can I have the bot join a server but only allow certain roles/users to use certain commands? Also, can I restrict the bot to only join certain channels? like an admin/mod channel?

Thank you


Solution

  • If you use Dsharpplus.CommandsNext.Attributes this is actually pretty easy!

    You can assign an attribute to your code as below, which would require you to have the Discord admin permission to use this command.

    [Command("greet")]
    [RequirePermissions(DSharpPlus.Permissions.Administrator)]
    public async Task GreetCommand(CommandContext ctx)
    {
        await ctx.RespondAsync("Greetings! Thank you for executing me!");
    }
    

    There are many attributes under DSharpPlus.Permissions that you can use to customize the control over who can use a command, but note that All and None are literal, you either need all of the permission there are (the server owner) or none of the permission.