Search in sources :

Example 1 with GuildMessageReactionRemoveEvent

use of net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionRemoveEvent in project pokeraidbot by magnusmickelsson.

the class EmoticonSignUpMessageListener method onEvent.

@Override
public void onEvent(GenericEvent event) {
    String reactionMessageId = null;
    User user = null;
    if (emoteMessageId == null && infoMessageId == null) {
        LOGGER.trace("This listener haven't received a emote message id or info message id yet.");
        return;
    }
    try {
        if (event instanceof GuildMessageReactionAddEvent) {
            final GuildMessageReactionAddEvent reactionEvent = (GuildMessageReactionAddEvent) event;
            user = reactionEvent.getUser();
            // If the bot added any reactions, don't respond to them
            if (user.isBot())
                return;
            reactionMessageId = reactionEvent.getReaction().getMessageId();
            if (emoteMessageId == null || !emoteMessageId.equals(reactionMessageId)) {
                return;
            }
            // If this is a reaction for a user that just triggered an error with his/her reaction, skip it
            if (user.getName().equals(userHadError)) {
                userHadError = null;
                return;
            }
            final MessageReaction.ReactionEmote emote = reactionEvent.getReaction().getReactionEmote();
            if (emote != null) {
                switch(emote.getName()) {
                    case Emotes.ONE:
                        addToSignUp(user, 0, 0, 0, 1);
                        break;
                    case Emotes.TWO:
                        addToSignUp(user, 0, 0, 0, 2);
                        break;
                    case Emotes.THREE:
                        addToSignUp(user, 0, 0, 0, 3);
                        break;
                    case Emotes.FOUR:
                        addToSignUp(user, 0, 0, 0, 4);
                        break;
                    case Emotes.FIVE:
                        addToSignUp(user, 0, 0, 0, 5);
                        break;
                    default:
                }
            }
        } else if (event instanceof GuildMessageReactionRemoveEvent) {
            final GuildMessageReactionRemoveEvent reactionEvent = (GuildMessageReactionRemoveEvent) event;
            // If the bot added any reactions, don't respond to them
            user = reactionEvent.getUser();
            if (user.isBot())
                return;
            // If this is a reaction for a user that just triggered an error with his/her reaction, skip it
            if (user.getName().equals(userHadError)) {
                userHadError = null;
                return;
            }
            reactionMessageId = reactionEvent.getReaction().getMessageId();
            if (!emoteMessageId.equals(reactionMessageId)) {
                return;
            }
            final MessageReaction.ReactionEmote emote = reactionEvent.getReaction().getReactionEmote();
            if (emote != null) {
                switch(emote.getName()) {
                    case Emotes.ONE:
                        removeFromSignUp(user, 0, 0, 0, 1);
                        break;
                    case Emotes.TWO:
                        removeFromSignUp(user, 0, 0, 0, 2);
                        break;
                    case Emotes.THREE:
                        removeFromSignUp(user, 0, 0, 0, 3);
                        break;
                    case Emotes.FOUR:
                        removeFromSignUp(user, 0, 0, 0, 4);
                        break;
                    case Emotes.FIVE:
                        removeFromSignUp(user, 0, 0, 0, 5);
                        break;
                    default:
                }
            }
        }
    } catch (Throwable t) {
        if (event instanceof GenericGuildMessageReactionEvent) {
            final GenericGuildMessageReactionEvent guildMessageReactionEvent = (GenericGuildMessageReactionEvent) event;
            reactionMessageId = guildMessageReactionEvent.getReaction().getMessageId();
            if (emoteMessageId == null) {
                LOGGER.warn("Emote message ID = null, this should get cleaned up!" + " Event: " + printInfoAbout(event));
                return;
            }
            if (!emoteMessageId.equals(reactionMessageId)) {
                LOGGER.warn("We got a guild reaction event throwing exception, but not one we were listening for!" + " Event: " + printInfoAbout(event));
                return;
            }
            // Since we got an error, remove last reaction
            if (reactionMessageId != null && reactionMessageId.equals(emoteMessageId)) {
                // Do this with a slight delay to prevent graphical glitches client side.
                guildMessageReactionEvent.getReaction().removeReaction(user).queueAfter(30, TimeUnit.MILLISECONDS);
                userHadError = user.getName();
            }
            if (user != null && t.getMessage() != null) {
                MessageBuilder messageBuilder = new MessageBuilder();
                if (!t.getMessage().contains(user.getAsMention())) {
                    messageBuilder.append(user.getAsMention()).append(": ");
                }
                messageBuilder.append(t.getMessage());
                guildMessageReactionEvent.getChannel().sendMessage(messageBuilder.build()).queue();
            } else {
                LOGGER.warn("We have a situation where user " + user + " or exception (of type " + t.getClass().getSimpleName() + ") message is null! Event: " + printInfoAbout(event));
            }
        } else {
            LOGGER.warn("Exception in event listener! Event: " + printInfoAbout(event));
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Stacktrace:", t);
            }
        }
    }
}
Also used : MessageReaction(net.dv8tion.jda.api.entities.MessageReaction) User(net.dv8tion.jda.api.entities.User) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) GuildMessageReactionRemoveEvent(net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionRemoveEvent) GuildMessageReactionAddEvent(net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent) GenericGuildMessageReactionEvent(net.dv8tion.jda.api.events.message.guild.react.GenericGuildMessageReactionEvent)

