Search in sources :

Example 1 with Reason

use of com.sx4.bot.entities.mod.Reason in project Sx4 by sx4-discord-bot.

the class OffencesCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
    Bson filter = Filters.eq("guildId", event.getGuild().getIdLong());
    if (member != null) {
        filter = Filters.and(filter, Filters.eq("targetId", member.getIdLong()));
    }
    event.getMongo().getOffences(filter, Sorts.descending("_id")).whenComplete((iterable, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        try {
            List<Document> data = iterable.into(new ArrayList<>());
            if (data.isEmpty()) {
                event.replyFailure((member == null ? "This server" : "**" + member.getUser().getAsTag() + "**") + " has no offences").queue();
                return;
            }
            User user = member == null ? null : member.getUser();
            PagedResult<Document> paged = new PagedResult<>(event.getBot(), data).setPerPage(6).setCustomFunction(page -> {
                EmbedBuilder embed = new EmbedBuilder().setAuthor("Offences", null, member == null ? event.getGuild().getIconUrl() : user.getEffectiveAvatarUrl()).setTitle("Page " + page.getPage() + "/" + page.getMaxPage()).setFooter(PagedResult.DEFAULT_FOOTER_TEXT);
                page.forEach((offence, index) -> {
                    Action action = Action.fromData(offence.get("action", Document.class));
                    ObjectId id = offence.getObjectId("_id");
                    OffsetDateTime time = OffsetDateTime.ofInstant(Instant.ofEpochSecond(id.getTimestamp()), ZoneOffset.UTC);
                    long targetId = offence.getLong("targetId");
                    User target = member == null ? event.getShardManager().getUserById(targetId) : user;
                    String targetContent = target == null ? "Anonymous#0000 (" + targetId + ")" : target.getAsTag();
                    long moderatorId = offence.getLong("moderatorId");
                    User moderator = event.getShardManager().getUserById(moderatorId);
                    String moderatorContent = moderator == null ? "Anonymous#0000 (" + moderatorId + ")" : moderator.getAsTag();
                    embed.addField(action.toString(), String.format("Target: %s\nModerator: %s\nReason: %s\nTime: %s", targetContent, moderatorContent, offence.get("reason", "None Given"), time.format(this.formatter)), true);
                });
                return new MessageBuilder().setEmbeds(embed.build());
            });
            paged.execute(event);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    });
}
Also used : Action(com.sx4.bot.entities.mod.action.Action) User(net.dv8tion.jda.api.entities.User) ObjectId(org.bson.types.ObjectId) Document(org.bson.Document) Bson(org.bson.conversions.Bson) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) OffsetDateTime(java.time.OffsetDateTime) PagedResult(com.sx4.bot.paged.PagedResult)

Example 2 with Reason

use of com.sx4.bot.entities.mod.Reason in project Sx4 by sx4-discord-bot.

the class ModLogCommand method view.

