예제 #1
0
        public async Task <Tuple <List <string>, List <string> > > RemoveSelfunverifyDefinitions(SocketGuild guild, string group, string[] values)
        {
            var config = await GrillBotRepository.ConfigRepository.FindConfigAsync(guild.Id, "selfunverify", null, false);

            var jsonData = config.GetData <SelfUnverifyConfig>();

            if (!jsonData.RolesToKeep.ContainsKey(group))
            {
                throw new ValidationException($"Skupina `{group}` neexistuje.");
            }

            var exists    = values.Where(o => jsonData.RolesToKeep[group].Contains(o)).ToList();
            var notExists = values.Where(o => !jsonData.RolesToKeep[group].Contains(o)).ToList();

            foreach (var item in exists)
            {
                jsonData.RolesToKeep[group].Remove(item);
            }

            if (jsonData.RolesToKeep[group].Count == 0)
            {
                jsonData.RolesToKeep.Remove(group);
            }

            config.Config = JObject.FromObject(jsonData);
            await GrillBotRepository.CommitAsync();

            return(Tuple.Create(exists, notExists));
        }
예제 #2
0
        public async Task AnylyzeMessageAndIncrementValuesAsync(SocketCommandContext context)
        {
            if (context.Guild == null)
            {
                return;
            }

            var mentionedEmotes = context.Message.Tags.Where(o => o.Type == TagType.Emoji)
                                  .Select(o => o.Value)
                                  .DistinctBy(o => o.ToString());

            var userEntity = await GrillBotRepository.UsersRepository.GetOrCreateUserAsync(context.Guild.Id, context.User.Id, UsersIncludes.Emotes);

            TryIncrementUnicodeFromMessage(context.Message.Content, userEntity);
            foreach (var emote in mentionedEmotes)
            {
                if (emote is DiscordEmoji emoji)
                {
                    IncrementCounter(emoji.Name, true, userEntity);
                }
                else
                {
                    var emoteId = emote.ToString();

                    if (context.Guild.Emotes.Any(o => o.ToString() == emoteId))
                    {
                        IncrementCounter(emoteId, false, userEntity);
                    }
                }
            }

            await GrillBotRepository.CommitAsync();
        }
예제 #3
0
        public async Task RemoveUnverifyFromWebAsync(long userId, SocketGuildUser fromUser)
        {
            var unverify = await GrillBotRepository.UnverifyRepository.FindUnverifyByID(userId);

            if (unverify == null)
            {
                return;
            }

            var guild = DiscordClient.GetGuild(unverify.User.GuildIDSnowflake);

            if (guild == null)
            {
                GrillBotRepository.Remove(unverify);
                await GrillBotRepository.CommitAsync();

                Queue.TryRemove <UnverifyBackgroundTask>(o => o.GuildId == unverify.User.GuildIDSnowflake && o.UserId == unverify.User.UserIDSnowflake);
                return;
            }

            var user = await guild.GetUserFromGuildAsync(unverify.User.UserIDSnowflake);

            if (user == null)
            {
                GrillBotRepository.Remove(unverify);
                await GrillBotRepository.CommitAsync();

                Queue.TryRemove <UnverifyBackgroundTask>(o => o.GuildId == guild.Id && o.UserId == unverify.User.UserIDSnowflake);
                return;
            }

            await RemoveUnverifyAsync(guild, user, fromUser);

            Queue.TryRemove <UnverifyBackgroundTask>(o => o.GuildId == guild.Id && o.UserId == user.Id);
        }
