Search in sources :

Example 6 with GuildMessageReactionAddEvent

use of net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent in project Gary by help-chat.

the class PaginationHandler method execute.

@Override
protected void execute(GenericEvent event) {
    switch(EventsEnum.fromEvent(event)) {
        case MESSAGE_REACTION_ADD:
            GuildMessageReactionAddEvent e = (GuildMessageReactionAddEvent) event;
            if (!e.getMember().getUser().isBot()) {
                String messageId = e.getMessageId();
                if (paginations.containsKey(messageId)) {
                    MessageReaction.ReactionEmote reactionEmote = e.getReactionEmote();
                    PaginationPage newPage;
                    if (reactionEmote.getEmote() == null) {
                        newPage = paginations.get(messageId).getPage(reactionEmote.getName());
                    } else {
                        newPage = paginations.get(messageId).getPage(reactionEmote.getEmote());
                    }
                    if (newPage != null) {
                        Object newMessage = newPage.getMessage();
                        Message message = e.getChannel().retrieveMessageById(messageId).complete();
                        if (newMessage instanceof String) {
                            message.editMessage((String) newMessage).queue();
                        } else if (newMessage instanceof MessageEmbed) {
                            message.editMessage((MessageEmbed) newMessage).override(true).queue();
                        }
                        e.getReaction().removeReaction(e.getUser()).queue();
                    }
                }
            }
            break;
        case MESSAGE_DELETE:
            paginations.remove(((GuildMessageDeleteEvent) event).getMessageId());
            break;
    }
}
Also used : MessageReaction(net.dv8tion.jda.api.entities.MessageReaction) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Message(net.dv8tion.jda.api.entities.Message) PaginationPage(me.piggypiglet.gary.core.objects.paginations.PaginationPage) GuildMessageReactionAddEvent(net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent)

Example 7 with GuildMessageReactionAddEvent

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

the class StarboardHandler method onGuildMessageReactionAdd.

public void onGuildMessageReactionAdd(GuildMessageReactionAddEvent event) {
    if (event.getUser().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", "channelId")));
    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("messageId", "$originalMessageId"), Accumulators.max("channelId", "$channelId"), 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), messageChannelId = data.get("channelId", 0L);
        TextChannel messageChannel = messageChannelId == 0L ? event.getChannel() : event.getGuild().getTextChannelById(messageChannelId);
        TextChannel channel = channelId == 0L ? null : event.getGuild().getTextChannelById(channelId);
        if (channel == null || messageChannel == 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("messageId");
        long messageId = originalMessageId == null ? event.getMessageIdLong() : originalMessageId;
        messageChannel.retrieveMessageById(messageId).queue(message -> {
            String image = message.getAttachments().stream().filter(Attachment::isImage).map(Attachment::getUrl).findFirst().orElse(null);
            Document star = new Document("userId", event.getUser().getIdLong()).append("messageId", messageId).append("guildId", event.getGuild().getIdLong());
            this.bot.getMongo().insertStar(star).thenCompose(result -> {
                Bson update = Updates.combine(Updates.inc("count", 1), Updates.setOnInsert("originalMessageId", messageId), Updates.setOnInsert("guildId", event.getGuild().getIdLong()), Updates.setOnInsert("channelId", event.getChannel().getIdLong()), Updates.set("content", message.getContentRaw()), Updates.set("authorId", message.getAuthor().getIdLong()));
                if (image != null) {
                    update = Updates.combine(update, Updates.set("image", image));
                }
                FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER).upsert(true);
                return this.bot.getMongo().findAndUpdateStarboard(Filters.eq("originalMessageId", messageId), update, options);
            }).thenCompose(updatedData -> {
                WebhookMessage webhookMessage = this.getStarboardMessage(starboard, updatedData, event.getGuild(), event.getMember(), emote, data.getBoolean("premium"));
                if (webhookMessage == null) {
                    return CompletableFuture.completedFuture(null);
                }
                if (updatedData.containsKey("messageId")) {
                    this.bot.getStarboardManager().editStarboard(updatedData.getLong("messageId"), channel.getIdLong(), starboard.get("webhook", MongoDatabase.EMPTY_DOCUMENT), webhookMessage);
                    // return null so no update is made in the next stage
                    return CompletableFuture.completedFuture(null);
                } else {
                    return this.bot.getStarboardManager().sendStarboard(channel, starboard.get("webhook", MongoDatabase.EMPTY_DOCUMENT), webhookMessage);
                }
            }).whenComplete((createdMessage, exception) -> {
                if (exception instanceof CompletionException) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
                        // duplicate star just ignore
                        return;
                    }
                }
                if (ExceptionUtility.sendErrorMessage(exception)) {
                    return;
                }
                if (createdMessage != null) {
                    Route.CompiledRoute route = Route.Messages.ADD_REACTION.compile(Long.toString(createdMessage.getChannelId()), Long.toString(createdMessage.getId()), EncodingUtil.encodeReaction(emote.getAsReactionCode()), "@me");
                    new RestActionImpl<>(event.getJDA(), route).queue(null, ErrorResponseException.ignore(ErrorResponse.UNKNOWN_EMOJI, ErrorResponse.MISSING_PERMISSIONS, ErrorResponse.MISSING_ACCESS));
                    this.bot.getMongo().updateStarboard(Filters.eq("originalMessageId", messageId), Updates.set("messageId", createdMessage.getId())).whenComplete(MongoDatabase.exceptionally());
                }
            });
        });
    });
}
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) MongoWriteException(com.mongodb.MongoWriteException) Attachment(net.dv8tion.jda.api.entities.Message.Attachment) Document(org.bson.Document) ReactionEmote(net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote) Bson(org.bson.conversions.Bson) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) CompletionException(java.util.concurrent.CompletionException) Route(net.dv8tion.jda.internal.requests.Route)

