From d7d0e22bfa87bdee1cad30cdda1a19c7b38d8027 Mon Sep 17 00:00:00 2001 From: Lala Sabathil Date: Mon, 16 Oct 2023 18:45:09 +0200 Subject: [PATCH] Create RequireAnyPermissionsAttribute.cs --- .../RequireAnyPermissionsAttribute.cs | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 DisCatSharp.ApplicationCommands/Attributes/RequireAnyPermissionsAttribute.cs diff --git a/DisCatSharp.ApplicationCommands/Attributes/RequireAnyPermissionsAttribute.cs b/DisCatSharp.ApplicationCommands/Attributes/RequireAnyPermissionsAttribute.cs new file mode 100644 index 000000000..124679b3c --- /dev/null +++ b/DisCatSharp.ApplicationCommands/Attributes/RequireAnyPermissionsAttribute.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +using DisCatSharp.ApplicationCommands.Context; +using DisCatSharp.Enums; + +namespace DisCatSharp.ApplicationCommands.Attributes; + +/// +/// Defines that usage of this application command is restricted to members with any of the specified permissions. This check also verifies that the bot has the same permissions. +/// +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)] +public sealed class RequireAnyPermissionsAttribute : ApplicationCommandCheckBaseAttribute +{ + /// + /// Gets the permissions required by this attribute. + /// + public List AnyPermissions { get; } + + /// + /// Defines that usage of this command is restricted to members with any of the specified permissions. This check also verifies that the bot has the same permissions. + /// + /// Permissions required to execute this command. + public RequireAnyPermissionsAttribute(params Permissions[] permissions) + { + this.AnyPermissions = permissions.ToList(); + } + + /// + /// Runs checks. + /// + public override async Task ExecuteChecksAsync(BaseContext ctx) + { + if (ctx.Guild == null) + throw new InvalidOperationException("This check cannot be used in a DM."); + + var usr = ctx.Member; + if (usr == null) + return false; + + var pusr = ctx.Channel.PermissionsFor(usr); + + var bot = await ctx.Guild.GetMemberAsync(ctx.Client.CurrentUser.Id).ConfigureAwait(false); + if (bot == null) + return false; + + var pbot = ctx.Channel.PermissionsFor(bot); + + var usrok = ctx.Guild.OwnerId == usr.Id || pusr.HasPermission(Permissions.Administrator); + var botok = ctx.Guild.OwnerId == bot.Id || pusr.HasPermission(Permissions.Administrator); + + if (!usrok) + usrok = this.AnyPermissions.Any(x => (pusr & x) != 0); + if (!botok) + botok = this.AnyPermissions.Any(x => (pbot & x) != 0); + + return usrok && botok; + } +}