예제 #4
0
        public async Task PostponeReminderAsync(IUserMessage message, SocketReaction reaction)
        {
            if (!(message.Channel is IPrivateChannel))
            {
                return;
            }

            if (!await CanPostponeRemindAsync(message, reaction))
            {
                var logMessage = $"Embeds: {message.Embeds.Count}, IsEmoji: {reaction.Emote is Emoji}, Time: {DateTime.UtcNow - message.CreatedAt}";
                Logger.LogInformation($"Skipped postpone remind for {(reaction.User.IsSpecified ? $"UnknownUser({reaction.UserId})" : reaction.User.Value.Username)}\n{logMessage}");

                return;
            }

            var remind = await GrillBotRepository.ReminderRepository.FindReminderByMessageIdAsync(message.Id);

            if (remind == null)
            {
                return;
            }

            var hours = ReminderDefinitions.EmojiToHourNumberMapping[reaction.Emote as Emoji];

            remind.RemindMessageIDSnowflake = null;
            remind.At = DateTime.Now.AddHours(hours);
            remind.PostponeCounter++;

            await message.DeleteMessageAsync();

            await GrillBotRepository.CommitAsync();

            Queue.Add(new ReminderBackgroundTask(remind));
        }
예제 #5
0
        public async Task AddReplyAsync(SocketGuild guild, string mustContains, string reply, string compareType, bool disabled, bool caseSensitive, string channel)
        {
            if (BotState.AutoReplyItems.Any(o => o.MustContains == mustContains))
            {
                throw new ArgumentException($"Automatická odpověď **{mustContains}** již existuje.");
            }

            var item = new AutoReplyItem()
            {
                MustContains       = mustContains,
                IsDisabled         = disabled,
                ReplyMessage       = reply,
                CaseSensitive      = caseSensitive,
                GuildIDSnowflake   = guild.Id,
                ChannelIDSnowflake = channel == "*" ? (ulong?)null : Convert.ToUInt64(channel)
            };

            item.SetCompareType(compareType);

            await GrillBotRepository.AddAsync(item);

            await GrillBotRepository.CommitAsync();

            BotState.AutoReplyItems.Add(item);
        }
예제 #6
0
        public async Task <string> UpdateUnverifyAsync(SocketGuildUser user, SocketGuild guild, string time, SocketUser fromUser)
        {
            var task = Queue.Get <UnverifyBackgroundTask>(o => o.GuildId == guild.Id && o.UserId == user.Id);

            if (task == null)
            {
                throw new NotFoundException("Aktualizace času nelze pro hledaného uživatele provést. Unverify nenalezeno.");
            }

            if (task.CanProcess() || (task.At - DateTime.Now).TotalSeconds < 30.0D)
            {
                throw new ValidationException("Aktualizace data a času již není možná. Vypršel čas, nebo zbývá méně, než půl minuty.");
            }

            var endDateTime = TimeParser.Parse(time, minimumMinutes: 10);
            await UnverifyLogger.LogUpdateAsync(DateTime.Now, endDateTime, guild, fromUser, user);

            var userEntity = await GrillBotRepository.UsersRepository.GetUserAsync(guild.Id, user.Id, UsersIncludes.Unverify);

            userEntity.Unverify.EndDateTime   = endDateTime;
            userEntity.Unverify.StartDateTime = DateTime.Now;
            await GrillBotRepository.CommitAsync();

            task.At = endDateTime;

            var pmMessage = MessageGenerator.CreateUpdatePMMessage(guild, endDateTime);
            await user.SendPrivateMessageAsync(pmMessage);

            return(MessageGenerator.CreateUpdateChannelMessage(user, endDateTime));
        }
예제 #7
0
        public async Task EditReplyAsync(SocketGuild guild, int id, string mustContains, string reply, string compareType, bool caseSensitive, string channel)
        {
            var item = BotState.AutoReplyItems.Find(o => o.GuildIDSnowflake == guild.Id && o.ID == id);

            if (item == null)
            {
                throw new ArgumentException($"Automatická odpověď s ID **{id}** nebyla nalezena.");
            }

            var dbItem = await GrillBotRepository.AutoReplyRepository.FindItemByIdAsync(id);

            dbItem.MustContains  = mustContains;
            dbItem.ReplyMessage  = reply;
            dbItem.CaseSensitive = caseSensitive;
            dbItem.SetCompareType(compareType);
            dbItem.ChannelIDSnowflake = channel == "*" ? (ulong?)null : Convert.ToUInt64(channel);

            await GrillBotRepository.CommitAsync();

            item.MustContains       = dbItem.MustContains;
            item.ReplyMessage       = dbItem.ReplyMessage;
            item.CaseSensitive      = dbItem.CaseSensitive;
            item.CompareType        = dbItem.CompareType;
            item.ChannelIDSnowflake = dbItem.ChannelIDSnowflake;
        }
