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();
}
});
});
});
});
}
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());
}
});
});
});
}
Aggregations