Search in sources :

Example 1 with GuildMemberRemoveEvent

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

the class LoggerHandler method onGuildMemberRemove.

public void onGuildMemberRemove(GuildMemberRemoveEvent event) {
    Guild guild = event.getGuild();
    User user = event.getUser();
    Member member = event.getMember();
    List<Role> roles = member == null ? Collections.emptyList() : member.getRoles();
    String rolesMessage = StringUtility.joinLimited(", ", roles, Role::getAsMention, MessageEmbed.VALUE_MAX_LENGTH);
    LoggerContext loggerContext = new LoggerContext().setUser(user);
    WebhookEmbedBuilder embed = new WebhookEmbedBuilder();
    embed.setDescription(String.format("`%s` just left the server", user.getName()));
    embed.setColor(this.bot.getConfig().getRed());
    embed.setTimestamp(Instant.now());
    embed.setAuthor(new EmbedAuthor(user.getAsTag(), user.getEffectiveAvatarUrl(), null));
    embed.setFooter(new EmbedFooter(String.format("User ID: %s", user.getId()), null));
    if (rolesMessage.length() != 0) {
        embed.addField(new EmbedField(true, "Roles", rolesMessage));
    }
    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 = data.getList("loggers", Document.class);
        if (loggers.isEmpty()) {
            return;
        }
        if (guild.getSelfMember().hasPermission(Permission.VIEW_AUDIT_LOGS)) {
            this.retrieveAuditLogsDelayed(guild, ActionType.KICK).whenComplete((logs, auditException) -> {
                User moderator = logs == null ? null : logs.stream().filter(e -> e.getTargetIdLong() == user.getIdLong()).filter(e -> Duration.between(e.getTimeCreated(), ZonedDateTime.now(ZoneOffset.UTC)).toSeconds() <= 5).map(AuditLogEntry::getUser).findFirst().orElse(null);
                LoggerEvent loggerEvent = moderator == null ? LoggerEvent.MEMBER_LEAVE : LoggerEvent.MEMBER_KICKED;
                if (moderator != null) {
                    loggerContext.setModerator(moderator);
                    embed.setDescription(String.format("`%s` has been kicked by **%s**", user.getName(), moderator.getAsTag()));
                }
                this.queue(guild, loggers, loggerEvent, loggerContext, embed.build());
            });
            return;
        }
        LoggerEvent loggerEvent = LoggerEvent.MEMBER_LEAVE;
        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) EmbedField(club.minnced.discord.webhook.send.WebhookEmbed.EmbedField) 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 2 with GuildMemberRemoveEvent

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

the class GuildMemberRemoveHandler method handleInternally.

@Override
protected Long handleInternally(DataObject content) {
    final long id = content.getLong("guild_id");
    boolean setup = getJDA().getGuildSetupController().onRemoveMember(id, content);
    if (setup)
        return null;
    GuildImpl guild = (GuildImpl) getJDA().getGuildsView().get(id);
    if (guild == null) {
        // We probably just left the guild and this event is trying to remove us from the guild, therefore ignore
        return null;
    }
    final long userId = content.getObject("user").getUnsignedLong("id");
    if (userId == getJDA().getSelfUser().getIdLong()) {
        // We probably just left the guild and this event is trying to remove us from the guild, therefore ignore
        return null;
    }
    // Update the memberCount
    guild.onMemberRemove();
    CacheView.SimpleCacheView<MemberPresenceImpl> presences = guild.getPresenceView();
    if (presences != null)
        presences.remove(userId);
    User user = api.getEntityBuilder().createUser(content.getObject("user"));
    MemberImpl member = (MemberImpl) guild.getMembersView().remove(userId);
    if (member == null) {
        // WebSocketClient.LOG.debug("Received GUILD_MEMBER_REMOVE for a Member that does not exist in the specified Guild. UserId: {} GuildId: {}", userId, id);
        // Remove user from voice channel if applicable
        guild.getVoiceChannelsView().forEachUnordered((channel) -> {
            VoiceChannelImpl impl = (VoiceChannelImpl) channel;
            Member connected = impl.getConnectedMembersMap().remove(userId);
            if (// user left channel!
            connected != null) {
                getJDA().handleEvent(new GuildVoiceLeaveEvent(getJDA(), responseNumber, connected, channel));
            }
        });
        // Fire cache independent event, we can still inform the library user about the member removal
        getJDA().handleEvent(new GuildMemberRemoveEvent(getJDA(), responseNumber, guild, user, null));
        return null;
    }
    GuildVoiceStateImpl voiceState = (GuildVoiceStateImpl) member.getVoiceState();
    if (// If this user was in an AudioChannel, fire VoiceLeaveEvent.
    voiceState != null && voiceState.inAudioChannel()) {
        AudioChannel channel = voiceState.getChannel();
        voiceState.setConnectedChannel(null);
        ((AudioChannelMixin<?>) channel).getConnectedMembersMap().remove(userId);
        getJDA().handleEvent(new GuildVoiceLeaveEvent(getJDA(), responseNumber, member, channel));
    }
    // The user is not in a different guild that we share
    SnowflakeCacheViewImpl<User> userView = getJDA().getUsersView();
    try (UnlockHook hook = userView.writeLock()) {
        if (// don't remove selfUser from cache
        userId != getJDA().getSelfUser().getIdLong() && getJDA().getGuildsView().stream().noneMatch(g -> g.getMemberById(userId) != null)) {
            userView.remove(userId);
            getJDA().getEventCache().clear(EventCache.Type.USER, userId);
        }
    }
    // Cache independent event
    getJDA().handleEvent(new GuildMemberRemoveEvent(getJDA(), responseNumber, guild, user, member));
    return null;
}
Also used : GuildVoiceLeaveEvent(net.dv8tion.jda.api.events.guild.voice.GuildVoiceLeaveEvent) AudioChannel(net.dv8tion.jda.api.entities.AudioChannel) GuildMemberRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent) UnlockHook(net.dv8tion.jda.internal.utils.UnlockHook) net.dv8tion.jda.internal.entities(net.dv8tion.jda.internal.entities) JDAImpl(net.dv8tion.jda.internal.JDAImpl) CacheView(net.dv8tion.jda.api.utils.cache.CacheView) GuildVoiceLeaveEvent(net.dv8tion.jda.api.events.guild.voice.GuildVoiceLeaveEvent) Member(net.dv8tion.jda.api.entities.Member) DataObject(net.dv8tion.jda.api.utils.data.DataObject) User(net.dv8tion.jda.api.entities.User) AudioChannelMixin(net.dv8tion.jda.internal.entities.mixin.channel.middleman.AudioChannelMixin) SnowflakeCacheViewImpl(net.dv8tion.jda.internal.utils.cache.SnowflakeCacheViewImpl) User(net.dv8tion.jda.api.entities.User) AudioChannel(net.dv8tion.jda.api.entities.AudioChannel) CacheView(net.dv8tion.jda.api.utils.cache.CacheView) UnlockHook(net.dv8tion.jda.internal.utils.UnlockHook) GuildMemberRemoveEvent(net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent) Member(net.dv8tion.jda.api.entities.Member)

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