예제 #8
0
        public async Task LogMessageDeletedAsync(Cacheable <IMessage, ulong> message, ISocketMessageChannel channel, SocketGuild guild)
        {
            var deletedMessage = message.HasValue ? message.Value : MessageCache.TryRemove(message.Id);

            var entity = new AuditLogItem()
            {
                Type             = AuditLogType.MessageDeleted,
                CreatedAt        = DateTime.Now,
                GuildIdSnowflake = guild.Id,
            };

            if (deletedMessage == null)
            {
                entity.SetData(MessageDeletedAuditData.Create(channel));
            }
            else
            {
                await ProcessMessageDeletedWithCacheAsync(entity, channel, deletedMessage, guild);
            }

            if (MessageCache.Exists(message.Id))
            {
                MessageCache.TryRemove(message.Id);
            }

            await MessageCache.AppendAroundAsync(channel, message.Id, 100);

            await GrillBotRepository.AddAsync(entity);

            await GrillBotRepository.CommitAsync();
        }
예제 #9
0
        public async Task LogMessageEditedAsync(Cacheable <IMessage, ulong> before, SocketMessage after, ISocketMessageChannel channel, SocketGuild guild)
        {
            var oldMessage = before.HasValue ? before.Value : MessageCache.Get(before.Id);

            if (!IsMessageEdited(oldMessage, after))
            {
                return;
            }

            var userId = await UserSearchService.GetUserIDFromDiscordUserAsync(guild, after.Author);

            var entity = new AuditLogItem()
            {
                Type             = AuditLogType.MessageEdited,
                CreatedAt        = DateTime.Now,
                GuildIdSnowflake = guild.Id,
                UserId           = userId
            };

            entity.SetData(MessageEditedAuditData.Create(channel, oldMessage, after));
            await GrillBotRepository.AddAsync(entity);

            await GrillBotRepository.CommitAsync();

            MessageCache.Update(after);
        }
예제 #10
0
        public async Task IncrementFromReactionAsync(SocketReaction reaction)
        {
            if (reaction.Channel is not SocketGuildChannel channel)
            {
                return;
            }
            if (!reaction.User.IsSpecified || !reaction.User.Value.IsUser())
            {
                return;
            }

            var userEntity = await GrillBotRepository.UsersRepository.GetOrCreateUserAsync(channel.Guild.Id, reaction.UserId, UsersIncludes.Emotes);

            if (reaction.Emote is DiscordEmoji emoji)
            {
                IncrementCounter(emoji.Name, true, userEntity);
            }
            else
            {
                var emoteId = reaction.Emote.ToString();

                if (channel.Guild.Emotes.Any(o => o.ToString() == emoteId))
                {
                    IncrementCounter(reaction.Emote.ToString(), false, userEntity);
                }
            }

            await GrillBotRepository.CommitAsync();
        }
예제 #11
0
        public async Task SetImunityAsync(IGuild guild, IUser user, string groupName)
        {
            var dbUser = await GrillBotRepository.UsersRepository.GetOrCreateUserAsync(guild.Id, user.Id, UsersIncludes.None);

            dbUser.UnverifyImunityGroup = groupName;
            await GrillBotRepository.CommitAsync();
        }
