Ejemplo n.º 1
0
        public async Task <IUserMessage> SendPaginatedMessageAsync(QuiccbanContext context,
                                                                   PaginatedMessage pager,
                                                                   ICriterion <SocketReaction> criterion = null)
        {
            var callback = new PaginatedMessageCallback(this, context, pager, criterion);
            await callback.DisplayAsync().ConfigureAwait(false);

            return(callback.Message);
        }
Ejemplo n.º 2
0
 public PaginatedMessageCallback(InteractiveService interactive,
                                 QuiccbanContext sourceContext,
                                 PaginatedMessage pager,
                                 ICriterion <SocketReaction> criterion = null)
 {
     Interactive = interactive;
     Context     = sourceContext;
     _criterion  = criterion ?? new EmptyCriterion <SocketReaction>();
     _pager      = pager;
     pages       = _pager.Pages.Count();
 }
Ejemplo n.º 3
0
        public async Task <bool> JudgeAsync(QuiccbanContext sourceContext, T parameter)
        {
            foreach (var criterion in _critiera)
            {
                var result = await criterion.JudgeAsync(sourceContext, parameter).ConfigureAwait(false);

                if (!result)
                {
                    return(false);
                }
            }
            return(true);
        }
Ejemplo n.º 4
0
        public async Task <IUserMessage> ReplyAndDeleteAsync(QuiccbanContext context,
                                                             string content, bool isTTS = false,
                                                             Embed embed            = null,
                                                             TimeSpan?timeout       = null,
                                                             RequestOptions options = null)
        {
            timeout = timeout ?? _defaultTimeout;
            var message = await context.Channel.SendMessageAsync(content, isTTS, embed, options).ConfigureAwait(false);

            _ = Task.Delay(timeout.Value)
                .ContinueWith(_ => message.DeleteAsync().ConfigureAwait(false))
                .ConfigureAwait(false);
            return(message);
        }
Ejemplo n.º 5
0
        public Task <SocketMessage> NextMessageAsync(QuiccbanContext context,
                                                     bool fromSourceUser     = true,
                                                     bool inSourceChannel    = true,
                                                     TimeSpan?timeout        = null,
                                                     CancellationToken token = default(CancellationToken))
        {
            var criterion = new Criteria <SocketMessage>();

            if (fromSourceUser)
            {
                criterion.AddCriterion(new EnsureSourceUserCriterion());
            }
            if (inSourceChannel)
            {
                criterion.AddCriterion(new EnsureSourceChannelCriterion());
            }
            return(NextMessageAsync(context, criterion, timeout, token));
        }
Ejemplo n.º 6
0
        public async Task <SocketMessage> NextMessageAsync(QuiccbanContext context,
                                                           ICriterion <SocketMessage> criterion,
                                                           TimeSpan?timeout        = null,
                                                           CancellationToken token = default(CancellationToken))
        {
            timeout = timeout ?? _defaultTimeout;

            var eventTrigger  = new TaskCompletionSource <SocketMessage>();
            var cancelTrigger = new TaskCompletionSource <bool>();

            token.Register(() => cancelTrigger.SetResult(true));

            async Task Handler(SocketMessage message)
            {
                var result = await criterion.JudgeAsync(context, message).ConfigureAwait(false);

                if (result)
                {
                    eventTrigger.SetResult(message);
                }
            }

            context.Client.MessageReceived += Handler;

            var trigger = eventTrigger.Task;
            var cancel  = cancelTrigger.Task;
            var delay   = Task.Delay(timeout.Value);
            var task    = await Task.WhenAny(trigger, delay, cancel).ConfigureAwait(false);

            context.Client.MessageReceived -= Handler;

            if (task == trigger)
            {
                return(await trigger.ConfigureAwait(false));
            }
            else
            {
                return(null);
            }
        }
        public Task <bool> JudgeAsync(QuiccbanContext sourceContext, SocketReaction parameter)
        {
            bool ok = parameter.UserId == sourceContext.User.Id;

            return(Task.FromResult(ok));
        }
Ejemplo n.º 8
0
        public Task <bool> JudgeAsync(QuiccbanContext sourceContext, IMessage parameter)
        {
            var ok = sourceContext.Channel.Id == parameter.Channel.Id;

            return(Task.FromResult(ok));
        }