Example 8 with GuildMessageReactionAddEvent

use of net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent in project Levelbot by Kaktushose.

the class ShopListener method onGuildMessageReactionAdd.

@Override
public void onGuildMessageReactionAdd(@NotNull GuildMessageReactionAddEvent event) {
    // bots should just be ignored
    if (event.getUser().isBot()) {
        return;
    }
    // must be in channel #levelsystem
    if (event.getChannel().getIdLong() != LEVEL_SYSTEM_CHANNEL_ID) {
        return;
    }
    if (levelbot.getUserService().getMutedUsers().contains(event.getUser().getIdLong())) {
        event.getReaction().removeReaction(event.getUser()).queue(null, new ErrorHandler().ignore(UNKNOWN_MESSAGE));
        return;
    }
    // indicates active purchase
    if (activeUsers.contains(event.getUser().getIdLong())) {
        event.getReaction().removeReaction(event.getUser()).queue(null, new ErrorHandler().ignore(UNKNOWN_MESSAGE));
        return;
    }
    Member member = event.getMember();
    ItemCategory itemCategory;
    switch(event.getMessageId()) {
        case PREMIUM_MESSAGE_ID:
            itemCategory = ItemCategory.PREMIUM;
            break;
        case DJ_MESSAGE_ID:
            itemCategory = ItemCategory.DJ;
            break;
        case NICKNAME_MESSAGE_ID:
            itemCategory = ItemCategory.NICKNAME;
            break;
        case COINS_BOOSTER_MESSAGE_ID:
            itemCategory = ItemCategory.COINS_BOOSTER;
            break;
        case XP_BOOSTER_MESSAGE_ID:
            itemCategory = ItemCategory.XP_BOOSTER;
            break;
        default:
            event.getReaction().removeReaction(member.getUser()).queue(null, new ErrorHandler().ignore(UNKNOWN_MESSAGE));
            return;
    }
    int variant;
    switch(event.getReactionEmote().getName()) {
        case NumberEmojis.ONE:
            variant = 0;
            break;
        case NumberEmojis.TWO:
            variant = 1;
            break;
        case NumberEmojis.THREE:
            variant = 2;
            break;
        default:
            event.getReaction().removeReaction(member.getUser()).queue();
            return;
    }
    if ((itemCategory == ItemCategory.COINS_BOOSTER || itemCategory == ItemCategory.XP_BOOSTER) && variant == 2) {
        event.getReaction().removeReaction(member.getUser()).queue();
        return;
    }
    Item item = levelService.getItemsByCategoryId(itemCategory.id).get(variant);
    BotUser botUser = userService.getUserById(member.getIdLong());
    String fail = null;
    if (shopService.hasItemOfCategory(member.getIdLong(), item.getCategoryId())) {
        fail = "Du besitzt dieses Item bereits!";
    }
    if (botUser.getCoins() < item.getPrice()) {
        fail = "Du hast nicht genug Münzen!";
    }
    TextChannel channel = event.getChannel();
    Consumer<Message> delete = success -> success.delete().queueAfter(30, TimeUnit.SECONDS, null, new ErrorHandler().ignore(UNKNOWN_MESSAGE));
    MessageBuilder builder = new MessageBuilder().append(member.getAsMention());
    if (fail != null) {
        // transaction failed
        channel.sendMessage(builder.setEmbeds(embedCache.getEmbed("shopError").injectValue("message", fail).toMessageEmbed()).build()).queue(delete);
    } else {
        activeUsers.add(member.getIdLong());
        // confirm transaction
        channel.sendMessage(builder.setEmbeds(embedCache.getEmbed("shopConfirm").injectValue("item", item.getName()).injectValue("price", item.getPrice()).toMessageEmbed()).build()).queue(confirmMessage -> {
            // wait for reactions
            // delete confirm message after 30 secs if nothing happens
            confirmMessage.delete().queueAfter(30, TimeUnit.SECONDS, success -> activeUsers.remove(member.getIdLong()), new ErrorHandler().ignore(UNKNOWN_MESSAGE));
            confirmMessage.addReaction(CONFIRM).and(confirmMessage.addReaction(CANCEL)).queue();
            ReactionWaiter waiter = new ReactionWaiter(confirmMessage, event.getMember(), CONFIRM, CANCEL);
            waiter.onEvent(reactionEvent -> {
                // on reaction confirm or cancel emoji
                confirmMessage.delete().queue();
                if (reactionEvent.getEmote().equals(CONFIRM)) {
                    shopService.buyItem(botUser.getUserId(), item.getItemId());
                    // successful transaction
                    channel.sendMessageEmbeds(embedCache.getEmbed("shopSuccess").injectValue("item", item.getName()).injectValue("days", TimeUnit.MILLISECONDS.toDays(item.getDuration())).toMessageEmbed()).queue(delete);
                    levelbot.getLogChannel().sendMessageEmbeds(embedCache.getEmbed("buyLog").injectValue("user", member.getAsMention()).injectValue("item", item.getName()).toMessageEmbed()).queue();
                }
                activeUsers.remove(member.getIdLong());
                waiter.stopWaiting(false);
            });
        });
    }
    event.getReaction().removeReaction(member.getUser()).queue();
}
Also used : Message(net.dv8tion.jda.api.entities.Message) BotUser(de.kaktushose.levelbot.database.model.BotUser) LevelService(de.kaktushose.levelbot.database.services.LevelService) ListenerAdapter(net.dv8tion.jda.api.hooks.ListenerAdapter) Set(java.util.Set) UNKNOWN_MESSAGE(net.dv8tion.jda.api.requests.ErrorResponse.UNKNOWN_MESSAGE) Levelbot(de.kaktushose.levelbot.bot.Levelbot) Member(net.dv8tion.jda.api.entities.Member) TextChannel(net.dv8tion.jda.api.entities.TextChannel) UserService(de.kaktushose.levelbot.database.services.UserService) HashSet(java.util.HashSet) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ShopService(de.kaktushose.levelbot.shop.data.ShopService) EmbedCache(com.github.kaktushose.jda.commands.embeds.EmbedCache) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) ReactionWaiter(de.kaktushose.discord.reactionwaiter.ReactionWaiter) GuildMessageReactionAddEvent(net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent) Item(de.kaktushose.levelbot.shop.data.items.Item) NotNull(org.jetbrains.annotations.NotNull) NumberEmojis(de.kaktushose.levelbot.util.NumberEmojis) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) BotUser(de.kaktushose.levelbot.database.model.BotUser) Message(net.dv8tion.jda.api.entities.Message) ReactionWaiter(de.kaktushose.discord.reactionwaiter.ReactionWaiter) Item(de.kaktushose.levelbot.shop.data.items.Item) TextChannel(net.dv8tion.jda.api.entities.TextChannel) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Member(net.dv8tion.jda.api.entities.Member)

Aggregations

GuildMessageReactionAddEvent (net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent)8 Message (net.dv8tion.jda.api.entities.Message)4 MessageReaction (net.dv8tion.jda.api.entities.MessageReaction)4 List (java.util.List)3 CompletableFuture (java.util.concurrent.CompletableFuture)2 JDA (net.dv8tion.jda.api.JDA)2 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)2 MessageEmbed (net.dv8tion.jda.api.entities.MessageEmbed)2 GenericEvent (net.dv8tion.jda.api.events.GenericEvent)2 GuildMessageReactionRemoveEvent (net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionRemoveEvent)2 NotNull (org.jetbrains.annotations.NotNull)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 ChatClientBootstrap (com.botdarr.clients.ChatClientBootstrap)1 EmbedCache (com.github.kaktushose.jda.commands.embeds.EmbedCache)1 ErrorCategory (com.mongodb.ErrorCategory)1 MongoWriteException (com.mongodb.MongoWriteException)1 com.mongodb.client.model (com.mongodb.client.model)1