예제 #12
0
        public async Task SetBotAdminAsync(SocketGuild guild, SocketUser user, bool isAdmin)
        {
            var entity = await GrillBotRepository.UsersRepository.GetOrCreateUserAsync(guild.Id, user.Id, UsersIncludes.None);

            entity.IsBotAdmin = isAdmin;

            await GrillBotRepository.CommitAsync();
        }
예제 #13
0
        public async Task RemoveImunityAsync(IGuild guild, IUser user)
        {
            var dbUser = await GrillBotRepository.UsersRepository.GetUserAsync(guild.Id, user.Id, UsersIncludes.None);

            if (string.IsNullOrEmpty(dbUser?.UnverifyImunityGroup))
            {
                throw new ValidationException($"Uživatel **{user.GetFullName()}** neměl imunitu vůči unverify.");
            }

            dbUser.UnverifyImunityGroup = null;
            await GrillBotRepository.CommitAsync();
        }
예제 #14
0
        public async Task <int> ClearOldDataAsync(DateTime before, SocketGuild guild)
        {
            var oldData = await GrillBotRepository.AuditLogs.GetAuditLogsBeforeDate(before, guild.Id).ToListAsync();

            foreach (var item in oldData.Where(o => o.Files.Count > 0))
            {
                GrillBotRepository.RemoveCollection(item.Files);
            }

            GrillBotRepository.RemoveCollection(oldData);
            await GrillBotRepository.CommitAsync();

            return(oldData.Count);
        }
예제 #15
0
        public async Task RemoveReplyAsync(SocketGuild guild, int id)
        {
            if (!BotState.AutoReplyItems.Any(o => o.GuildIDSnowflake == guild.Id && o.ID == id))
            {
                throw new ArgumentException($"Automatická odpověď s ID **{id}** neexistuje.");
            }

            var entity = await GrillBotRepository.AutoReplyRepository.FindItemByIdAsync(id);

            GrillBotRepository.Remove(entity);
            await GrillBotRepository.CommitAsync();

            BotState.AutoReplyItems.RemoveAll(o => o.ID == id);
        }
예제 #16
0
        public async Task TriggerReminder(long id, bool force)
        {
            var entity = await GrillBotRepository.ReminderRepository.FindReminderByIDAsync(id);

            if (entity == null)
            {
                return;
            }

            var message = await NotifyUserAsync(entity, force);

            entity.RemindMessageIDSnowflake = message?.Id;
            await GrillBotRepository.CommitAsync();
        }
예제 #17
0
        public async Task OnUserLeftGuildAsync(SocketGuildUser user)
        {
            Queue.TryRemove <UnverifyBackgroundTask>(o => o.GuildId == user.Guild.Id && o.UserId == user.Id);

            var unverify = await GrillBotRepository.UnverifyRepository.FindUnverifyByUser(user.Guild.Id, user.Id);

            if (unverify == null)
            {
                return;
            }

            GrillBotRepository.Remove(unverify);
            await GrillBotRepository.CommitAsync();
        }
예제 #18
0
        public async Task DeleteItemAsync(long id)
        {
            var item = await GrillBotRepository.AuditLogs.FindItemByIdAsync(id);

            if (item == null)
            {
                return;
            }

            if (item.Files.Count > 0)
            {
                GrillBotRepository.RemoveCollection(item.Files);
            }

            GrillBotRepository.Remove(item);
            await GrillBotRepository.CommitAsync();
        }
예제 #19
0
        public async Task AddSelfunverifyDefinitionsAsync(SocketGuild guild, string group, string[] values)
        {
            var config = await GrillBotRepository.ConfigRepository.FindConfigAsync(guild.Id, "selfunverify", null, false);

            var jsonData = config.GetData <SelfUnverifyConfig>();

            if (!jsonData.RolesToKeep.ContainsKey(group))
            {
                jsonData.RolesToKeep.Add(group, new List <string>());
            }

            jsonData.RolesToKeep[group].AddRange(values);
            jsonData.RolesToKeep[group] = jsonData.RolesToKeep[group].Distinct().ToList();

            config.Config = JObject.FromObject(jsonData);
            await GrillBotRepository.CommitAsync();
        }
