Search in sources :

Example 6 with AuditLogChange

use of net.dv8tion.jda.api.audit.AuditLogChange in project Sx4 by sx4-discord-bot.

the class LoggerHandler method onPermissionOverrideUpdate.

public void onPermissionOverrideUpdate(PermissionOverrideUpdateEvent event) {
    Guild guild = event.getGuild();
    GuildChannel channel = event.getChannel();
    IPermissionHolder permissionHolder = event.getPermissionHolder();
    PermissionOverride permissionOverride = event.getPermissionOverride();
    ChannelType channelType = event.getChannelType();
    LoggerEvent loggerEvent = channelType == ChannelType.CATEGORY ? LoggerEvent.CATEGORY_OVERRIDE_CREATE : channelType == ChannelType.STORE ? LoggerEvent.STORE_CHANNEL_OVERRIDE_CREATE : channelType == ChannelType.VOICE ? LoggerEvent.VOICE_CHANNEL_OVERRIDE_CREATE : LoggerEvent.TEXT_CHANNEL_OVERRIDE_CREATE;
    LoggerContext loggerContext = new LoggerContext().setUser(event.isMemberOverride() ? permissionHolder.getIdLong() : 0L).setRole(event.isRoleOverride() ? permissionHolder.getIdLong() : 0L).setChannel(channel);
    String message = LoggerUtility.getPermissionOverrideDifference(event.getOldAllowRaw(), event.getOldInheritedRaw(), event.getOldDenyRaw(), permissionOverride);
    StringBuilder description = new StringBuilder(String.format("The %s %s has had permission overrides updated for %s", LoggerUtility.getChannelTypeReadable(channelType), channelType == ChannelType.CATEGORY ? "`" + channel.getName() + "`" : channel.getAsMention(), event.isRoleOverride() ? event.getRole().getAsMention() : "`" + event.getMember().getEffectiveName() + "`"));
    WebhookEmbedBuilder embed = new WebhookEmbedBuilder();
    embed.setColor(this.bot.getConfig().getOrange());
    embed.setTimestamp(Instant.now());
    embed.setAuthor(new EmbedAuthor(guild.getName(), guild.getIconUrl(), null));
    embed.setFooter(new EmbedFooter(String.format("%s ID: %s", event.isRoleOverride() ? "Role" : "User", permissionHolder.getIdLong()), null));
    this.bot.getMongo().aggregateLoggers(this.getPipeline(guild.getIdLong())).whenComplete((documents, exception) -> {
        if (ExceptionUtility.sendErrorMessage(exception)) {
            return;
        }
        if (documents.isEmpty()) {
            return;
        }
        Document data = documents.get(0);
        List<Document> loggers = LoggerUtility.getValidLoggers(data.getList("loggers", Document.class), loggerEvent, loggerContext);
        if (loggers.isEmpty()) {
            return;
        }
        if (guild.getSelfMember().hasPermission(Permission.VIEW_AUDIT_LOGS)) {
            this.retrieveAuditLogsDelayed(guild, ActionType.CHANNEL_OVERRIDE_CREATE).whenComplete((logs, auditException) -> {
                User moderator = logs == null ? null : logs.stream().filter(e -> Duration.between(e.getTimeCreated(), ZonedDateTime.now(ZoneOffset.UTC)).toSeconds() <= 5).filter(e -> e.getTargetIdLong() == channel.getIdLong()).filter(e -> {
                    AuditLogChange allow = e.getChangeByKey("allow"), deny = e.getChangeByKey("deny");
                    Integer denyNewValue = deny == null ? null : deny.getNewValue(), denyOldValue = deny == null ? null : deny.getOldValue();
                    Integer allowNewValue = allow == null ? null : allow.getNewValue(), allowOldValue = allow == null ? null : allow.getOldValue();
                    int denyNew = denyNewValue == null ? (int) permissionOverride.getDeniedRaw() : denyNewValue, denyOld = denyOldValue == null ? (int) event.getOldDenyRaw() : denyOldValue;
                    int allowNew = allowNewValue == null ? (int) permissionOverride.getAllowedRaw() : allowNewValue, allowOld = allowOldValue == null ? (int) event.getOldAllowRaw() : allowOldValue;
                    return denyNew == permissionOverride.getDeniedRaw() && denyOld == event.getOldDenyRaw() && allowNew == permissionOverride.getAllowedRaw() && allowOld == event.getOldAllowRaw();
                }).map(AuditLogEntry::getUser).findFirst().orElse(null);
                if (moderator != null) {
                    loggerContext.setModerator(moderator);
                    description.append(String.format(" by **%s**", moderator.getAsTag()));
                }
                description.append(message);
                embed.setDescription(description.toString());
                this.queue(guild, loggers, loggerEvent, loggerContext, embed.build());
            });
        } else {
            description.append(message);
            embed.setDescription(description.toString());
            this.queue(guild, loggers, loggerEvent, loggerContext, embed.build());
        }
    });
}
Also used : MessageBulkDeleteEvent(net.dv8tion.jda.api.events.message.MessageBulkDeleteEvent) Document(org.bson.Document) PermissionOverrideCreateEvent(net.dv8tion.jda.api.events.guild.override.PermissionOverrideCreateEvent) RoleCreateEvent(net.dv8tion.jda.api.events.role.RoleCreateEvent) StoreChannelDeleteEvent(net.dv8tion.jda.api.events.channel.store.StoreChannelDeleteEvent) Permission(net.dv8tion.jda.api.Permission) ZonedDateTime(java.time.ZonedDateTime) Aggregates(com.mongodb.client.model.Aggregates) EmoteUpdateRolesEvent(net.dv8tion.jda.api.events.emote.update.EmoteUpdateRolesEvent) AuditLogChange(net.dv8tion.jda.api.audit.AuditLogChange) CategoryCreateEvent(net.dv8tion.jda.api.events.channel.category.CategoryCreateEvent) LoggerManager(com.sx4.bot.managers.LoggerManager) ColourUtility(com.sx4.bot.utility.ColourUtility) TextChannelDeleteEvent(net.dv8tion.jda.api.events.channel.text.TextChannelDeleteEvent) EmoteAddedEvent(net.dv8tion.jda.api.events.emote.EmoteAddedEvent) TextChannelUpdateNameEvent(net.dv8tion.jda.api.events.channel.text.update.TextChannelUpdateNameEvent) TextChannelCreateEvent(net.dv8tion.jda.api.events.channel.text.TextChannelCreateEvent) Duration(java.time.Duration) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) ZoneOffset(java.time.ZoneOffset) LoggerContext(com.sx4.bot.entities.management.LoggerContext) LoggerEvent(com.sx4.bot.entities.management.LoggerEvent) AuditLogKey(net.dv8tion.jda.api.audit.AuditLogKey) PermissionOverrideDeleteEvent(net.dv8tion.jda.api.events.guild.override.PermissionOverrideDeleteEvent) EmbedFooter(club.minnced.discord.webhook.send.WebhookEmbed.EmbedFooter) GuildMessageUpdateEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageUpdateEvent) java.util.concurrent(java.util.concurrent) EmoteUpdateNameEvent(net.dv8tion.jda.api.events.emote.update.EmoteUpdateNameEvent) CategoryDeleteEvent(net.dv8tion.jda.api.events.channel.category.CategoryDeleteEvent) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) GuildBanEvent(net.dv8tion.jda.api.events.guild.GuildBanEvent) GuildMemberRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent) EventListener(net.dv8tion.jda.api.hooks.EventListener) CategoryUpdateNameEvent(net.dv8tion.jda.api.events.channel.category.update.CategoryUpdateNameEvent) GuildMemberUpdateNicknameEvent(net.dv8tion.jda.api.events.guild.member.update.GuildMemberUpdateNicknameEvent) NotNull(org.jetbrains.annotations.NotNull) RoleUpdateColorEvent(net.dv8tion.jda.api.events.role.update.RoleUpdateColorEvent) ActionType(net.dv8tion.jda.api.audit.ActionType) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) VoiceChannelUpdateNameEvent(net.dv8tion.jda.api.events.channel.voice.update.VoiceChannelUpdateNameEvent) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) EmbedAuthor(club.minnced.discord.webhook.send.WebhookEmbed.EmbedAuthor) GuildMemberRoleRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRoleRemoveEvent) RoleUpdatePermissionsEvent(net.dv8tion.jda.api.events.role.update.RoleUpdatePermissionsEvent) VoiceChannelDeleteEvent(net.dv8tion.jda.api.events.channel.voice.VoiceChannelDeleteEvent) Projections(com.mongodb.client.model.Projections) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) TLongIntHashMap(gnu.trove.map.hash.TLongIntHashMap) EmbedField(club.minnced.discord.webhook.send.WebhookEmbed.EmbedField) AuditLogEntry(net.dv8tion.jda.api.audit.AuditLogEntry) Filters(com.mongodb.client.model.Filters) GuildMessageDeleteEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageDeleteEvent) Bson(org.bson.conversions.Bson) Pair(net.dv8tion.jda.internal.utils.tuple.Pair) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder) Sx4(com.sx4.bot.core.Sx4) GuildMemberRoleAddEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRoleAddEvent) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) EmoteRemovedEvent(net.dv8tion.jda.api.events.emote.EmoteRemovedEvent) Operators(com.sx4.bot.database.mongo.model.Operators) Accumulators(com.mongodb.client.model.Accumulators) TLongIntMap(gnu.trove.map.TLongIntMap) VoiceChannelCreateEvent(net.dv8tion.jda.api.events.channel.voice.VoiceChannelCreateEvent) LoggerUtility(com.sx4.bot.utility.LoggerUtility) RoleUpdateNameEvent(net.dv8tion.jda.api.events.role.update.RoleUpdateNameEvent) StoreChannelUpdateNameEvent(net.dv8tion.jda.api.events.channel.store.update.StoreChannelUpdateNameEvent) TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap) OkHttpClient(okhttp3.OkHttpClient) PermissionOverrideUpdateEvent(net.dv8tion.jda.api.events.guild.override.PermissionOverrideUpdateEvent) net.dv8tion.jda.api.events.guild.voice(net.dv8tion.jda.api.events.guild.voice) StoreChannelCreateEvent(net.dv8tion.jda.api.events.channel.store.StoreChannelCreateEvent) GuildMessage(com.sx4.bot.entities.cache.GuildMessage) GuildUnbanEvent(net.dv8tion.jda.api.events.guild.GuildUnbanEvent) TLongObjectMap(gnu.trove.map.TLongObjectMap) RoleDeleteEvent(net.dv8tion.jda.api.events.role.RoleDeleteEvent) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) StringUtility(com.sx4.bot.utility.StringUtility) GuildMemberJoinEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent) AuditLogChange(net.dv8tion.jda.api.audit.AuditLogChange) LoggerEvent(com.sx4.bot.entities.management.LoggerEvent) Document(org.bson.Document) LoggerContext(com.sx4.bot.entities.management.LoggerContext) EmbedFooter(club.minnced.discord.webhook.send.WebhookEmbed.EmbedFooter) EmbedAuthor(club.minnced.discord.webhook.send.WebhookEmbed.EmbedAuthor) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder)

