public async Task HandleReactionAsync(ulong userId, ulong messageId, ulong channelId, IEmoji emoji, bool add) { // TODO: Cache valid reactions to reduce DB calls using (var db = new DataContext()) { Stopwatch sw = new Stopwatch(); sw.Start(); if (_cache.ExistsIgnore <ReactableRoleMessage>(messageId)) { return; } var messageMatch = _cache.Retrieve <ReactableRoleMessage>(x => x.ChannelId == channelId && x.MessageId == messageId); if (messageMatch == null) { messageMatch = db.RoleMessages.FirstOrDefault(x => x.ChannelId == channelId && x.MessageId == messageId); if (messageMatch != null) { // Populate cache _cache.Put(messageMatch, TimeSpan.FromHours(1)); } } if (messageMatch == null) { _cache.PutIgnore <ReactableRoleMessage>(TimeSpan.FromHours(1), messageId); return; } AssignableRole roleMatch; if (emoji is CustomEmoji ce) { if (_cache.ExistsIgnore <AssignableRole>(messageMatch.GuildId, ce.Id.RawValue)) { return; } roleMatch = _cache.Retrieve <AssignableRole>(x => x.GuildId == messageMatch.GuildId && x.EmojiId == ce.Id.RawValue) ?? db.Roles.FirstOrDefault(x => x.GuildId == messageMatch.GuildId && x.EmojiId == ce.Id.RawValue); if (roleMatch == null) { _cache.PutIgnore <AssignableRole>(TimeSpan.FromHours(1), messageMatch.GuildId, ce.Id.RawValue); return; } } else if (emoji is Emoji em) { if (_cache.ExistsIgnore <AssignableRole>(messageMatch.GuildId, em.Name)) { return; } roleMatch = _cache.Retrieve <AssignableRole>(x => x.GuildId == messageMatch.GuildId && x.EmojiName == em.Name) ?? db.Roles.FirstOrDefault(x => x.GuildId == messageMatch.GuildId && x.EmojiName == em.Name); if (roleMatch == null) { _cache.PutIgnore <AssignableRole>(TimeSpan.FromHours(1), messageMatch.GuildId, em.Name); return; } } else { return; } _cache.Put(roleMatch, TimeSpan.FromHours(1)); #if DEBUG await Bot.SendMessageAsync(channelId, $"{sw.ElapsedMilliseconds}ms elapsed"); #endif if (add) { await Bot.GrantRoleAsync(messageMatch.GuildId, userId, roleMatch.RoleId); } else { await Bot.RevokeRoleAsync(messageMatch.GuildId, userId, roleMatch.RoleId); } } }