예제 #20
0
        public async Task LogUserLeftAsync(SocketGuildUser user)
        {
            if (user == null)
            {
                return;
            }

            var ban = await user.Guild.FindBanAsync(user);

            RestAuditLogEntry dcAuditLogItem;

            if (ban != null)
            {
                dcAuditLogItem = (await user.Guild.GetAuditLogDataAsync(actionType: ActionType.Ban))?
                                 .FirstOrDefault(o => (o.Data as BanAuditLogData)?.Target.Id == user.Id);
            }
            else
            {
                dcAuditLogItem = (await user.Guild.GetAuditLogDataAsync(actionType: ActionType.Kick))?
                                 .FirstOrDefault(o => (o.Data as KickAuditLogData)?.Target.Id == user.Id);
            }

            long?executor = null;

            if (dcAuditLogItem != null)
            {
                executor = await UserSearchService.GetUserIDFromDiscordUserAsync(user.Guild, dcAuditLogItem.User);
            }

            var entity = new AuditLogItem()
            {
                Type             = AuditLogType.UserLeft,
                CreatedAt        = DateTime.Now,
                GuildIdSnowflake = user.Guild.Id,
                UserId           = executor
            };

            entity.SetData(UserLeftAuditData.Create(user.Guild, user, ban != null, ban?.Reason));
            await GrillBotRepository.AddAsync(entity);

            await GrillBotRepository.CommitAsync();
        }
예제 #21
0
        public async Task LogCommandAsync(Optional <CommandInfo> command, ICommandContext context)
        {
            if (context.Guild == null || !command.IsSpecified)
            {
                return;
            }

            var userId = await UserSearchService.GetUserIDFromDiscordUserAsync(context.Guild, context.User);

            var entity = new AuditLogItem()
            {
                Type             = AuditLogType.Command,
                CreatedAt        = DateTime.Now,
                GuildIdSnowflake = context.Guild.Id,
                UserId           = userId
            };

            entity.SetData(CommandAuditData.CreateDbItem(context, command.Value));
            await GrillBotRepository.AddAsync(entity);

            await GrillBotRepository.CommitAsync();
        }
예제 #22
0
        public async Task SetActiveStatusAsync(SocketGuild guild, int id, bool disabled)
        {
            var item = BotState.AutoReplyItems.Find(o => o.GuildIDSnowflake == guild.Id && o.ID == id);

            if (item == null)
            {
                throw new ArgumentException("Hledaná odpověď nebyla nalezena.");
            }

            if (item.IsDisabled == disabled)
            {
                throw new ArgumentException("Tato automatická odpověd již má požadovaný stav.");
            }

            var dbItem = await GrillBotRepository.AutoReplyRepository.FindItemByIdAsync(id);

            dbItem.IsDisabled = disabled;

            await GrillBotRepository.CommitAsync();

            item.IsDisabled = disabled;
        }
예제 #23
0
        public async Task AutoUnverifyRemoveAsync(ulong guildID, ulong userID)
        {
            try
            {
                var unverify = await GrillBotRepository.UnverifyRepository.FindUnverifyByUser(guildID, userID);

                if (unverify == null)
                {
                    return;
                }

                var guild = DiscordClient.GetGuild(guildID);

                if (guild == null)
                {
                    GrillBotRepository.Remove(unverify);
                    await GrillBotRepository.CommitAsync();

                    return;
                }

                var user = await guild.GetUserFromGuildAsync(userID);

                if (user == null)
                {
                    GrillBotRepository.Remove(unverify);
                    await GrillBotRepository.CommitAsync();

                    return;
                }

                await RemoveUnverifyAsync(guild, user, DiscordClient.CurrentUser, true);
            }
            catch (Exception ex)
            {
                var message = new LogMessage(LogSeverity.Error, nameof(UnverifyService), "An error occured when unverify returning access.", ex);
                await Logger.OnLogAsync(message);
            }
        }