Example 7 with AuditLogChange

use of net.dv8tion.jda.api.audit.AuditLogChange in project IB.ai by ib-ai.

the class GuildListener method queryAuditLog.

/**
 * Queries the audit logs to gain information about punishment handling.
 * @param guild The guild.
 * @param target The target member.
 */
private void queryAuditLog(Guild guild, long target, ActionType... actionTypes) {
    executorService.schedule(() -> {
        synchronized (mutex) {
            guild.retrieveAuditLogs().limit(10).queue(entries -> {
                if (entries.isEmpty()) {
                    IBai.INSTANCE.getLogger().info("No audit logs retrieved.");
                    return;
                }
                for (AuditLogEntry latest : entries) {
                    if (Arrays.stream(actionTypes).anyMatch(latest.getType()::equals) && latest.getTargetType() == TargetType.MEMBER && latest.getTargetIdLong() == target) {
                        IBai.INSTANCE.getLogger().info("Found audit log: type '{}', target type '{}', target id '{}', " + "user {}, options {}", latest.getType(), latest.getTargetType(), latest.getTargetId(), latest.getUser(), latest.getOptions());
                        guild.getJDA().retrieveUserById(latest.getTargetIdLong()).queue(user -> {
                            User staff = latest.getUser();
                            String reason = latest.getReason();
                            if (user == null || staff == null) {
                                IBai.INSTANCE.getLogger().info("User or Staff is null");
                                throw new RuntimeException("user/staff nil");
                            }
                            boolean redacted = false;
                            if (reason != null && (reason.toLowerCase().contains("-redacted") || reason.toLowerCase().contains("-redact"))) {
                                redacted = true;
                                reason = reason.replace("-redacted", "").replace("-redact", "");
                            }
                            // Temporary Shorthand for rule 5 bans
                            if (reason != null && reason.equalsIgnoreCase("-r5")) {
                                reason = "Rule 5. Academic Dishonesty is strictly prohibited.";
                                redacted = true;
                            }
                            Punishment punishment = new Punishment(null, user.getAsTag(), user.getId(), staff.getAsTag(), staff.getId(), reason, redacted);
                            PunishmentHandler handler = new PunishmentHandler(guild, punishment);
                            switch(latest.getType()) {
                                case KICK:
                                    punishment.setType(PunishmentType.KICK);
                                    handler.onPunish();
                                    break;
                                case MEMBER_ROLE_UPDATE:
                                    AuditLogChange rolesAddedRaw = latest.getChangeByKey(AuditLogKey.MEMBER_ROLES_ADD);
                                    AuditLogChange rolesRemovedRaw = latest.getChangeByKey(AuditLogKey.MEMBER_ROLES_REMOVE);
                                    if (rolesAddedRaw != null) {
                                        if (staff.getIdLong() == guild.getJDA().getSelfUser().getIdLong()) {
                                            IBai.INSTANCE.getLogger().info("Ignored adding role since it was sent by user " + "{} (self)", staff.getIdLong());
                                            return;
                                        }
                                        List<Map<String, String>> roles = rolesAddedRaw.getNewValue();
                                        if (isNotMute(guild, roles)) {
                                            return;
                                        }
                                        punishment.setType(PunishmentType.MUTE);
                                        handler.onPunish();
                                    }
                                    if (rolesRemovedRaw != null) {
                                        List<Map<String, String>> roles = rolesRemovedRaw.getNewValue();
                                        if (isNotMute(guild, roles)) {
                                            return;
                                        }
                                        punishment.setType(PunishmentType.MUTE);
                                        handler.onRevocation();
                                    }
                                    break;
                                case BAN:
                                    IBai.INSTANCE.getLogger().info("Handling Ban");
                                    punishment.setType(PunishmentType.BAN);
                                    handler.onPunish();
                                    break;
                                case UNBAN:
                                    punishment.setType(PunishmentType.BAN);
                                    handler.onRevocation();
                                    break;
                                default:
                                    break;
                            }
                        }, error -> {
                            IBai.INSTANCE.getLogger().info("Could not retrieve user.");
                            IBai.INSTANCE.getLogger().info(error.getMessage());
                        });
                        break;
                    }
                }
            }, error -> {
                IBai.INSTANCE.getLogger().info("Blimey, there's been an error in the audit log.");
                IBai.INSTANCE.getLogger().error(error.getMessage());
            });
        }
    }, 3, TimeUnit.SECONDS);
}
Also used : Punishment(com.ibdiscord.punish.Punishment) User(net.dv8tion.jda.api.entities.User) AuditLogEntry(net.dv8tion.jda.api.audit.AuditLogEntry) PunishmentHandler(com.ibdiscord.punish.PunishmentHandler) AuditLogChange(net.dv8tion.jda.api.audit.AuditLogChange) Map(java.util.Map)

