Пример #1
0
 public General(IServiceProvider serviceProvider) : base(serviceProvider)
 {
     _serviceProvider   = serviceProvider;
     _pollRepository    = _serviceProvider.GetRequiredService <PollRepository>();
     _commandService    = _serviceProvider.GetRequiredService <CommandService>();
     _moderationService = _serviceProvider.GetRequiredService <ModerationService>();
 }
Пример #2
0
 public Task Note(
     [Summary("The user to which the note is being applied.")]
     IGuildUser subject,
     [Summary("The reason for the note.")]
     [Remainder]
     string reason)
 => ModerationService.CreateInfractionAsync(InfractionType.Notice, subject.Id, reason, null);
Пример #3
0
        public void Aprove_ShouldCallSubmissionRepository_Update(int id)
        {
            //Arrange
            var mockSubmissionRepository = new Mock <IRepository <Submission> >();

            var fakeSubmission = new Submission();

            mockSubmissionRepository.Setup(x => x.GetById(id)).Returns(fakeSubmission);

            var mockQuestionService        = new Mock <IQuestionUtility>();
            var mockDateTimeProvider       = new Mock <IDateTimeProvider>();
            var mockAuthenticationProvider = new Mock <IAuthenticationProvider>();
            var mockUnitOfWork             = new Mock <IUnitOfWork>();

            var controller = new ModerationService(mockSubmissionRepository.Object,
                                                   mockQuestionService.Object,
                                                   mockDateTimeProvider.Object,
                                                   mockAuthenticationProvider.Object,
                                                   mockUnitOfWork.Object
                                                   );

            //Act
            controller.Approve(id);

            //Assert
            mockSubmissionRepository.Verify(x => x.Update(fakeSubmission), Times.Once);
        }
Пример #4
0
 public Crime(UserRepository userRepo, GangRepository gangRepo, ModerationService moderationService, Item[] _items)
 {
     _userRepo          = userRepo;
     _gangRepo          = gangRepo;
     _moderationService = moderationService;
     _items             = items;
 }
Пример #5
0
 public async Task CleanAsync(
     [Summary("The number of messages to delete.")]
     int count)
 => await ModerationService.DeleteMessagesAsync(
     Context.Channel as ITextChannel, count, true,
     () => Context.GetUserConfirmationAsync(
         $"You are attempting to delete the past {count} messages in #{Context.Channel.Name}.{Environment.NewLine}"));
Пример #6
0
        public async Task <ActionResult> SoftBanAsync(
            [CheckHierarchy, EnsureNotSelf, Description("The member to softban.")]
            SocketGuildUser user, [Description("The amount of days of messages to delete. Defaults to 7.")]
            int daysToDelete = 0,
            [Remainder, Description("The reason for the softban.")]
            string reason = "Softbanned by a Moderator.")
        {
            var e = Context.CreateEmbedBuilder(
                $"You've been softbanned from **{Context.Guild.Name}** for **{reason}**.")
                    .ApplyConfig(Context.GuildData);

            if (!await user.TrySendMessageAsync(embed: e.Build()))
            {
                Logger.Warn(LogSource.Module, $"encountered a 403 when trying to message {user}!");
            }

            try
            {
                await user.BanAsync(daysToDelete == 0? 7 : daysToDelete, reason);

                await Context.Guild.RemoveBanAsync(user);

                return(Ok($"Successfully softbanned **{user.Username}#{user.Discriminator}**.", _ =>
                          ModerationService.OnModActionCompleteAsync(ModActionEventArgs.New
                                                                     .WithDefaultsFromContext(Context)
                                                                     .WithTarget(user)
                                                                     .WithReason(reason))
                          ));
            }
            catch
            {
                return(BadRequest(
                           "An error occurred softbanning that user. Do I have permission; or are they higher than me in the role list?"));
            }
        }
Пример #7
0
 public Task Warn(
     [Summary("The user to which the warning is being issued.")]
     IGuildUser subject,
     [Summary("The reason for the warning.")]
     [Remainder]
     string reason)
 => ModerationService.CreateInfractionAsync(InfractionType.Warning, subject.Id, reason, null);