@Command(value = "view", aliases = { "viewcase", "view case", "list" }, description = "View a mod log case from the server")
@CommandId(70)
@Examples({ "modlog view 5e45ce6d3688b30ee75201ae", "modlog view" })
public void view(Sx4CommandEvent event, @Argument(value = "id", nullDefault = true) ObjectId id) {
    Bson projection = Projections.include("moderatorId", "reason", "targetId", "action");
    if (id == null) {
        List<Document> allData = event.getMongo().getModLogs(Filters.eq("guildId", event.getGuild().getIdLong()), projection).into(new ArrayList<>());
        if (allData.isEmpty()) {
            event.replyFailure("There are no mod logs in this server").queue();
            return;
        }
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), allData).setDisplayFunction(data -> {
            long targetId = data.getLong("targetId");
            User target = event.getShardManager().getUserById(targetId);
            return Action.fromData(data.get("action", Document.class)) + " to `" + (target == null ? targetId : target.getAsTag() + "`");
        }).setIncreasedIndex(true);
        paged.onSelect(select -> event.reply(ModLog.fromData(select.getSelected()).getEmbed(event.getShardManager())).queue());
        paged.execute(event);
    } else {
        Document data = event.getMongo().getModLogById(Filters.and(Filters.eq("_id", id), Filters.eq("guildId", event.getGuild().getIdLong())), projection);
        if (data == null) {
            event.replyFailure("I could not find a mod log with that id").queue();
            return;
        }
        event.reply(ModLog.fromData(data).getEmbed(event.getShardManager())).queue();
    }
}
Also used : Document(org.bson.Document) CancelException(com.sx4.bot.waiter.exception.CancelException) WebhookClient(club.minnced.discord.webhook.WebhookClient) Command(com.jockie.bot.core.command.Command) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) TextChannel(net.dv8tion.jda.api.entities.TextChannel) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) PagedResult(com.sx4.bot.paged.PagedResult) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) Pair(net.dv8tion.jda.internal.utils.tuple.Pair) ButtonUtility(com.sx4.bot.utility.ButtonUtility) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) Reason(com.sx4.bot.entities.mod.Reason) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) com.mongodb.client.model(com.mongodb.client.model) Range(com.sx4.bot.entities.argument.Range) Argument(com.jockie.bot.core.argument.Argument) Action(com.sx4.bot.entities.mod.action.Action) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Operators(com.sx4.bot.database.mongo.model.Operators) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Sx4Command(com.sx4.bot.core.Sx4Command) CompletionException(java.util.concurrent.CompletionException) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) Premium(com.sx4.bot.annotations.command.Premium) ModuleCategory(com.sx4.bot.category.ModuleCategory) ModLog(com.sx4.bot.entities.mod.ModLog) List(java.util.List) Examples(com.sx4.bot.annotations.command.Examples) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) User(net.dv8tion.jda.api.entities.User) Document(org.bson.Document) PagedResult(com.sx4.bot.paged.PagedResult) Bson(org.bson.conversions.Bson) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 3 with Reason

use of com.sx4.bot.entities.mod.Reason in project Sx4 by sx4-discord-bot.

the class TemporaryBanCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user") String userArgument, @Argument(value = "time", nullDefault = true) Duration time, @Argument(value = "reason", endless = true, nullDefault = true) Reason reason, @Option(value = "days", description = "Set how many days of messages should be deleted from the user") @DefaultNumber(1) @Limit(min = 0, max = 7) int days) {
    SearchUtility.getUser(event.getShardManager(), userArgument).thenAccept(user -> {
        if (user == null) {
            event.replyFailure("I could not find that user").queue();
            return;
        }
        if (user.getIdLong() == event.getSelfUser().getIdLong()) {
            event.replyFailure("You cannot ban me, that is illegal").queue();
            return;
        }
        Guild guild = event.getGuild();
        Member member = guild.getMember(user);
        if (member != null) {
            if (!event.getMember().canInteract(member)) {
                event.replyFailure("You cannot ban someone higher or equal than your top role").queue();
                return;
            }
            if (!event.getSelfMember().canInteract(member)) {
                event.replyFailure("I cannot ban someone higher or equal than my top role").queue();
                return;
            }
        }
        event.getGuild().retrieveBan(user).submit().whenComplete((ban, exception) -> {
            if (exception instanceof ErrorResponseException && ((ErrorResponseException) exception).getErrorResponse() == ErrorResponse.UNKNOWN_BAN) {
                Document data = event.getMongo().getGuildById(guild.getIdLong(), Projections.include("temporaryBan.defaultTime")).get("temporaryBan", MongoDatabase.EMPTY_DOCUMENT);
                long duration = time == null ? data.get("defaultTime", ModUtility.DEFAULT_TEMPORARY_BAN_DURATION) : time.toSeconds();
                List<Bson> update = List.of(Operators.set("unbanAt", Operators.add(Operators.nowEpochSecond(), duration)));
                Bson filter = Filters.and(Filters.eq("userId", event.getMember().getIdLong()), Filters.eq("guildId", event.getGuild().getIdLong()));
                event.getMongo().updateTemporaryBan(filter, update, new UpdateOptions().upsert(true)).whenComplete((result, resultException) -> {
                    if (ExceptionUtility.sendExceptionally(event, resultException)) {
                        return;
                    }
                    event.getGuild().ban(user, days).reason(ModUtility.getAuditReason(reason, event.getAuthor())).queue($ -> {
                        event.replySuccess("**" + user.getAsTag() + "** has been temporarily banned for " + TimeUtility.LONG_TIME_FORMATTER.parse(duration)).queue();
                        event.getBot().getModActionManager().onModAction(new TemporaryBanEvent(event.getMember(), user, reason, member != null, duration));
                        event.getBot().getTemporaryBanManager().putBan(event.getGuild().getIdLong(), user.getIdLong(), duration);
                    });
                });
            } else {
                if (ExceptionUtility.sendExceptionally(event, exception)) {
                    return;
                }
                event.replyFailure("That user is already banned").queue();
            }
        });
    });
}
Also used : ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Guild(net.dv8tion.jda.api.entities.Guild) Document(org.bson.Document) TemporaryBanEvent(com.sx4.bot.events.mod.TemporaryBanEvent) Member(net.dv8tion.jda.api.entities.Member) UpdateOptions(com.mongodb.client.model.UpdateOptions) Bson(org.bson.conversions.Bson)