예제 #24
0
        public async Task <List <string> > CleanOldEmotesAsync(SocketGuild guild)
        {
            await guild.SyncGuildAsync();

            var emoteClearCandidates = GrillBotRepository.EmoteStatsRepository.GetEmotesForClear(guild.Id, 14);

            if (emoteClearCandidates.Count == 0)
            {
                return(new List <string>());
            }

            var removed = new List <string>();

            foreach (var candidate in emoteClearCandidates)
            {
                if (candidate.IsUnicode)
                {
                    var formatedFirstOccured = candidate.FirstOccuredAt.ToLocaleDatetime();
                    var formatedLastOccured  = candidate.LastOccuredAt.ToLocaleDatetime();

                    removed.Add($"> Smazán unicode emote **{candidate.RealID}**. Použití: 0, Poprvé použit: {formatedFirstOccured}, Naposledy použit: {formatedLastOccured}");
                    await GrillBotRepository.EmoteStatsRepository.RemoveEmojiNoCommitAsync(guild, candidate.EmoteID);

                    continue;
                }

                var parsedEmote = Emote.Parse(candidate.RealID);
                if (!guild.Emotes.Any(o => o.Id == parsedEmote.Id))
                {
                    removed.Add($"> Smazán starý emote **{parsedEmote.Name}** ({parsedEmote.Id}). Použito {candidate.UseCount.FormatWithSpaces()}x.");
                    await GrillBotRepository.EmoteStatsRepository.RemoveEmojiNoCommitAsync(guild, candidate.RealID);
                }
            }

            await GrillBotRepository.CommitAsync();

            return(removed);
        }
예제 #25
0
        public async Task CreateReminderAsync(IGuild guild, IUser fromUser, IUser toUser, DateTime at, string message, IMessage originalMessage)
        {
            ValidateReminderCreation(at, message);

            var fromUserEntity = await GrillBotRepository.UsersRepository.GetOrCreateUserAsync(guild.Id, fromUser.Id, UsersIncludes.Reminders);

            await GrillBotRepository.CommitAsync();

            var toUserEntity = await GrillBotRepository.UsersRepository.GetOrCreateUserAsync(guild.Id, toUser.Id, UsersIncludes.Reminders);

            var remindEntity = new ReminderEntity()
            {
                At         = at,
                FromUserID = fromUser == toUser ? (long?)null : fromUserEntity.ID,
                Message    = message,
                OriginalMessageIDSnowflake = originalMessage.Id
            };

            toUserEntity.Reminders.Add(remindEntity);

            await GrillBotRepository.CommitAsync();

            Queue.Add(new ReminderBackgroundTask(remindEntity));
        }
예제 #26
0
        public async Task LogUserJoinAsync(SocketGuildUser user)
        {
            if (user == null || !user.IsUser())
            {
                return;
            }

            var userEntity = await GrillBotRepository.UsersRepository.GetOrCreateUserAsync(user.Guild.Id, user.Id, UsersIncludes.None);

            await GrillBotRepository.CommitAsync();

            var entity = new AuditLogItem()
            {
                Type             = AuditLogType.UserJoined,
                CreatedAt        = DateTime.Now,
                GuildIdSnowflake = user.Guild.Id,
                UserId           = userEntity.ID
            };

            entity.SetData(UserJoinedAuditData.Create(user.Guild));
            await GrillBotRepository.AddAsync(entity);

            await GrillBotRepository.CommitAsync();
        }
