diff --git a/ChaosBot/Discord/Modules/Admin/Role.cs b/ChaosBot/Discord/Modules/Admin/Role.cs new file mode 100644 index 0000000..bf99aa7 --- /dev/null +++ b/ChaosBot/Discord/Modules/Admin/Role.cs @@ -0,0 +1,94 @@ +using System; +using Discord; +using Discord.Commands; +using System.Threading.Tasks; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using ChaosBot.Discord.PreConditions; +using ChaosBot.Models; +using Microsoft.EntityFrameworkCore; +using NLog; + +namespace ChaosBot.Discord.Modules.Admin +{ + public class Role : ModuleBase + { + private static readonly ILogger Logger = Program.Logger; + + [Command("role add")] + [CheckCommandPerm("Admin")] + public async Task RoleAddCommand(params string[] parameters) + { + try + { + await using (ChaosbotContext dbContext = new ChaosbotContext()) + { + string parameterString = String.Join("", parameters); + + // Fetch last message + IMessage message = (await Context.Channel.GetMessagesAsync(2).FlattenAsync()).Last(); + + // Parse parameters + string pattern = @"((|[^<]+)<@&(\d+)>)"; + string input = parameterString; + + foreach (Match m in Regex.Matches(input, pattern)) + { + try + { + IEmote emote; + string emoteString = m.Groups[2].Value; + string roleString = m.Groups[3].Value; + IRole role = Context.Guild.Roles.First(r => r.Id.ToString() == roleString); + + if (Emote.TryParse(emoteString, out Emote tempEmote)) + { + if (tempEmote.Animated && Context.Client.CurrentUser.PremiumType != PremiumType.Nitro) + throw new NotSupportedException("No support for animated icons"); + + if (Context.Guild.Emotes.All(e => e.Id != tempEmote.Id) && + Context.Client.CurrentUser.PremiumType != PremiumType.Nitro) + throw new NotSupportedException($"No support for emotes from other servers"); + + emote = tempEmote; + } + else + { + emote = new Emoji(emoteString); + } + + // Register DB entry + RoleReaction roleReaction = new RoleReaction + { + DiscordGuildId = Context.Guild.Id, + DiscordMessageId = message.Id, + DiscordRoleId = role.Id, + DiscordEmoteName = emote.ToString() + }; + + await dbContext.RoleReactions.Upsert(roleReaction) + .On(r => new {r.DiscordGuildId, r.DiscordEmoteNameEncoded, r.DiscordMessageId, r.DiscordRoleId}) + .RunAsync(); + + // Add reaction to message + await message.AddReactionAsync(emote); + } + catch (Exception ex) + { + await ReplyAsync($"Something went wrong trying to process {m.Value}: {ex.Message}"); + Logger.Error( + $"{MethodBase.GetCurrentMethod().ReflectedType.FullName}: Exception [{ex}] thrown, <[{ex.Message}]>."); + } + } + + await dbContext.SaveChangesAsync(); + } + } + catch (Exception ex) + { + Logger.Error($"{MethodBase.GetCurrentMethod().ReflectedType.FullName}: Exception [{ex}] thrown, <[{ex.Message}]>."); + } + } + } +} \ No newline at end of file