Search in sources :

Example 51 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class AntiRegexHandler method handle.

public void handle(Message message) {
    if (!message.isFromGuild()) {
        return;
    }
    Member member = message.getMember();
    if (member == null) {
        return;
    }
    User user = member.getUser();
    if (user.isBot()) {
        return;
    }
    Guild guild = message.getGuild();
    Member selfMember = guild.getSelfMember();
    GuildMessageChannel messageChannel = message.getGuildChannel();
    long guildId = guild.getIdLong(), userId = member.getIdLong(), channelId = (messageChannel instanceof ThreadChannel ? ((ThreadChannel) messageChannel).getParentChannel() : messageChannel).getIdLong();
    Category parent = messageChannel instanceof ICategorizableChannel ? ((ICategorizableChannel) messageChannel).getParentCategory() : null;
    List<Role> roles = member.getRoles();
    String content = message.getContentRaw();
    List<Bson> guildPipeline = List.of(Aggregates.project(Projections.fields(Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L))), Projections.computed("guildId", "$_id"))), Aggregates.match(Filters.eq("guildId", guild.getIdLong())));
    List<Bson> pipeline = List.of(Aggregates.match(Filters.and(Filters.eq("guildId", guild.getIdLong()), Filters.exists("enabled", false))), Aggregates.group(null, Accumulators.push("regexes", Operators.ROOT)), Aggregates.unionWith("guilds", guildPipeline), Aggregates.group(null, Accumulators.max("premium", "$premium"), Accumulators.max("regexes", "$regexes")), Aggregates.project(Projections.computed("regexes", Operators.let(new Document("regexes", Operators.ifNull("$regexes", Collections.EMPTY_LIST)), Operators.cond(Operators.ifNull("$premium", false), "$$regexes", Operators.concatArrays(Operators.filter("$$regexes", Operators.ne("$$this.type", RegexType.REGEX.getId())), Operators.slice(Operators.filter("$$regexes", Operators.eq("$$this.type", RegexType.REGEX.getId())), 0, 3)))))));
    this.bot.getMongo().aggregateRegexes(pipeline).whenComplete((documents, exception) -> {
        if (documents.isEmpty()) {
            return;
        }
        Document data = documents.get(0);
        this.executor.submit(() -> {
            List<CompletableFuture<Document>> matches = new ArrayList<>();
            Regexes: for (Document regex : data.getList("regexes", Document.class)) {
                if (member.hasPermission(Permission.ADMINISTRATOR) && regex.getBoolean("admin", true)) {
                    continue;
                }
                List<Document> channels = regex.getList("whitelist", Document.class, Collections.emptyList());
                Document channel = channels.stream().filter(d -> (d.getInteger("type") == WhitelistType.CHANNEL.getId() && d.getLong("id") == channelId) || (d.getInteger("type") == WhitelistType.CATEGORY.getId() && parent != null && d.getLong("id") == parent.getIdLong())).min(Comparator.comparingInt(d -> d.getInteger("type", 0))).orElse(MongoDatabase.EMPTY_DOCUMENT);
                List<Document> holders = channel.getList("holders", Document.class, Collections.emptyList());
                for (Document holder : holders) {
                    long holderId = holder.getLong("id");
                    int type = holder.getInteger("type");
                    if (type == HolderType.USER.getType() && userId == holderId) {
                        continue Regexes;
                    } else if (type == HolderType.ROLE.getType() && (guildId == holderId || roles.stream().anyMatch(role -> role.getIdLong() == holderId))) {
                        continue Regexes;
                    }
                }
                RegexType type = RegexType.fromId(regex.getInteger("type"));
                Pattern pattern = type == RegexType.REGEX ? Pattern.compile(regex.getString("pattern")) : this.invitePattern;
                Matcher matcher;
                try {
                    matcher = this.executor.submit(() -> pattern.matcher(content)).get(2000, TimeUnit.MILLISECONDS);
                } catch (TimeoutException | InterruptedException | ExecutionException e) {
                    continue;
                }
                Set<String> codes = new HashSet<>();
                int matchCount = 0, totalCount = 0;
                while (matcher.find()) {
                    List<Document> groups = channel.getList("groups", Document.class, Collections.emptyList());
                    for (Document group : groups) {
                        List<String> strings = group.getList("strings", String.class, Collections.emptyList());
                        String match = matcher.group(group.getInteger("group"));
                        if (match != null && strings.contains(match)) {
                            matchCount++;
                        }
                    }
                    if (type == RegexType.INVITE) {
                        codes.add(matcher.group(1));
                    }
                    totalCount++;
                }
                if (matchCount == totalCount) {
                    continue;
                }
                CompletableFuture<Document> future;
                if (type == RegexType.INVITE) {
                    List<CompletableFuture<Invite>> futures = codes.stream().map(code -> Invite.resolve(message.getJDA(), code, true).submit()).collect(Collectors.toList());
                    List<Long> guilds = channel.getList("guilds", Long.class, Collections.emptyList());
                    future = FutureUtility.anyOf(futures, invite -> {
                        Invite.Guild inviteGuild = invite.getGuild();
                        return inviteGuild == null || (!guilds.contains(inviteGuild.getIdLong()) && inviteGuild.getIdLong() != guildId);
                    }).thenApply(invite -> invite == null ? null : regex);
                } else {
                    future = CompletableFuture.completedFuture(regex);
                }
                matches.add(future);
            }
            FutureUtility.anyOf(matches, Objects::nonNull).thenAccept(regex -> {
                if (regex == null) {
                    return;
                }
                ObjectId id = regex.getObjectId("_id");
                RegexType type = RegexType.fromId(regex.getInteger("type"));
                Document match = regex.get("match", MongoDatabase.EMPTY_DOCUMENT);
                long matchAction = match.get("action", MatchAction.ALL);
                Document mod = regex.get("mod", MongoDatabase.EMPTY_DOCUMENT);
                Document actionData = mod.get("action", Document.class);
                Action action = actionData == null ? null : Action.fromData(actionData);
                Document attempts = regex.get("attempts", MongoDatabase.EMPTY_DOCUMENT);
                int maxAttempts = attempts.get("amount", 3);
                if ((matchAction & MatchAction.DELETE_MESSAGE.getRaw()) == MatchAction.DELETE_MESSAGE.getRaw() && selfMember.hasPermission(messageChannel, Permission.MESSAGE_MANAGE)) {
                    message.delete().queue();
                }
                Document reset = attempts.get("reset", Document.class);
                List<Bson> update = List.of(Operators.set("attempts", Operators.let(new Document("attempts", Operators.ifNull("$attempts", 0)), Operators.cond(Operators.exists("$reset"), Operators.max(1, Operators.add(1, Operators.subtract("$$attempts", Operators.multiply(Operators.toInt(Operators.floor(Operators.divide(Operators.subtract(Operators.nowEpochSecond(), "$lastAttempt"), "$reset.after"))), "$reset.amount")))), Operators.add("$$attempts", 1)))), Operators.set("lastAttempt", Operators.nowEpochSecond()), Operators.setOnInsert("guildId", guildId), reset == null ? Operators.unset("reset") : Operators.set("reset", reset));
                Bson filter = Filters.and(Filters.eq("userId", userId), Filters.eq("regexId", id));
                FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().upsert(true).projection(Projections.include("attempts")).returnDocument(ReturnDocument.AFTER);
                this.bot.getMongo().findAndUpdateRegexAttempt(filter, update, options).whenComplete((attemptsData, attemptsException) -> {
                    if (ExceptionUtility.sendErrorMessage(attemptsException)) {
                        return;
                    }
                    int currentAttempts = attemptsData.getInteger("attempts", 0);
                    String matchMessage = this.format(match.get("message", type.getDefaultMatchMessage()), user, messageChannel, id, currentAttempts, maxAttempts, action);
                    String modMessage = this.format(mod.get("message", type.getDefaultModMessage()), user, messageChannel, id, currentAttempts, maxAttempts, action);
                    boolean send = (matchAction & MatchAction.SEND_MESSAGE.getRaw()) == MatchAction.SEND_MESSAGE.getRaw() && selfMember.hasPermission(messageChannel, Permission.MESSAGE_SEND);
                    if (action != null && currentAttempts == maxAttempts) {
                        Reason reason = new Reason(String.format("Sent a message which matched regex `%s` %d time%s", id.toHexString(), maxAttempts, maxAttempts == 1 ? "" : "s"));
                        ModUtility.performAction(this.bot, action, member, selfMember, reason).thenCompose(result -> {
                            if (send) {
                                messageChannel.sendMessage(modMessage).allowedMentions(EnumSet.allOf(Message.MentionType.class)).queue();
                            }
                            return this.bot.getMongo().deleteRegexAttempt(Filters.and(Filters.eq("userId", userId), Filters.eq("regexId", id)));
                        }).whenComplete((result, modException) -> {
                            Throwable cause = modException instanceof CompletionException ? modException.getCause() : modException;
                            if (cause instanceof ModException) {
                                messageChannel.sendMessage(modException.getMessage() + " " + this.bot.getConfig().getFailureEmote()).queue();
                                return;
                            }
                            ExceptionUtility.sendExceptionally(messageChannel, modException);
                        });
                        return;
                    }
                    if (send) {
                        messageChannel.sendMessage(matchMessage).allowedMentions(EnumSet.allOf(Message.MentionType.class)).queue();
                    }
                });
            });
        });
    });
}
Also used : HolderType(com.sx4.bot.entities.settings.HolderType) Document(org.bson.Document) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) java.util(java.util) ModException(com.sx4.bot.exceptions.mod.ModException) Permission(net.dv8tion.jda.api.Permission) MessageUpdateEvent(net.dv8tion.jda.api.events.message.MessageUpdateEvent) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) MatchAction(com.sx4.bot.entities.mod.auto.MatchAction) Bson(org.bson.conversions.Bson) Matcher(java.util.regex.Matcher) Sx4(com.sx4.bot.core.Sx4) Reason(com.sx4.bot.entities.mod.Reason) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) com.mongodb.client.model(com.mongodb.client.model) FutureUtility(com.sx4.bot.utility.FutureUtility) Action(com.sx4.bot.entities.mod.action.Action) Operators(com.sx4.bot.database.mongo.model.Operators) java.util.concurrent(java.util.concurrent) ModUtility(com.sx4.bot.utility.ModUtility) WhitelistType(com.sx4.bot.entities.management.WhitelistType) Collectors(java.util.stream.Collectors) EventListener(net.dv8tion.jda.api.hooks.EventListener) StringFormatter(com.sx4.bot.formatter.StringFormatter) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) RegexType(com.sx4.bot.entities.mod.auto.RegexType) Pattern(java.util.regex.Pattern) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) NotNull(org.jetbrains.annotations.NotNull) RegexType(com.sx4.bot.entities.mod.auto.RegexType) MatchAction(com.sx4.bot.entities.mod.auto.MatchAction) Action(com.sx4.bot.entities.mod.action.Action) Matcher(java.util.regex.Matcher) ModException(com.sx4.bot.exceptions.mod.ModException) Document(org.bson.Document) Reason(com.sx4.bot.entities.mod.Reason) Bson(org.bson.conversions.Bson) Pattern(java.util.regex.Pattern) ObjectId(org.bson.types.ObjectId)

Example 52 with UserId

use of com.sx4.bot.annotations.argument.UserId 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)

Aggregations

Document (org.bson.Document)46 Bson (org.bson.conversions.Bson)44 Sx4Command (com.sx4.bot.core.Sx4Command)36 Command (com.jockie.bot.core.command.Command)28 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)26 User (net.dv8tion.jda.api.entities.User)26 CommandId (com.sx4.bot.annotations.command.CommandId)25 Examples (com.sx4.bot.annotations.command.Examples)23 Operators (com.sx4.bot.database.mongo.model.Operators)23 List (java.util.List)21 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)20 Permission (net.dv8tion.jda.api.Permission)20 Member (net.dv8tion.jda.api.entities.Member)20 ModuleCategory (com.sx4.bot.category.ModuleCategory)18 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)18 PagedResult (com.sx4.bot.paged.PagedResult)14 Argument (com.jockie.bot.core.argument.Argument)13 com.mongodb.client.model (com.mongodb.client.model)13 ArrayList (java.util.ArrayList)13 BotPermissions (com.sx4.bot.annotations.command.BotPermissions)12