public async Task <IActionResult> PostPunishments([FromBody] Punishments punishments)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.Punishments.Add(punishments);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (PunishmentsExists(punishments.Id))
                {
                    return(new StatusCodeResult(StatusCodes.Status409Conflict));
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction("GetPunishments", new { id = punishments.Id }));
        }
예제 #2
0
            private async ValueTask <AdminCommandResult> BlockUserAsync(CachedMember target, CachedTextChannel channel,
                                                                        TimeSpan?duration, string reason)
            {
                channel ??= (CachedTextChannel)Context.Channel;

                if (channel.Overwrites.Any(x => x.TargetId == target.Id))
                {
                    return(CommandErrorLocalized("moderation_alreadyblocked", args: Markdown.Bold(target.Tag)));
                }

                var guild = await Context.Database.GetOrCreateGuildAsync(Context.Guild.Id);

                Mute mute = null;

                if (guild.Settings.HasFlag(GuildSettings.Punishments))
                {
                    var image  = new MemoryStream();
                    var format = ImageFormat.Default;
                    if (Context.Message.Attachments.FirstOrDefault() is { } attachment&&
                        attachment.FileName.HasImageExtension(out format))
                    {
                        var stream = await Http.GetStreamAsync(attachment.Url);

                        await stream.CopyToAsync(image);

                        image.Seek(0, SeekOrigin.Begin);
                    }

                    mute = new Mute(Context.Guild.Id, target.Id, Context.User.Id, reason, duration, channel.Id, image, format);
                    if (channel.Overwrites.FirstOrDefault(x => x.TargetId == target.Id) is CachedOverwrite overwrite)
                    {
                        mute.StoreOverwrite(overwrite);
                        await channel.DeleteOverwriteAsync(target.Id);
                    }
                    mute = Context.Database.Punishments.Add(mute).Entity as Mute;
                    await Context.Database.SaveChangesAsync();

                    await Punishments.LogMuteAsync(target, Context.Guild, Context.User, mute);
                }

                await channel.AddOrModifyOverwriteAsync(new LocalOverwrite(target,
                                                                           new OverwritePermissions().Deny(Permission.SendMessages).Deny(Permission.AddReactions)));

                return(duration.HasValue
                    ? CommandSuccessLocalized("moderation_block_temporary", args: new object[]
                {
                    (mute is { } ? $"`[#{mute.Id}]` " : string.Empty) + target.Format(),
예제 #3
0
        public BaseRepository(IServiceProvider serviceProvider)
        {
            Logger     = serviceProvider.GetRequiredService <ILogger <T> >();
            Database   = serviceProvider.GetRequiredService <Database>();
            DiscordAPI = serviceProvider.GetRequiredService <DiscordAPIInterface>();

            _config            = serviceProvider.GetRequiredService <InternalConfiguration>();
            _identityManager   = serviceProvider.GetRequiredService <IdentityManager>();
            _discordAnnouncer  = serviceProvider.GetRequiredService <DiscordAnnouncer>();
            _filesHandler      = serviceProvider.GetRequiredService <FilesHandler>();
            _punishmentHandler = serviceProvider.GetRequiredService <Punishments>();
            _scheduler         = serviceProvider.GetRequiredService <Scheduler>();
            _translator        = serviceProvider.GetRequiredService <Translator>();
            _discordBot        = serviceProvider.GetRequiredService <DiscordBot>();
            _client            = serviceProvider.GetRequiredService <DiscordSocketClient>();
            _eventHandler      = serviceProvider.GetRequiredService <InternalEventHandler>();
            _serviceProvider   = serviceProvider;
        }
예제 #4
0
        private async ValueTask <AdminCommandResult> BanUserAsync(IUser target, string reason, Warning source = null)
        {
            if (!(await Context.Guild.GetBanAsync(target.Id) is null))
            {
                return(CommandErrorLocalized("moderation_alreadybanned", args: Markdown.Bold(target.Tag)));
            }

            var guild = await Context.Database.GetOrCreateGuildAsync(Context.Guild.Id);

            Ban ban = null;

            if (guild.Settings.HasFlag(GuildSettings.Punishments))
            {
                var image  = new MemoryStream();
                var format = ImageFormat.Default;
                if (Context.Message.Attachments.FirstOrDefault() is { } attachment&&
                    attachment.FileName.HasImageExtension(out format))
                {
                    var stream = await Http.GetStreamAsync(attachment.Url);

                    await stream.CopyToAsync(image);

                    image.Seek(0, SeekOrigin.Begin);
                }

                ban = Context.Database.Punishments
                      .Add(new Ban(Context.Guild.Id, target.Id, Context.User.Id, reason, null, image, format)).Entity as Ban;
                await Context.Database.SaveChangesAsync();

                await Punishments.LogBanAsync(target, Context.Guild, ban);

                source?.SetSecondaryPunishment(ban);
            }

            await Context.Guild.BanMemberAsync(target.Id,
                                               FormatAuditLogReason(reason ?? Context.Localize("punishment_noreason"),
                                                                    ban?.CreatedAt ?? DateTimeOffset.UtcNow, Context.User),
                                               7);

            Punishments.BannedUserIds.Add(target.Id);
            return(CommandSuccessLocalized("moderation_ban",
                                           args: (ban is { } ? $"`[#{ban.Id}]` " : string.Empty) + target.Format()));
        public async Task <IActionResult> PutPunishments([FromRoute] string id, [FromBody] Punishments punishments)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            punishments = await _context.Punishments.SingleOrDefaultAsync(m => m.Id == id);

            if (id != punishments.Id)
            {
                return(BadRequest());
            }

            punishments.DatePay = DateTime.Now;

            _context.Entry(punishments).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PunishmentsExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
예제 #6
0
            public async ValueTask <AdminCommandResult> RevokePunishmentAsync([MustBe(Operator.GreaterThan, 0)] int id,
                                                                              [Remainder] string reason = null)
            {
                var punishment =
                    await Context.Database.Punishments.FirstOrDefaultAsync(x =>
                                                                           x.GuildId == Context.Guild.Id && x.Id == id) as RevocablePunishment;

                if (punishment is null)
                {
                    return(CommandErrorLocalized("punishment_notfound_id"));
                }

                if (punishment.RevokedAt.HasValue)
                {
                    return(CommandErrorLocalized("punishment_alreadyrevoked"));
                }


                punishment.Revoke(Context.User.Id, reason);
                Context.Database.Punishments.Update(punishment);
                await Context.Database.SaveChangesAsync();

                var key = "punishment_revoked_success";

                switch (punishment)
                {
                case Ban _:
                    try
                    {
                        await Context.Guild.UnbanMemberAsync(punishment.TargetId);
                    }
                    catch (DiscordHttpException ex) when(ex.HttpStatusCode == HttpStatusCode.Forbidden)
                    {
                        key = "punishment_revoked_nounban";
                    }
                    break;

                case Mute mute:
                    if (!(Context.Guild.GetMember(punishment.TargetId) is CachedMember target))
                    {
                        break;
                    }
                    if (mute.ChannelId.HasValue)
                    {
                        var channel = Context.Guild.GetTextChannel(mute.ChannelId.Value);
                        if (!channel.Overwrites.Any(x =>
                                                    x.TargetId == punishment.TargetId && x.Permissions.Denied.SendMessages &&
                                                    x.Permissions.Denied.AddReactions))
                        {
                            key = "punishment_revoked_nounmute";
                            break;
                        }

                        await channel.DeleteOverwriteAsync(target.Id);

                        if (mute.PreviousChannelAllowValue.HasValue)
                        {
                            await channel.AddOrModifyOverwriteAsync(new LocalOverwrite(target,
                                                                                       new OverwritePermissions(mute.PreviousChannelAllowValue.Value,
                                                                                                                mute.PreviousChannelDenyValue.Value)));
                        }
                        break;
                    }

                    var muteRole = await Context.Database.GetSpecialRoleAsync(Context.Guild.Id, RoleType.Mute);

                    if (muteRole is null)
                    {
                        break;
                    }
                    await target.RevokeRoleAsync(muteRole.Id);

                    break;

                case Warning _:
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                if (await Context.Database.GetLoggingChannelAsync(Context.Guild.Id, LogType.Revoke) is CachedTextChannel logChannel)
                {
                    var target = await Context.Client.GetOrDownloadUserAsync(punishment.TargetId);

                    var moderator = await Context.Client.GetOrDownloadUserAsync(punishment.RevokerId);

                    await Punishments.SendLoggingRevocationEmbedAsync(punishment, target, moderator, logChannel,
                                                                      Context.Language);

                    _ = Punishments.SendTargetRevocationEmbedAsync(punishment, target, Context.Language);
                }

                return(CommandSuccessLocalized(key));
            }
예제 #7
0
            public async ValueTask <AdminCommandResult> ShowPunishmentAsync([MustBe(Operator.GreaterThan, 0)] int id)
            {
                var punishment =
                    await Context.Database.Punishments.FirstOrDefaultAsync(x =>
                                                                           x.GuildId == Context.Guild.Id && x.Id == id);

                if (punishment is null)
                {
                    return(CommandErrorLocalized("punishment_notfound_id"));
                }


                var target = await Context.Client.GetOrDownloadUserAsync(punishment.TargetId);

                var moderator = await Context.Client.GetOrDownloadUserAsync(punishment.ModeratorId);

                var builder = new LocalEmbedBuilder()
                              .WithSuccessColor()
                              .WithTitle(Context.Localize($"punishment_{punishment.GetType().Name.ToLower()}") +
                                         $" - {Context.Localize("punishment_case", punishment.Id)}")
                              .AddField(Context.Localize("punishment_target_title"), target?.Format(false) ?? "???", true)
                              .AddField(Context.Localize("punishment_moderator_title"), moderator?.Format(false) ?? "???", true)
                              .AddField(Context.Localize("punishment_timestamp_title"),
                                        punishment.CreatedAt.ToString("g", Context.Language.Culture), true)
                              .AddField(Context.Localize("title_reason"),
                                        punishment.Reason ?? Context.Localize("punishment_noreason"));

                switch (punishment)
                {
                case Ban ban:
                    builder.AddField(Context.Localize("punishment_duration"),
                                     ban.Duration.HasValue
                                ? ban.Duration.Value.HumanizeFormatted(Localization, Context.Language, TimeUnit.Second)
                                : Context.Localize("punishment_permanent"));
                    break;

                case Mute mute:
                    if (mute.ChannelId.HasValue)
                    {
                        builder.AddField(Context.Localize("punishment_mute_channel"),
                                         Context.Guild.GetTextChannel(mute.ChannelId.Value)?.Mention ?? "???");
                    }
                    builder.AddField(Context.Localize("punishment_duration"),
                                     mute.Duration.HasValue
                                ? mute.Duration.Value.HumanizeFormatted(Localization, Context.Language, TimeUnit.Second)
                                : Context.Localize("punishment_permanent"));
                    break;

                case Warning warning when warning.SecondaryPunishmentId.HasValue:
                    var secondary = await Context.Database.Punishments.FindAsync(warning.SecondaryPunishmentId.Value);

                    builder.AddField(Punishments.FormatAdditionalPunishment(secondary, Context.Language));
                    break;
                }

                if (punishment is RevocablePunishment revocable)
                {
                    if (revocable.IsAppealable)
                    {
                        builder.AddField(Context.Localize("punishment_appealed"), revocable.AppealedAt.HasValue
                            ? $"✅ {revocable.AppealedAt.Value.ToString("g", Context.Language.Culture)} - {revocable.AppealReason.TrimTo(950)}"
                            : "❌");
                    }

                    var revoker = revocable.RevokedAt.HasValue
                        ? await Context.Client.GetOrDownloadUserAsync(revocable.RevokerId)
                        : default;

                    builder.AddField(Context.Localize("punishment_revoked"), revocable.RevokedAt.HasValue
                        ? "✅ " + revocable.RevokedAt.Value.ToString("g", Context.Language.Culture) + $" - {Markdown.Bold(revoker?.Tag ?? "???")} - " +
                                     (revocable.RevocationReason?.TrimTo(920) ?? Context.Localize("punishment_noreason"))
                        : "❌");
                }

                if (punishment.Format != ImageFormat.Default)
                {
                    builder.WithImageUrl($"attachment://attachment.{punishment.Format.ToString().ToLower()}");
                    return(CommandSuccess(embed: builder.Build(), attachment: new LocalAttachment(punishment.Image,
                                                                                                  $"attachment.{punishment.Format.ToString().ToLower()}")));
                }

                return(CommandSuccess(embed: builder.Build()));
            }
        public void setLifeEvents()
        {
            int randomNumber = 0;

            while (lifeEvents.Count < numberOfLifeEvents)
            {
                randomNumber = DiceRoll.roll(1, 100);

                if (1 <= randomNumber && randomNumber <= 10)
                {
                    Tragedies tragedies = new Tragedies(parents, siblings);
                    lifeEvents.Add($"You suffered a tragedy. {tragedies.Roll()}");
                }
                else if (11 <= randomNumber && randomNumber <= 20)
                {
                    Boons boons = new Boons();
                    lifeEvents.Add($"You gained a bit of good fortune. {boons.Roll()}");
                    equipment.Add(boons.GetItem());
                }
                else if (21 <= randomNumber && randomNumber <= 30)
                {
                    Individual individual = Individual.generateIndividual();
                    if (lifeEvents.Contains("You fell in love or got married"))
                    {
                        lifeEvents.Add($"You had a child.\n{individual.getString()}");
                    }
                    else
                    {
                        lifeEvents.Add($"You fell in love or got married.\n{individual.getString()}");
                    }
                }
                else if (31 <= randomNumber && randomNumber <= 40)
                {
                    Individual adventurer = Individual.generateIndividual();
                    adventurer.relationship = "Hostile";
                    adventurer.setLivingStatus();

                    lifeEvents.Add($"You made an enemy of an adventurer. You are {(DiceRoll.roll(1, 6) % 2 == 0 ? "to blame" : "blameless")} for the rift between you two. " +
                                   $"Work with your DM to determine this hostile character’s identity and the danger this enemy poses to you.\n{adventurer.getString()}");
                }
                else if (41 <= randomNumber && randomNumber <= 50)
                {
                    Individual adventurer = Individual.generateIndividual();
                    adventurer.relationship = "Friendly";
                    adventurer.setLivingStatus();

                    lifeEvents.Add($"You made a friend of an adventurer. Work with your DM to add more detail to this friendly character and establish how your friendship began.\n{adventurer.getString()}");
                }
                else if (51 <= randomNumber && randomNumber <= 70)
                {
                    lifeEvents.Add("You spent time working in a job related to your background. Start the game with an extra 2d6 gp.");
                }
                else if (71 <= randomNumber && randomNumber <= 75)
                {
                    Individual individual = Individual.generateIndividual();
                    lifeEvents.Add($"You met someone important. Work out additional details with your DM as needed to fit this character into your backstory.\n{individual.getString()}");
                }
                else if (76 <= randomNumber && randomNumber <= 80)
                {
                    Adventures adventures = new Adventures();
                    lifeEvents.Add($"You went on an adventure. {adventures.Roll()} Work with your DM to determine the nature of the adventure and the creatures you encountered.");
                    equipment.Add(adventures.GetItem());
                }
                else if (81 <= randomNumber && randomNumber <= 85)
                {
                    SupernaturalEvents supernaturalEvents = new SupernaturalEvents();
                    lifeEvents.Add($"You had a supernatural experience. {supernaturalEvents.Roll()}");
                }
                else if (86 <= randomNumber && randomNumber <= 90)
                {
                    Wars wars = new Wars();
                    lifeEvents.Add($"You fought in a battle. {wars.Roll()} Work with your DM to come up with the reason for the battle and the factions involved. It might have been a small conflict between your community and a band of orcs, or it could have been a major battle in a larger war.");
                }
                else if (91 <= randomNumber && randomNumber <= 95)
                {
                    Crimes      crimes      = new Crimes();
                    Punishments punishments = new Punishments();

                    lifeEvents.Add($"You committed a crime or were wrong accused of doing so, the nature of which was was {crimes.Roll()}. {punishments.Roll()}");
                }
                else if (96 <= randomNumber && randomNumber <= 99)
                {
                    lifeEvents.Add($"You encountered something magical. {new ArcaneMatters().Roll()}");
                }
                else if (randomNumber == 100)
                {
                    WeirdStuff weirdStuff = new WeirdStuff();
                    lifeEvents.Add($"Something truly strange happened to you. {weirdStuff.Roll()}");
                }
            }
        }