Search in sources :

Example 1 with GuildMemberRoleRemoveEvent

use of net.dv8tion.jda.api.events.guild.member.GuildMemberRoleRemoveEvent in project JDA by DV8FromTheWorld.

the class EntityBuilder method updateMemberRoles.

private void updateMemberRoles(MemberImpl member, List<Role> newRoles, long responseNumber) {
    Set<Role> currentRoles = member.getRoleSet();
    // Find the roles removed.
    List<Role> removedRoles = new LinkedList<>();
    each: for (Role role : currentRoles) {
        for (Iterator<Role> it = newRoles.iterator(); it.hasNext(); ) {
            Role r = it.next();
            if (role.equals(r)) {
                it.remove();
                continue each;
            }
        }
        removedRoles.add(role);
    }
    if (removedRoles.size() > 0)
        currentRoles.removeAll(removedRoles);
    if (newRoles.size() > 0)
        currentRoles.addAll(newRoles);
    if (removedRoles.size() > 0) {
        getJDA().handleEvent(new GuildMemberRoleRemoveEvent(getJDA(), responseNumber, member, removedRoles));
    }
    if (newRoles.size() > 0) {
        getJDA().handleEvent(new GuildMemberRoleAddEvent(getJDA(), responseNumber, member, newRoles));
    }
}
Also used : TemplateRole(net.dv8tion.jda.api.entities.templates.TemplateRole) GuildMemberRoleAddEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRoleAddEvent) GuildMemberRoleRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRoleRemoveEvent)

Example 2 with GuildMemberRoleRemoveEvent

use of net.dv8tion.jda.api.events.guild.member.GuildMemberRoleRemoveEvent in project Sx4 by sx4-discord-bot.

the class LoggerHandler method onGuildMemberRoleRemove.

public void onGuildMemberRoleRemove(GuildMemberRoleRemoveEvent event) {
    Guild guild = event.getGuild();
    Member member = event.getMember();
    User user = event.getUser();
    List<Role> roles = event.getRoles();
    Role firstRole = roles.get(0);
    // Ensure role delete event has been sent just in case
    this.delay(() -> {
        StringBuilder description = new StringBuilder();
        boolean multiple = roles.size() > 1;
        LoggerEvent loggerEvent = LoggerEvent.MEMBER_ROLE_REMOVE;
        LoggerContext loggerContext = new LoggerContext().setRole(multiple ? 0L : firstRole.getIdLong()).setUser(user);
        WebhookEmbedBuilder embed = new WebhookEmbedBuilder();
        embed.setColor(this.bot.getConfig().getRed());
        embed.setTimestamp(Instant.now());
        embed.setAuthor(new EmbedAuthor(user.getAsTag(), user.getEffectiveAvatarUrl(), null));
        boolean deleted;
        if (multiple) {
            StringBuilder builder = new StringBuilder();
            /* Make sure there is always enough space to write all the components to it */
            int maxLength = MessageEmbed.DESCRIPTION_MAX_LENGTH - 32 - /* Max nickname length */
            32 - /* Result String overhead */
            16 - /* " and x more" overhead */
            3;
            for (int i = 0; i < roles.size(); i++) {
                Role role = roles.get(i);
                String entry = (i == roles.size() - 1 ? " and " : i != 0 ? ", " : "") + role.getAsMention();
                if (builder.length() + entry.length() < maxLength) {
                    builder.append(entry);
                } else {
                    builder.append(String.format(" and **%s** more", roles.size() - i));
                    break;
                }
            }
            description.append(String.format("The roles %s have been removed from `%s`", builder, member.getEffectiveName()));
            deleted = false;
        } else {
            deleted = guild.getRoleById(firstRole.getIdLong()) == null;
            description.append(String.format("The role %s has been removed from `%s`", deleted ? "`" + firstRole.getName() + "`" : firstRole.getAsMention(), member.getEffectiveName()));
            embed.setFooter(new EmbedFooter(String.format("Role ID: %s", firstRole.getId()), null));
            if (deleted) {
                description.append(" by **role deletion**");
            }
        }
        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 (!deleted && !firstRole.isManaged() && guild.getSelfMember().hasPermission(Permission.VIEW_AUDIT_LOGS)) {
                this.retrieveAuditLogs(guild, ActionType.MEMBER_ROLE_UPDATE).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() == member.getUser().getIdLong()).filter(e -> {
                        AuditLogChange change = e.getChangeByKey(AuditLogKey.MEMBER_ROLES_REMOVE);
                        if (change == null) {
                            return false;
                        }
                        List<Map<String, String>> roleEntries = change.getNewValue();
                        List<String> roleIds = roleEntries.stream().map(roleEntry -> roleEntry.get("id")).collect(Collectors.toList());
                        for (Role role : roles) {
                            if (!roleIds.contains(role.getId())) {
                                return false;
                            }
                        }
                        return true;
                    }).map(AuditLogEntry::getUser).findFirst().orElse(null);
                    if (moderator != null) {
                        loggerContext.setModerator(moderator);
                        description.append(String.format(" by **%s**", moderator.getAsTag()));
                    }
                    embed.setDescription(description.toString());
                    this.queue(guild, loggers, loggerEvent, loggerContext, embed.build());
                });
            } else {
                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) TLongIntHashMap(gnu.trove.map.hash.TLongIntHashMap) TLongIntMap(gnu.trove.map.TLongIntMap) TLongObjectHashMap(gnu.trove.map.hash.TLongObjectHashMap) TLongObjectMap(gnu.trove.map.TLongObjectMap)

Aggregations

WebhookEmbed (club.minnced.discord.webhook.send.WebhookEmbed)1 EmbedAuthor (club.minnced.discord.webhook.send.WebhookEmbed.EmbedAuthor)1 EmbedField (club.minnced.discord.webhook.send.WebhookEmbed.EmbedField)1 EmbedFooter (club.minnced.discord.webhook.send.WebhookEmbed.EmbedFooter)1 WebhookEmbedBuilder (club.minnced.discord.webhook.send.WebhookEmbedBuilder)1 Accumulators (com.mongodb.client.model.Accumulators)1 Aggregates (com.mongodb.client.model.Aggregates)1 Filters (com.mongodb.client.model.Filters)1 Projections (com.mongodb.client.model.Projections)1 Sx4 (com.sx4.bot.core.Sx4)1 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)1 Operators (com.sx4.bot.database.mongo.model.Operators)1 GuildMessage (com.sx4.bot.entities.cache.GuildMessage)1 LoggerContext (com.sx4.bot.entities.management.LoggerContext)1 LoggerEvent (com.sx4.bot.entities.management.LoggerEvent)1 LoggerManager (com.sx4.bot.managers.LoggerManager)1 ColourUtility (com.sx4.bot.utility.ColourUtility)1 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)1 LoggerUtility (com.sx4.bot.utility.LoggerUtility)1 StringUtility (com.sx4.bot.utility.StringUtility)1