예제 #27
0
        private async Task <string> SetUnverifyAsync(SocketUser socketUser, string time, string data, SocketGuild guild, SocketUser fromUser, bool selfUnverify,
                                                     List <string> toKeep, SocketRole mutedRole)
        {
            var user = await guild.GetUserFromGuildAsync(socketUser.Id);

            await Checker.ValidateAsync(user, guild, selfUnverify);

            var profile = await UnverifyProfileGenerator.CreateProfileAsync(user, guild, time, data, selfUnverify, toKeep, mutedRole);

            UnverifyLog unverifyLogEntity;

            if (selfUnverify)
            {
                unverifyLogEntity = await UnverifyLogger.LogSelfUnverifyAsync(profile, guild);
            }
            else
            {
                unverifyLogEntity = await UnverifyLogger.LogUnverifyAsync(profile, guild, fromUser);
            }

            try
            {
                if (mutedRole != null)
                {
                    await user.SetRoleAsync(mutedRole);
                }

                await user.RemoveRolesAsync(profile.RolesToRemove);

                foreach (var channelOverride in profile.ChannelsToRemove)
                {
                    var channel = guild.GetChannel(channelOverride.ChannelID);
                    await channel?.AddPermissionOverwriteAsync(user, new OverwritePermissions(viewChannel : PermValue.Deny));
                }

                var userEntity = await GrillBotRepository.UsersRepository.GetOrCreateUserAsync(guild.Id, user.Id, UsersIncludes.Unverify);

                userEntity.Unverify = new Database.Entity.Unverify.Unverify()
                {
                    DeserializedChannels = profile.ChannelsToRemove.ConvertAll(o => new ChannelOverride(o.ChannelID, o.Perms)),
                    DeserializedRoles    = profile.RolesToRemove.ConvertAll(o => o.Id),
                    EndDateTime          = profile.EndDateTime,
                    Reason          = profile.Reason,
                    StartDateTime   = profile.StartDateTime,
                    SetLogOperation = unverifyLogEntity
                };

                await GrillBotRepository.CommitAsync();

                Queue.Add(new UnverifyBackgroundTask(guild.Id, user.Id, profile.EndDateTime));

                var pmMessage = MessageGenerator.CreateUnverifyPMMessage(profile, guild);
                await user.SendPrivateMessageAsync(pmMessage);

                return(MessageGenerator.CreateUnverifyMessageToChannel(profile));
            }
            catch (Exception ex)
            {
                if (mutedRole != null)
                {
                    await user.RemoveRoleAsync(mutedRole);
                }

                await user.AddRolesAsync(profile.RolesToRemove);

                foreach (var channelOverride in profile.ChannelsToRemove)
                {
                    var channel = guild.GetChannel(channelOverride.ChannelID);

                    if (channel != null)
                    {
                        await channel.AddPermissionOverwriteAsync(user, channelOverride.Perms);
                    }
                }

                var errorMessage = new LogMessage(LogSeverity.Warning, nameof(UnverifyService), "An error occured when unverify removing access.", ex);
                await Logger.OnLogAsync(errorMessage);

                return(MessageGenerator.CreateUnverifyFailedToChannel(user));
            }
        }
예제 #28
0
        public async Task TriggerBackgroundTaskAsync(object data)
        {
            if (data is not DownloadAuditLogBackgroundTask task)
            {
                return;
            }

            var guild = Client.GetGuild(task.GuildId);

            if (guild == null)
            {
                return;
            }

            if (!AuditServiceHelper.IsTypeDefined(task.ActionType))
            {
                return;
            }

            var logs = await guild.GetAuditLogDataAsync(100, task.ActionType);

            if (logs.Count == 0)
            {
                return;
            }

            var auditLogType = AuditServiceHelper.AuditLogTypeMap[task.ActionType];
            var logIds       = (await GrillBotRepository.AuditLogs.GetLastAuditLogIdsQuery(guild.Id, auditLogType).ToListAsync())
                               .ConvertAll(o => Convert.ToUInt64(o));

            foreach (var log in logs)
            {
                if (logIds.Contains(log.Id))
                {
                    continue;
                }

                var userId = await GetOrCreateUserId(guild, log.User);

                var item = new AuditLogItem()
                {
                    CreatedAt             = log.CreatedAt.LocalDateTime,
                    DcAuditLogIdSnowflake = log.Id,
                    UserId           = userId,
                    GuildIdSnowflake = guild.Id,
                    Type             = auditLogType
                };

                var logMappingMethod = AuditServiceHelper.AuditLogDataMap[task.ActionType];

                if (logMappingMethod != null)
                {
                    var mappedItem = logMappingMethod(log.Data);

                    if (mappedItem != null)
                    {
                        item.SetData(mappedItem);
                    }
                }

                await GrillBotRepository.AddAsync(item);
            }

            await GrillBotRepository.CommitAsync();
        }