Aggregations

AuditLogChange (net.dv8tion.jda.api.audit.AuditLogChange)7 AuditLogEntry (net.dv8tion.jda.api.audit.AuditLogEntry)6 ActionType (net.dv8tion.jda.api.audit.ActionType)5 WebhookEmbed (club.minnced.discord.webhook.send.WebhookEmbed)4 EmbedAuthor (club.minnced.discord.webhook.send.WebhookEmbed.EmbedAuthor)4 EmbedField (club.minnced.discord.webhook.send.WebhookEmbed.EmbedField)4 EmbedFooter (club.minnced.discord.webhook.send.WebhookEmbed.EmbedFooter)4 WebhookEmbedBuilder (club.minnced.discord.webhook.send.WebhookEmbedBuilder)4 Accumulators (com.mongodb.client.model.Accumulators)4 Aggregates (com.mongodb.client.model.Aggregates)4 Filters (com.mongodb.client.model.Filters)4 Projections (com.mongodb.client.model.Projections)4 Sx4 (com.sx4.bot.core.Sx4)4 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)4 Operators (com.sx4.bot.database.mongo.model.Operators)4 GuildMessage (com.sx4.bot.entities.cache.GuildMessage)4 LoggerContext (com.sx4.bot.entities.management.LoggerContext)4 LoggerEvent (com.sx4.bot.entities.management.LoggerEvent)4 LoggerManager (com.sx4.bot.managers.LoggerManager)4 ColourUtility (com.sx4.bot.utility.ColourUtility)4