Пример #8
0
        public async Task <ActionResult> KickAsync([CheckHierarchy, EnsureNotSelf, Description("The member to kick.")]
                                                   SocketGuildUser user,
                                                   [Remainder, Description("The reason for the kick.")]
                                                   string reason = "Kicked by a Moderator.")
        {
            var e = Context.CreateEmbedBuilder($"You've been kicked from **{Context.Guild.Name}** for **{reason}**.")
                    .ApplyConfig(Context.GuildData);

            if (!await user.TrySendMessageAsync(embed: e.Build()))
            {
                Logger.Warn(LogSource.Module, $"encountered a 403 when trying to message {user}!");
            }

            try
            {
                await user.KickAsync(reason);

                return(Ok($"Successfully kicked **{user.Username}#{user.Discriminator}** from this guild.", _ =>
                          ModerationService.OnModActionCompleteAsync(ModActionEventArgs.New
                                                                     .WithDefaultsFromContext(Context)
                                                                     .WithActionType(ModActionType.Kick)
                                                                     .WithTarget(user)
                                                                     .WithReason(reason))
                          ));
            }
            catch
            {
                return(BadRequest(
                           "An error occurred kicking that user. Do I have permission; or are they higher than me in the role list?"));
            }
        }
Пример #9
0
        public async Task <ActionResult> ClearWarnsAsync(
            [Remainder, EnsureNotSelf, Description("The member who you want to clear warns for.")]
            SocketGuildUser member)
        {
            var warnCount = Context.GuildData.Extras.Warns.RemoveWhere(x => x.User == member.Id);

            Db.Save(Context.GuildData);

            var e = Context
                    .CreateEmbedBuilder(
                $"Your {"warn".ToQuantity(warnCount)} in {Format.Bold(Context.Guild.Name)} have been cleared. Hooray!")
                    .ApplyConfig(Context.GuildData);

            if (!await member.TrySendMessageAsync(embed: e.Build()))
            {
                Logger.Warn(LogSource.Volte, $"encountered a 403 when trying to message {member}!");
            }

            return(Ok($"Cleared **{warnCount}** warnings for **{member}**.", _ =>
                      ModerationService.OnModActionCompleteAsync(ModActionEventArgs.New
                                                                 .WithDefaultsFromContext(Context)
                                                                 .WithActionType(ModActionType.ClearWarns)
                                                                 .WithTarget(member))
                      ));
        }
Пример #10
0
        private async Task ConfirmAndReplyWithCountsAsync(ulong userId)
        {
            await Context.AddConfirmation();

            // If the channel is public, do not list the infraction embed that occurs after a user has reached 3 infractions
            if ((Context.Channel as IGuildChannel)?.IsPublic() is true)
            {
                return;
            }

            var counts = await ModerationService.GetInfractionCountsForUserAsync(userId);

            //TODO: Make this configurable
            if (counts.Values.Any(count => count >= 3))
            {
                // https://modix.gg/infractions?subject=12345
                var url = new UriBuilder(Config.WebsiteBaseUrl)
                {
                    Path  = "/infractions",
                    Query = $"subject={userId}"
                }.RemoveDefaultPort().ToString();

                await ReplyAsync(embed : new EmbedBuilder()
                                 .WithTitle("Infraction Count Notice")
                                 .WithColor(Color.Orange)
                                 .WithDescription(FormatUtilities.FormatInfractionCounts(counts))
                                 .WithUrl(url)
                                 .Build());
            }
        }
        private static void ImageContent(String token, String endpoint)
        {
            // The obs url of file
            String dataUrl = "";
            // The image content confidence interval,"politics" default 0.48f,"terrorism":0
            float threshold = 0.6f;

            JArray categories = new JArray();

            categories.Add("politics");
            categories.Add("terrorism");
            categories.Add("p**n");

            // post data by native file
            String data   = utils.ConvertFileToBase64("../../data/moderation-terrorism.jpg");
            String reslut = ModerationService.ImageContentToken(token, data, dataUrl, threshold, categories, endpoint);

            Console.WriteLine(reslut);

            // The OBS link must match the region, and the OBS resources of different regions are not shared
            dataUrl = "https://sdk-obs-source-save.obs.cn-north-4.myhuaweicloud.com/terrorism.jpg";

            // post data by obs url
            reslut = ModerationService.ImageContentToken(token, "", dataUrl, threshold, categories, endpoint);
            Console.WriteLine(reslut);
            Console.ReadKey();
        }