예제 #29
0
        public async Task <string> RemoveUnverifyAsync(SocketGuild guild, SocketGuildUser user, SocketUser fromUser, bool isAuto = false)
        {
            try
            {
                BotState.CurrentReturningUnverifyFor.Add(user);

                var userEntity = await GrillBotRepository.UsersRepository.GetUserAsync(guild.Id, user.Id, UsersIncludes.Unverify);

                if (userEntity?.Unverify == null)
                {
                    return(MessageGenerator.CreateRemoveAccessUnverifyNotFound(user));
                }

                var unverifyConfig = (await GrillBotRepository.ConfigRepository.FindConfigAsync(guild.Id, "unverify", null, false))?.GetData <UnverifyConfig>();
                var mutedRole      = unverifyConfig == null ? null : guild.GetRole(unverifyConfig.MutedRoleID);

                var rolesToReturn = userEntity.Unverify.DeserializedRoles.Where(o => !user.Roles.Any(x => x.Id == o))
                                    .Select(o => guild.GetRole(o)).Where(role => role != null).ToList();

                var channelsToReturn = userEntity.Unverify.DeserializedChannels
                                       .Select(o => new ChannelOverwrite(guild.GetChannel(o.ChannelIdSnowflake), o.GetPermissions()))
                                       .Where(o => o.Channel != null).ToList();

                if (isAuto)
                {
                    await UnverifyLogger.LogAutoRemoveAsync(rolesToReturn, channelsToReturn, user, guild);
                }
                else
                {
                    await UnverifyLogger.LogRemoveAsync(rolesToReturn, channelsToReturn, guild, user, fromUser);
                }

                foreach (var channel in channelsToReturn)
                {
                    if (channel.Channel is SocketGuildChannel socketGuildChannel)
                    {
                        try
                        {
                            await socketGuildChannel.AddPermissionOverwriteAsync(user, channel.Perms);
                        }
                        catch (HttpException ex)
                        {
                            var message = new LogMessage(LogSeverity.Error, nameof(UnverifyService), $"An error occured when unverify returning access to channel {channel.Channel.Name} for user {user.GetFullName()}", ex);
                            await Logger.OnLogAsync(message);
                        }
                    }
                }

                await user.AddRolesAsync(rolesToReturn);

                if (mutedRole != null)
                {
                    await user.RemoveRoleAsync(mutedRole);
                }

                userEntity.Unverify = null;
                await GrillBotRepository.CommitAsync();

                Queue.TryRemove <UnverifyBackgroundTask>(o => o.GuildId == guild.Id && o.UserId == user.Id);

                if (!isAuto)
                {
                    var message = MessageGenerator.CreateRemoveAccessManuallyPMMessage(guild);
                    await user.SendPrivateMessageAsync(message);
                }

                return(MessageGenerator.CreateRemoveAccessManuallyToChannel(user));
            }
            catch (Exception ex)
            {
                if (!isAuto)
                {
                    throw;
                }

                var message = new LogMessage(LogSeverity.Error, nameof(UnverifyService), "An error occured when unverify returning access.", ex);
                await Logger.OnLogAsync(message);

                return(MessageGenerator.CreateRemoveAccessManuallyFailed(user, ex));
            }
            finally
            {
                BotState.CurrentReturningUnverifyFor.RemoveAll(o => o.Id == user.Id);
            }
        }