Search in sources :

Example 6 with ReactionEmote

use of net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote in project Sx4 by sx4-discord-bot.

the class StarboardHandler method getStarboardMessage.

private WebhookMessage getStarboardMessage(Document guildData, Document starboard, Guild guild, Member member, ReactionEmote emote, boolean premium) {
    List<Document> messages = guildData.getList("messages", Document.class, StarboardManager.DEFAULT_CONFIGURATION);
    int stars = starboard.getInteger("count");
    Document messageData = messages.stream().filter(d -> starboard.getInteger("count") >= d.getInteger("stars")).max(Comparator.comparingInt(d -> d.getInteger("stars"))).orElse(null);
    if (messageData == null) {
        return null;
    }
    int nextStars = messages.stream().filter(d -> starboard.getInteger("count") < d.getInteger("stars")).mapToInt(d -> d.getInteger("stars")).min().orElse(0);
    User author = this.bot.getShardManager().getUserById(starboard.getLong("authorId"));
    long channelId = starboard.getLong("channelId");
    TextChannel channel = guild.getTextChannelById(channelId);
    if (channel == null) {
        return null;
    }
    String messageLink = "https://discord.com/channels/" + guild.getId() + "/" + channelId + "/" + starboard.getLong("originalMessageId");
    // temporary while embed support isn't a thing
    WebhookEmbedBuilder builder = new WebhookEmbedBuilder().setAuthor(new WebhookEmbed.EmbedAuthor(author == null ? "Anonymous#0000" : author.getAsTag(), author == null ? null : author.getEffectiveAvatarUrl(), null)).setColor(-21453).addField(new WebhookEmbed.EmbedField(false, "Message Link", "[Jump!](" + messageLink + ")")).setImageUrl(starboard.getString("image"));
    String content = starboard.getString("content");
    if (content != null && !content.isBlank()) {
        builder.addField(new WebhookEmbed.EmbedField(false, "Message", StringUtility.limit(content, MessageEmbed.VALUE_MAX_LENGTH, "[...](" + messageLink + ")")));
    }
    Document webhookData = guildData.get("webhook", MongoDatabase.EMPTY_DOCUMENT);
    try {
        return this.format(messageData.get("message", Document.class), member, channel, emote, stars, nextStars, starboard.getObjectId("_id")).setUsername(premium ? webhookData.get("name", "Sx4 - Starboard") : "Sx4 - Starboard").setAvatarUrl(premium ? webhookData.get("avatar", this.bot.getShardManager().getShardById(0).getSelfUser().getEffectiveAvatarUrl()) : this.bot.getShardManager().getShardById(0).getSelfUser().getEffectiveAvatarUrl()).addEmbeds(builder.build()).build();
    } catch (IllegalArgumentException e) {
        // TODO: can't currently happen but when embed support is added handle this
        return null;
    }
}
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) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder)

Example 7 with ReactionEmote

use of net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote 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 ReactionEmote

use of net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote 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)

Example 9 with ReactionEmote

use of net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote in project Bean by Xirado.

the class MessageReactionRemoveListener method onMessageReactionRemove.

@Override
public void onMessageReactionRemove(@NotNull MessageReactionRemoveEvent e) {
    if (!e.isFromGuild())
        return;
    if (GuildJoinListener.isGuildBanned(e.getGuild().getIdLong()))
        return;
    ReactionEmote reactionemote = e.getReactionEmote();
    String reacted = reactionemote.isEmoji() ? reactionemote.getAsReactionCode() : reactionemote.getEmote().getId();
    GuildData data = GuildManager.getGuildData(e.getGuild());
    data.getReactionRoles().stream().filter(x -> x.getMessageId() == e.getMessageIdLong() && x.getEmote().equals(reacted)).findFirst().ifPresent(reactionRole -> e.getGuild().retrieveMemberById(e.getUserId()).queue((member) -> {
        if (member.getUser().isBot())
            return;
        Role role = e.getGuild().getRoleById(reactionRole.getRoleId());
        if (role != null)
            e.getGuild().removeRoleFromMember(member, role).queue(s -> {
            }, ex -> {
            });
    }, (error) -> {
    }));
}
Also used : GuildManager(at.xirado.bean.data.GuildManager) ReactionEmote(net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote) MessageReactionRemoveAllEvent(net.dv8tion.jda.api.events.message.react.MessageReactionRemoveAllEvent) MessageReactionRemoveEvent(net.dv8tion.jda.api.events.message.react.MessageReactionRemoveEvent) GuildData(at.xirado.bean.data.GuildData) Logger(org.slf4j.Logger) Role(net.dv8tion.jda.api.entities.Role) LoggerFactory(org.slf4j.LoggerFactory) ListenerAdapter(net.dv8tion.jda.api.hooks.ListenerAdapter) NotNull(org.jetbrains.annotations.NotNull) Role(net.dv8tion.jda.api.entities.Role) GuildData(at.xirado.bean.data.GuildData) ReactionEmote(net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote)

Aggregations

ReactionEmote (net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote)9 NotNull (org.jetbrains.annotations.NotNull)6 Document (org.bson.Document)5 MongoWriteException (com.mongodb.MongoWriteException)4 Sx4 (com.sx4.bot.core.Sx4)4 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)4 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)4 List (java.util.List)4 CompletionException (java.util.concurrent.CompletionException)4 WebhookEmbed (club.minnced.discord.webhook.send.WebhookEmbed)3 WebhookEmbedBuilder (club.minnced.discord.webhook.send.WebhookEmbedBuilder)3 WebhookMessage (club.minnced.discord.webhook.send.WebhookMessage)3 WebhookMessageBuilder (club.minnced.discord.webhook.send.WebhookMessageBuilder)3 ErrorCategory (com.mongodb.ErrorCategory)3 com.mongodb.client.model (com.mongodb.client.model)3 Operators (com.sx4.bot.database.mongo.model.Operators)3 Formatter (com.sx4.bot.formatter.Formatter)3 JsonFormatter (com.sx4.bot.formatter.JsonFormatter)3 StarboardManager (com.sx4.bot.managers.StarboardManager)3 MessageUtility (com.sx4.bot.utility.MessageUtility)3