Example 4 with Reason

use of com.sx4.bot.entities.mod.Reason in project Sx4 by sx4-discord-bot.

the class BanCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user") String userArgument, @Argument(value = "reason", endless = true, nullDefault = true) Reason reason, @Option(value = "days", description = "Set how many days of messages should be deleted from the user") @DefaultNumber(1) @Limit(min = 0, max = 7) int days) {
    SearchUtility.getUser(event.getShardManager(), userArgument).thenAccept(user -> {
        if (user == null) {
            event.replyFailure("I could not find that user").queue();
            return;
        }
        if (user.getIdLong() == event.getSelfUser().getIdLong()) {
            event.replyFailure("You cannot ban me, that is illegal").queue();
            return;
        }
        Member member = event.getGuild().getMember(user);
        if (member != null) {
            if (!event.getMember().canInteract(member)) {
                event.replyFailure("You cannot ban someone higher or equal than your top role").queue();
                return;
            }
            if (!event.getSelfMember().canInteract(member)) {
                event.replyFailure("I cannot ban someone higher or equal than my top role").queue();
                return;
            }
        }
        event.getGuild().retrieveBan(user).submit().whenComplete((ban, exception) -> {
            if (exception instanceof ErrorResponseException && ((ErrorResponseException) exception).getErrorResponse() == ErrorResponse.UNKNOWN_BAN) {
                event.getGuild().ban(user, days).reason(ModUtility.getAuditReason(reason, event.getAuthor())).queue($ -> {
                    event.replySuccess("**" + user.getAsTag() + "** has been banned").queue();
                    event.getBot().getModActionManager().onModAction(new BanEvent(event.getMember(), user, reason, member != null));
                });
            } else {
                event.replyFailure("That user is already banned").queue();
            }
        });
    });
}
Also used : BanEvent(com.sx4.bot.events.mod.BanEvent) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Member(net.dv8tion.jda.api.entities.Member)

Example 5 with Reason

use of com.sx4.bot.entities.mod.Reason in project Sx4 by sx4-discord-bot.

the class LoggerHandler method handleBulkMessages.

