From d7c997f0cf866d847455df92ef2fd820945d79b9 Mon Sep 17 00:00:00 2001 From: Sean Stoves Date: Mon, 15 Jun 2020 21:33:10 -0400 Subject: [PATCH] Adding Dynamic Permission PreCondition node --- ChaosBot/Discord/Modules/ConfigCommands.cs | 4 +-- ChaosBot/Discord/Services/RequireRole.cs | 42 ++++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 ChaosBot/Discord/Services/RequireRole.cs diff --git a/ChaosBot/Discord/Modules/ConfigCommands.cs b/ChaosBot/Discord/Modules/ConfigCommands.cs index 64bafce..e81820b 100644 --- a/ChaosBot/Discord/Modules/ConfigCommands.cs +++ b/ChaosBot/Discord/Modules/ConfigCommands.cs @@ -2,7 +2,6 @@ using Discord; using Discord.Commands; using System.Threading.Tasks; -using System.Collections.Generic; using NLog; using System.Text; using ChaosBot.Database.Repository; @@ -15,8 +14,7 @@ namespace ChaosBot.Discord.Modules private static readonly string _prefix = ConfigurationRepository.GetValue("Discord:Prefix"); [Command("config")] - [RequireBotPermission(GuildPermission.ManageGuild)] - [RequireUserPermission(GuildPermission.ManageGuild)] + [RequireRole("Admin")] public async Task setConfig(string configFlag = null, string value = null) { var sb = new StringBuilder(); diff --git a/ChaosBot/Discord/Services/RequireRole.cs b/ChaosBot/Discord/Services/RequireRole.cs new file mode 100644 index 0000000..9fdfc63 --- /dev/null +++ b/ChaosBot/Discord/Services/RequireRole.cs @@ -0,0 +1,42 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using ChaosBot; +using ChaosBot.Database.Repository; +using Discord.Commands; +using Discord.WebSocket; + +public class RequireRole : PreconditionAttribute +{ + private string _name { get; set; } + + public RequireRole(string name) => _name = name; + + public override Task CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) + { + if (context.User is SocketGuildUser gUser) + { + switch (_name) + { + case "Admin": + _name = ConfigurationRepository.GetValue("Role:Admin", context.Guild.Id); + break; + case "Officer": + _name = ConfigurationRepository.GetValue("Role:Officer", context.Guild.Id); + break; + case "Member": + _name = ConfigurationRepository.GetValue("Role:Member", context.Guild.Id); + break; + default: + return Task.FromResult(PreconditionResult.FromError($"{_name} is not a valid Permission Node.")); + } + + if (gUser.Roles.Any(r => r.Name == _name)) + return Task.FromResult(PreconditionResult.FromSuccess()); + else + return Task.FromResult(PreconditionResult.FromError($"You must have a role named {_name} to run this command.")); + } + else + return Task.FromResult(PreconditionResult.FromError("You must be in a guild to run this command.")); + } +} \ No newline at end of file