Ejemplo n.º 9
0
        private async Task StartAsync()
        {
            async Task LoginRoutine()
            {
                await discordClient.LoginAsync(TokenType.Bot, _config.DiscordToken);

                await discordClient.StartAsync();

                await Task.Delay(-1);
            }

            discordClient.Ready += async() =>
            {
                if (!IsReady)
                {
                    ApplicationInfo = await discordClient.GetApplicationInfoAsync();

                    _logger.LogInformation($"Logged into Discord as \"{discordClient.CurrentUser}\" in {discordClient.Guilds.Count} guild{(discordClient.Guilds.Count > 1 ? "s" : "")}.");

                    LoadCommands();

                    var guildStorage = _serviceProvider.GetService <GuildStorage>();

                    var dbGuilds = await guildStorage.GetAllGuildsAsync();

                    foreach (var guild in dbGuilds)
                    {
                        var unexpiredCases = guild.Cases.Where(x => (x.GetEndingTime() > DateTimeOffset.UtcNow && x.ActionType != ActionType.Warn) || (x.ActionType == ActionType.Warn && x.GetWarnEndingTime() > DateTimeOffset.UtcNow));

                        int failedCaseAdds = 0;
                        foreach (var guildCase in unexpiredCases)
                        {
                            if (!_caseHandlingService.TryAdd(guildCase))
                            {
                                failedCaseAdds++;
                            }
                        }

                        if (failedCaseAdds > 0)
                        {
                            _logger.LogWarning($"Failed to add {failedCaseAdds} cases to in-memory cache.");
                        }

                        //resolve all cases that had expired
                        var unresolvedExpiredCases = guild.Cases.Where(x => !x.Resolved && ((x.ActionType != ActionType.Warn && x.GetEndingTime() <= DateTimeOffset.UtcNow) || (x.GetWarnEndingTime() <= DateTimeOffset.UtcNow && x.ActionType == ActionType.Warn)));

                        foreach (var guildCase in unresolvedExpiredCases)
                        {
                            await _caseHandlingService.ResolveAsync(guildCase, null, null, false, false);
                        }
                    }

                    IsReady = true;
                }
            };

            discordClient.MessageReceived += async(m) =>
            {
                if (m.Channel is IDMChannel)
                {
                    return;
                }
                if (!(m is SocketUserMessage msg))
                {
                    return;
                }

                if (CommandUtilities.HasAnyPrefix(msg.Content, _prefixes, StringComparison.OrdinalIgnoreCase, out string pfx, out string output))
                {
                    var context = new QuiccbanContext(discordClient, msg, _serviceProvider);
                    var result  = await _commands.ExecuteAsync(output, context, _serviceProvider);

                    if (result is QuiccbanSuccessResult success && !string.IsNullOrWhiteSpace(success.ReplyValue))
                    {
                        await context.Channel.SendMessageAsync(success.ReplyValue);
                    }

                    if (result is QuiccbanFailResult inCommandFail)
                    {
                        await context.Channel.SendMessageAsync(inCommandFail.Reason);
                    }

                    if (result is ChecksFailedResult checkFail)
                    {
                        await context.Channel.SendMessageAsync(checkFail.FailedChecks.FirstOrDefault().Error);
                    }

                    if (result is ParameterChecksFailedResult paramCheckFail)
                    {
                        await context.Channel.SendMessageAsync(paramCheckFail.FailedChecks.FirstOrDefault().Error);
                    }
                }
            };

            discordClient.UserBanned += async(u, g) =>
            {
                await Task.Delay(500);

                var auditLogs = await g.GetAuditLogsAsync(20).FlattenAsync();

                var auditLog = auditLogs.FirstOrDefault(a => a.Data is BanAuditLogData ban && ban.Target.Id == u.Id);
                if (auditLog == null)
                {
                    return;
                }

                if (auditLog.User.Id == discordClient.CurrentUser.Id)
                {
                    return;
                }

                var data      = auditLog.Data as BanAuditLogData;
                var dbService = _serviceProvider.GetService <DatabaseService>();

                await dbService.CreateNewCaseAsync(g, auditLog.Reason, ActionType.Ban, 0, auditLog.User, data.Target);
            };

            discordClient.UserUnbanned += async(u, g) =>
            {
                await Task.Delay(500);

                var auditLogs = await g.GetAuditLogsAsync(20).FlattenAsync();

                var auditLog = auditLogs.FirstOrDefault(a => a.Data is UnbanAuditLogData unban && unban.Target.Id == u.Id);
                if (auditLog == null)
                {
                    return;
                }

                if (auditLog.User.Id == discordClient.CurrentUser.Id)
                {
                    return;
                }

                var data        = auditLog.Data as UnbanAuditLogData;
                var dbService   = _serviceProvider.GetService <DatabaseService>();
                var caseService = _serviceProvider.GetService <CaseHandlingService>();

                var tempcase = caseService.GetCases().FirstOrDefault(x => x.GuildId == g.Id && x.TargetId == data.Target.Id && x.ActionType == ActionType.TempBan && !x.Resolved);
                if (tempcase != null)
                {
                    await _caseHandlingService.ResolveAsync(tempcase, auditLog.User, auditLog.Reason, true, false);
                }
                else
                {
                    await dbService.CreateNewCaseAsync(g, auditLog.Reason, ActionType.Ban, 0, auditLog.User, data.Target);
                }
            };

            discordClient.UserLeft += async(u) =>
            {
                await Task.Delay(500);

                var auditLogs = await u.Guild.GetAuditLogsAsync(20).FlattenAsync();

                var auditLog = auditLogs.FirstOrDefault(a => a.Data is KickAuditLogData kick && kick.Target.Id == u.Id);
                if (auditLog == null)
                {
                    return;
                }

                if (auditLog.User.Id == discordClient.CurrentUser.Id)
                {
                    return;
                }

                var data      = auditLog.Data as KickAuditLogData;
                var dbService = _serviceProvider.GetService <DatabaseService>();

                await dbService.CreateNewCaseAsync(u.Guild, auditLog.Reason, ActionType.Kick, 0, auditLog.User, data.Target);
            };

            discordClient.GuildMemberUpdated += async(u_before, u_after) =>
            {
                await Task.Delay(500);

                var auditLogs = await u_after.Guild.GetAuditLogsAsync(20).FlattenAsync();

                var auditLog = auditLogs.FirstOrDefault(a => a.Data is MemberRoleAuditLogData role && role.Target.Id == u_after.Id);
                if (auditLog == null)
                {
                    return;
                }

                if (auditLog.User.Id == discordClient.CurrentUser.Id)
                {
                    return;
                }

                var data = auditLog.Data as MemberRoleAuditLogData;

                var dbService   = _serviceProvider.GetService <DatabaseService>();
                var caseService = _serviceProvider.GetService <CaseHandlingService>();
                var dbGuild     = await dbService.GetOrCreateGuildAsync(u_after.Guild);

                if (data.Roles.Any(x => x.RoleId == dbGuild.MuteRoleId && x.Added))
                {
                    await dbService.CreateNewCaseAsync(u_after.Guild, auditLog.Reason, ActionType.Mute, 0, auditLog.User, data.Target);
                }
                else if (data.Roles.Any(x => x.RoleId == dbGuild.MuteRoleId && !x.Added))
                {
                    var tempcase = caseService.GetCases().FirstOrDefault(x => x.TargetId == data.Target.Id && x.ActionType == ActionType.TempMute && !x.Resolved);
                    if (tempcase != null)
                    {
                        await _caseHandlingService.ResolveAsync(tempcase, auditLog.User, auditLog.Reason, true, false);
                    }
                    else
                    {
                        await dbService.CreateNewCaseAsync(u_after.Guild, auditLog.Reason, ActionType.Unmute, 0, auditLog.User, data.Target);
                    }
                }
            };



            _logger.LogInformation("Attempting to log into Discord...");

            try
            {
                await LoginRoutine();
            }
            catch
            {
                _logger.LogError("Failed to log into Discord. Attempting reconnect in 10 seconds.");
                await Task.Delay(10000);

                try
                {
                    await LoginRoutine();
                }
                catch
                {
                    _logger.LogError("Reconnection failed. Exiting.");
                    Environment.Exit(0);
                }
            }
        }
Ejemplo n.º 10
0
 public Task <bool> JudgeAsync(QuiccbanContext sourceContext, T parameter)
 => Task.FromResult(true);
Ejemplo n.º 11
0
        public Task <bool> JudgeAsync(QuiccbanContext sourceContext, SocketMessage parameter)
        {
            bool ok = int.TryParse(parameter.Content, out _);

            return(Task.FromResult(ok));
        }