Пример #12
0
        public async Task <ActionResult> PurgeAsync([Description("The amount of messages to purge.")]
                                                    int count, [Description("If provided, will only delete messages by this user within `count` messages.")]
                                                    RestUser targetAuthor = null)
        {
            //+1 to include the command invocation message, and actually delete the last x messages instead of x - 1.
            //lets you theoretically use 0 to delete only the invocation message, for testing or something.
            var messages = (await Context.Channel.GetMessagesAsync(count + 1).FlattenAsync()).ToList();

            try
            {
                await Context.Channel.DeleteMessagesAsync(
                    messages.Where(x => targetAuthor is null || x.Author.Id == targetAuthor.Id),
                    DiscordHelper.CreateRequestOptions(opts =>
                                                       opts.AuditLogReason = $"Messages purged by {Context.User}."));
            }
            catch (ArgumentOutOfRangeException)
            {
                return(BadRequest(
                           $"Messages bulk deleted must be younger than 14 days. {Format.Code("This is a Discord restriction, not a Volte one.")}"));
            }

            //-1 to show that the correct amount of messages were deleted.
            return(None(async() =>
            {
                await Interactive.ReplyAndDeleteAsync(Context, string.Empty,
                                                      embed: Context.CreateEmbed($"Successfully deleted {Format.Bold("message".ToQuantity(messages.Count - 1))}."),
                                                      timeout: 3.Seconds());
                await ModerationService.OnModActionCompleteAsync(ModActionEventArgs.New
                                                                 .WithDefaultsFromContext(Context)
                                                                 .WithActionType(ModActionType.Purge)
                                                                 .WithCount(count));
            }, false));
        }
Пример #13
0
        public async Task <ActionResult> DeleteAsync(
            [Description("The ID of the message to delete. Must be in the current channel.")]
            ulong messageId)
        {
            var target = await Context.Channel.GetMessageAsync(messageId);

            if (target is null)
            {
                return(BadRequest("That message doesn't exist in this channel."));
            }

            await target.TryDeleteAsync($"Message deleted by Moderator {Context.User}.");

            return(Ok($"{DiscordHelper.BallotBoxWithCheck} Deleted that message.", async m =>
            {
                //await Interactive.ReplyAndDeleteAsync(Context,)
                _ = Executor.ExecuteAfterDelayAsync(3.Seconds(), async() =>
                {
                    await Context.Message.TryDeleteAsync();
                    await m.DeleteAsync();
                });

                await ModerationService.OnModActionCompleteAsync(ModActionEventArgs.New
                                                                 .WithDefaultsFromContext(Context)
                                                                 .WithActionType(ModActionType.Delete)
                                                                 .WithTarget(messageId)
                                                                 );
            }));
        }
Пример #14
0
 public Task Mute(
     [Summary("The user to be muted.")]
     IGuildUser subject,
     [Summary("The reason for the mute.")]
     [Remainder]
     string reason)
 => ModerationService.CreateInfractionAsync(InfractionType.Mute, subject.Id, reason, null);
Пример #15
0
        public async Task <ActionResult> BanAsync([CheckHierarchy, EnsureNotSelf, Description("The member to ban.")]
                                                  SocketGuildUser member,
                                                  [Remainder, Description("The reason for the ban.")]
                                                  string reason = "Banned by a Moderator.")
        {
            var e = Context
                    .CreateEmbedBuilder(
                $"You've been banned from {Format.Bold(Context.Guild.Name)} for {Format.Bold(reason)}.")
                    .ApplyConfig(Context.GuildData);

            if (!await member.TrySendMessageAsync(embed: e.Build()))
            {
                Logger.Warn(LogSource.Module, $"encountered a 403 when trying to message {member}!");
            }

            try
            {
                await member.BanAsync(7, reason);

                return(Ok($"Successfully banned **{member}** from this guild.", _ =>
                          ModerationService.OnModActionCompleteAsync(ModActionEventArgs.New
                                                                     .WithDefaultsFromContext(Context)
                                                                     .WithActionType(ModActionType.Ban)
                                                                     .WithTarget(member)
                                                                     .WithReason(reason))
                          ));
            }
            catch
            {
                return(BadRequest(
                           "An error occurred banning that member. Do I have permission; or are they higher than me in the role list?"));
            }
        }
Пример #16
0
        public async Task ForceUnban(
            [Summary("The id of the user to be un-banned.")]
            ulong subjectId)
        {
            var result = await ModerationService.RescindInfractionAsync(InfractionType.Ban, subjectId);

            await AddConfirmationOrHandleAsync(result);
        }
Пример #17
0
        public async Task UnBanAsync(
            [Summary("The user to be un-banned.")]
            DiscordUserOrMessageAuthorEntity subject)
        {
            await ModerationService.RescindInfractionAsync(InfractionType.Ban, subject.UserId);

            await ConfirmAndReplyWithCountsAsync(subject.UserId);
        }