public void handleBulkMessages(TextChannel textChannel, List<String> messageIds, List<Document> loggers, LoggerEvent loggerEvent, User moderator) {
    Guild guild = textChannel.getGuild();
    for (Document logger : loggers) {
        if ((logger.get("events", LoggerEvent.ALL) & loggerEvent.getRaw()) != loggerEvent.getRaw()) {
            continue;
        }
        long channelId = logger.getLong("channelId");
        TextChannel channel = guild.getTextChannelById(channelId);
        if (channel == null) {
            continue;
        }
        List<Document> entities = logger.getEmbedded(List.of("blacklist", "entities"), Collections.emptyList());
        List<WebhookEmbed> embeds = new ArrayList<>();
        for (String messageId : messageIds) {
            WebhookEmbedBuilder embed = new WebhookEmbedBuilder().setColor(this.bot.getConfig().getRed()).setTimestamp(Instant.now()).setFooter(new EmbedFooter("Message ID: " + messageId, null));
            LoggerContext loggerContext = new LoggerContext().setChannel(textChannel);
            if (moderator != null) {
                loggerContext.setModerator(moderator);
            }
            String reason = moderator == null ? "in a bulk delete" : "by **" + moderator.getAsTag() + "**";
            GuildMessage message = this.bot.getMessageCache().getMessageById(messageId);
            if (message == null) {
                if (!LoggerUtility.isWhitelisted(entities, loggerEvent, loggerContext)) {
                    continue;
                }
                embed.setDescription(String.format("A message sent in %s was deleted %s", textChannel.getAsMention(), reason));
                embed.setAuthor(new EmbedAuthor(guild.getName(), guild.getIconUrl(), null));
            } else {
                User author = message.getAuthor();
                loggerContext.setUser(author);
                if (!LoggerUtility.isWhitelisted(entities, loggerEvent, loggerContext)) {
                    continue;
                }
                embed.setDescription(String.format("The message sent by `%s` in %s was deleted %s", author.getName(), textChannel.getAsMention(), reason));
                embed.setAuthor(new EmbedAuthor(author.getAsTag(), author.getEffectiveAvatarUrl(), null));
                String content = message.getContent();
                if (!content.isBlank()) {
                    embed.addField(new EmbedField(false, "Message", StringUtility.limit(content, MessageEmbed.VALUE_MAX_LENGTH, "...")));
                }
            }
            embeds.add(embed.build());
        }
        this.getManager(channelId).queue(channel, logger, embeds);
    }
}
Also used : EmbedField(club.minnced.discord.webhook.send.WebhookEmbed.EmbedField) Document(org.bson.Document) LoggerContext(com.sx4.bot.entities.management.LoggerContext) EmbedFooter(club.minnced.discord.webhook.send.WebhookEmbed.EmbedFooter) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) GuildMessage(com.sx4.bot.entities.cache.GuildMessage) EmbedAuthor(club.minnced.discord.webhook.send.WebhookEmbed.EmbedAuthor) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder)

Aggregations

Document (org.bson.Document)11 Bson (org.bson.conversions.Bson)10 Reason (com.sx4.bot.entities.mod.Reason)8 User (net.dv8tion.jda.api.entities.User)8 Member (net.dv8tion.jda.api.entities.Member)7 com.mongodb.client.model (com.mongodb.client.model)6 Operators (com.sx4.bot.database.mongo.model.Operators)6 Permission (net.dv8tion.jda.api.Permission)6 Guild (net.dv8tion.jda.api.entities.Guild)6 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)5 CompletionException (java.util.concurrent.CompletionException)5 Role (net.dv8tion.jda.api.entities.Role)5 ErrorResponseException (net.dv8tion.jda.api.exceptions.ErrorResponseException)5 ObjectId (org.bson.types.ObjectId)5 Command (com.jockie.bot.core.command.Command)4 Sx4 (com.sx4.bot.core.Sx4)4 Action (com.sx4.bot.entities.mod.action.Action)4 List (java.util.List)4 Sx4Command (com.sx4.bot.core.Sx4Command)3 com.sx4.bot.entities.mod.action (com.sx4.bot.entities.mod.action)3