Example 2 with GuildMessageReactionRemoveEvent

use of net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionRemoveEvent in project Sx4 by sx4-discord-bot.

the class StarboardHandler method onGuildMessageReactionRemove.

public void onGuildMessageReactionRemove(GuildMessageReactionRemoveEvent event) {
    User user = event.getUser();
    if (user == null || user.isBot()) {
        return;
    }
    List<Bson> starboardPipeline = List.of(Aggregates.match(Filters.or(Filters.eq("originalMessageId", event.getMessageIdLong()), Filters.eq("messageId", event.getMessageIdLong()))), Aggregates.project(Projections.include("originalMessageId", "messageId", "count")));
    List<Bson> pipeline = List.of(Aggregates.match(Filters.eq("_id", event.getGuild().getIdLong())), Aggregates.project(Projections.fields(Projections.include("starboard"), Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L))))), Aggregates.unionWith("starboards", starboardPipeline), Aggregates.group(null, Accumulators.max("count", "$count"), Accumulators.max("messageId", "$messageId"), Accumulators.max("originalMessageId", "$originalMessageId"), Accumulators.max("starboard", "$starboard"), Accumulators.max("premium", "$premium")));
    this.bot.getMongo().aggregateGuilds(pipeline).whenComplete((documents, aggregateException) -> {
        if (ExceptionUtility.sendErrorMessage(aggregateException)) {
            return;
        }
        if (documents.isEmpty()) {
            return;
        }
        Document data = documents.get(0);
        Document starboard = data.get("starboard", MongoDatabase.EMPTY_DOCUMENT);
        if (!starboard.get("enabled", false)) {
            return;
        }
        long channelId = starboard.get("channelId", 0L);
        TextChannel channel = channelId == 0L ? null : event.getGuild().getTextChannelById(channelId);
        if (channel == null) {
            return;
        }
        ReactionEmote emote = event.getReactionEmote();
        boolean emoji = emote.isEmoji();
        Document emoteData = starboard.get("emote", new Document("name", "⭐"));
        if ((emoji && !emote.getEmoji().equals(emoteData.getString("name"))) || (!emoji && (!emoteData.containsKey("id") || emoteData.getLong("id") != emote.getIdLong()))) {
            return;
        }
        Long originalMessageId = data.getLong("originalMessageId");
        if (originalMessageId == null) {
            return;
        }
        List<Document> config = starboard.getList("messages", Document.class, StarboardManager.DEFAULT_CONFIGURATION);
        this.bot.getMongo().deleteStarById(event.getUserIdLong(), originalMessageId).thenCompose(result -> {
            if (result.getDeletedCount() == 0) {
                return CompletableFuture.completedFuture(null);
            }
            List<Bson> update = List.of(Operators.set("count", Operators.subtract("$count", 1)), Operators.set("messageId", Operators.cond(Operators.isEmpty(Operators.filter(config, Operators.gte(Operators.subtract("$count", 1), "$$this.stars"))), Operators.REMOVE, "$messageId")));
            FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER);
            return this.bot.getMongo().findAndUpdateStarboard(Filters.eq("originalMessageId", originalMessageId), update, options);
        }).whenComplete((updatedData, exception) -> {
            if (ExceptionUtility.sendErrorMessage(exception) || updatedData == null) {
                return;
            }
            if (!data.containsKey("messageId")) {
                return;
            }
            WebhookMessage webhookMessage = this.getStarboardMessage(starboard, updatedData, event.getGuild(), event.getMember(), emote, data.getBoolean("premium"));
            if (webhookMessage == null) {
                this.bot.getStarboardManager().deleteStarboard(data.getLong("messageId"), channel.getIdLong(), starboard.get("webhook", MongoDatabase.EMPTY_DOCUMENT));
            } else {
                this.bot.getStarboardManager().editStarboard(data.getLong("messageId"), channel.getIdLong(), starboard.get("webhook", MongoDatabase.EMPTY_DOCUMENT), webhookMessage);
            }
        });
    });
}
Also used : Document(org.bson.Document) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) ReactionEmote(net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) MongoWriteException(com.mongodb.MongoWriteException) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) CompletableFuture(java.util.concurrent.CompletableFuture) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) GuildMessageReactionRemoveEvent(net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionRemoveEvent) Bson(org.bson.conversions.Bson) Formatter(com.sx4.bot.formatter.Formatter) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder) Sx4(com.sx4.bot.core.Sx4) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) com.mongodb.client.model(com.mongodb.client.model) EncodingUtil(net.dv8tion.jda.internal.utils.EncodingUtil) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) Operators(com.sx4.bot.database.mongo.model.Operators) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) MessageUtility(com.sx4.bot.utility.MessageUtility) StarboardManager(com.sx4.bot.managers.StarboardManager) CompletionException(java.util.concurrent.CompletionException) Route(net.dv8tion.jda.internal.requests.Route) RestActionImpl(net.dv8tion.jda.internal.requests.RestActionImpl) List(java.util.List) EventListener(net.dv8tion.jda.api.hooks.EventListener) GuildMessageReactionAddEvent(net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) NotNull(org.jetbrains.annotations.NotNull) Comparator(java.util.Comparator) StringUtility(com.sx4.bot.utility.StringUtility) ErrorCategory(com.mongodb.ErrorCategory) Document(org.bson.Document) ReactionEmote(net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote) Bson(org.bson.conversions.Bson) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) List(java.util.List)

Aggregations

GuildMessageReactionAddEvent (net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent)2 GuildMessageReactionRemoveEvent (net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionRemoveEvent)2 WebhookEmbed (club.minnced.discord.webhook.send.WebhookEmbed)1 WebhookEmbedBuilder (club.minnced.discord.webhook.send.WebhookEmbedBuilder)1 WebhookMessage (club.minnced.discord.webhook.send.WebhookMessage)1 WebhookMessageBuilder (club.minnced.discord.webhook.send.WebhookMessageBuilder)1 ErrorCategory (com.mongodb.ErrorCategory)1 MongoWriteException (com.mongodb.MongoWriteException)1 com.mongodb.client.model (com.mongodb.client.model)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 Formatter (com.sx4.bot.formatter.Formatter)1 JsonFormatter (com.sx4.bot.formatter.JsonFormatter)1 StarboardManager (com.sx4.bot.managers.StarboardManager)1 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)1 MessageUtility (com.sx4.bot.utility.MessageUtility)1 StringUtility (com.sx4.bot.utility.StringUtility)1 Comparator (java.util.Comparator)1 List (java.util.List)1