Пример #18
0
        public async Task UnBanAsync(
            [Summary("The user to be un-banned.")]
            DiscordUserEntity subject)
        {
            await ModerationService.RescindInfractionAsync(InfractionType.Ban, subject.Id);

            await Context.AddConfirmation();
        }
Пример #19
0
        public async Task UnMuteAsync(
            [Summary("The user to be un-muted.")]
            DiscordUserEntity subject)
        {
            await ModerationService.RescindInfractionAsync(InfractionType.Mute, subject.Id);

            await ConfirmAndReplyWithCountsAsync(subject.Id);
        }
Пример #20
0
        public async Task ToggleToxicityAsync()
        {
            var config = ModerationService.GetModerationConfig(Context.Guild.Id);

            config.UsePerspective = !config.UsePerspective;
            ModerationService.SaveModerationConfig(config);
            await ReplyAsync($"Toxic message checking: {config.UsePerspective}");
        }
Пример #21
0
        public Task ToxicityToken(string token = null)
        {
            var setup = ModerationService.GetSetup();

            setup.PerspectiveToken = token;
            ModerationService.SetPerspectiveSetup(setup);
            return(Task.CompletedTask);
        }
Пример #22
0
        public async Task BlacklistUsernameRemove([Remainder] string name)
        {
            var config = ModerationService.GetModerationConfig(Context.Guild.Id);

            config.BlacklistedUsernames = config.BlacklistedUsernames.Where(x => x.Content.Equals(name, StringComparison.InvariantCultureIgnoreCase)).ToList();
            ModerationService.SaveModerationConfig(config);
            await ReplyAsync($"Removed.");
        }
Пример #23
0
        public async Task ToggleBlacklistAsync()
        {
            var config = ModerationService.GetModerationConfig(Context.Guild.Id);

            config.UseBlacklist = !config.UseBlacklist;
            ModerationService.SaveModerationConfig(config);
            await ReplyAsync($"Using Blacklist: {config.UseBlacklist}");
        }
Пример #24
0
        public async Task ToggleIpsAsync()
        {
            var config = ModerationService.GetModerationConfig(Context.Guild.Id);

            config.BlockIps = !config.BlockIps;
            ModerationService.SaveModerationConfig(config);
            await ReplyAsync($"IP Address Blocking: {config.BlockIps}");
        }
Пример #25
0
        public async Task UnMute(
            [Summary("The user to be un-muted.")]
            IGuildUser subject)
        {
            var result = await ModerationService.RescindInfractionAsync(InfractionType.Mute, subject.Id);

            await AddConfirmationOrHandleAsync(result);
        }
Пример #26
0
        public async Task ForceUnban(
            [Summary("The id of the user to be un-banned.")]
            ulong subjectId)
        {
            await ModerationService.RescindInfractionAsync(InfractionType.Ban, subjectId);

            await Context.AddConfirmation();
        }
Пример #27
0
        public async Task DeleteAsync(
            [Summary("The ID value of the infraction to be deleted.")]
            long infractionId)
        {
            await ModerationService.DeleteInfractionAsync(infractionId);

            await Context.AddConfirmation();
        }
Пример #28
0
 public Moderator(IServiceProvider serviceProvider) : base(serviceProvider)
 {
     _serviceProvider   = serviceProvider;
     _userRepository    = _serviceProvider.GetRequiredService <UserRepository>();
     _pollRepository    = _serviceProvider.GetRequiredService <PollRepository>();
     _muteRepository    = _serviceProvider.GetRequiredService <MuteRepository>();
     _moderationService = _serviceProvider.GetRequiredService <ModerationService>();
 }
Пример #29
0
        public async Task SetTimeLimit(int seconds)
        {
            var config = ModerationService.GetModerationConfig(Context.Guild.Id);

            config.SpamSettings.SecondsToCheck = seconds;
            ModerationService.SaveModerationConfig(config);
            await ReplyAsync($"Max Messages per {config.SpamSettings.SecondsToCheck} Seconds Set. {config.SpamSettings.MessagesPerTime}/{config.SpamSettings.SecondsToCheck}s");
        }
Пример #30
0
        public async Task UnBan(
            [Summary("The user to be un-banned.")]
            IGuildUser subject)
        {
            await ModerationService.RescindInfractionAsync(InfractionType.Ban, subject.Id);

            await AddConfirmation();
        }