use of com.sx4.bot.annotations.command.Premium in project Sx4 by sx4-discord-bot.
the class LoggerCommand method toggle.
@Command(value = "toggle", aliases = { "enable", "disable" }, description = "Toggles the state of a logger")
@CommandId(56)
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@Examples({ "logger toggle #logs", "logger toggle" })
public void toggle(Sx4CommandEvent event, @Argument(value = "channel", endless = true, nullDefault = true) TextChannel channel) {
TextChannel effectiveChannel = channel == null ? event.getTextChannel() : channel;
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", event.getGuild().getIdLong())));
List<Bson> pipeline = List.of(Aggregates.match(Filters.and(Filters.eq("guildId", event.getGuild().getIdLong()), Filters.exists("enabled", false))), Aggregates.project(Projections.include("channelId")), Aggregates.group(null, Accumulators.push("loggers", Operators.ROOT)), Aggregates.unionWith("guilds", guildPipeline), Aggregates.group(null, Accumulators.max("loggers", "$loggers"), Accumulators.max("premium", "$premium")), Aggregates.project(Projections.fields(Projections.computed("premium", Operators.ifNull("$premium", false)), Projections.computed("count", Operators.size(Operators.ifNull("$loggers", Collections.EMPTY_LIST))), Projections.computed("disabled", Operators.isEmpty(Operators.filter(Operators.ifNull("$loggers", Collections.EMPTY_LIST), Operators.eq("$$this.channelId", effectiveChannel.getIdLong())))))));
event.getMongo().aggregateLoggers(pipeline).thenCompose(documents -> {
Document data = documents.isEmpty() ? null : documents.get(0);
boolean disabled = data == null || data.getBoolean("disabled");
int count = data == null ? 0 : data.getInteger("count");
if (data != null && disabled && count >= 3 && !data.getBoolean("premium")) {
throw new IllegalArgumentException("You need to have Sx4 premium to have more than 3 enabled loggers, you can get premium at <https://www.patreon.com/Sx4>");
}
if (count >= 25) {
throw new IllegalArgumentException("You can not have any more than 25 enabled loggers");
}
List<Bson> update = List.of(Operators.set("enabled", Operators.cond(Operators.exists("$enabled"), Operators.REMOVE, false)));
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER).projection(Projections.include("enabled"));
return event.getMongo().findAndUpdateLogger(Filters.eq("channelId", effectiveChannel.getIdLong()), update, options);
}).whenComplete((data, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof IllegalArgumentException) {
event.replyFailure(cause.getMessage()).queue();
return;
}
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
if (data == null) {
event.replyFailure("There is not a logger in that channel").queue();
return;
}
event.replySuccess("The logger in " + effectiveChannel.getAsMention() + " is now **" + (data.get("enabled", true) ? "enabled" : "disabled") + "**").queue();
});
}
use of com.sx4.bot.annotations.command.Premium in project Sx4 by sx4-discord-bot.
the class FreeGameManager method sendFreeGameNotifications.
public CompletableFuture<List<ReadonlyMessage>> sendFreeGameNotifications(List<? extends FreeGame<?>> games) {
games.forEach(this::addAnnouncedGame);
List<Document> gameData = games.stream().map(FreeGame::toData).collect(Collectors.toList());
if (!gameData.isEmpty()) {
this.bot.getMongo().insertManyAnnouncedGames(gameData).whenComplete(MongoDatabase.exceptionally());
}
List<Bson> guildPipeline = List.of(Aggregates.match(Operators.expr(Operators.eq("$_id", "$$guildId"))), Aggregates.project(Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L)))));
List<Bson> pipeline = List.of(Aggregates.lookup("guilds", List.of(new Variable<>("guildId", "$guildId")), guildPipeline, "premium"), Aggregates.addFields(new Field<>("premium", Operators.cond(Operators.isEmpty("$premium"), false, Operators.get(Operators.arrayElemAt("$premium", 0), "premium")))));
return this.bot.getMongo().aggregateFreeGameChannels(pipeline).thenComposeAsync(documents -> {
List<WriteModel<Document>> bulkData = new ArrayList<>();
List<CompletableFuture<List<ReadonlyMessage>>> futures = new ArrayList<>();
for (Document data : documents) {
if (!data.getBoolean("enabled", true)) {
continue;
}
TextChannel channel = this.bot.getShardManager().getTextChannelById(data.getLong("channelId"));
if (channel == null) {
continue;
}
String avatar = channel.getJDA().getSelfUser().getEffectiveAvatarUrl();
boolean premium = data.getBoolean("premium");
Document webhookData = data.get("webhook", MongoDatabase.EMPTY_DOCUMENT);
long platforms = data.get("platforms", FreeGameType.ALL);
List<WebhookMessage> messages = new ArrayList<>();
for (FreeGame<?> game : games) {
long raw = game.getType().getRaw();
if ((platforms & raw) != raw) {
continue;
}
Formatter<Document> formatter = new JsonFormatter(data.get("message", FreeGameManager.DEFAULT_MESSAGE)).addVariable("game", game);
WebhookMessage message;
try {
message = MessageUtility.fromJson(formatter.parse()).setAvatarUrl(premium ? webhookData.get("avatar", avatar) : avatar).setUsername(premium ? webhookData.get("name", "Sx4 - Free Games") : "Sx4 - Free Games").build();
} catch (IllegalArgumentException e) {
bulkData.add(new UpdateOneModel<>(Filters.eq("_id", data.getObjectId("_id")), Updates.unset("message")));
continue;
}
messages.add(message);
}
if (!messages.isEmpty()) {
futures.add(this.sendFreeGameNotificationMessages(channel, webhookData, messages));
}
}
if (!bulkData.isEmpty()) {
this.bot.getMongo().bulkWriteFreeGameChannels(bulkData).whenComplete(MongoDatabase.exceptionally());
}
return FutureUtility.allOf(futures).thenApply(list -> list.stream().flatMap(List::stream).collect(Collectors.toList()));
});
}
use of com.sx4.bot.annotations.command.Premium in project Sx4 by sx4-discord-bot.
the class ModLogManager method sendModLog.
public CompletableFuture<ReadonlyMessage> sendModLog(TextChannel channel, Document webhookData, WebhookEmbed embed, boolean premium) {
User selfUser = channel.getJDA().getSelfUser();
WebhookMessage message = new WebhookMessageBuilder().setAvatarUrl(premium ? webhookData.get("avatar", selfUser.getEffectiveAvatarUrl()) : selfUser.getEffectiveAvatarUrl()).setUsername(premium ? webhookData.get("name", "Sx4 - Mod Logs") : "Sx4 - Mod Logs").addEmbeds(embed).build();
WebhookClient webhook;
if (this.webhooks.containsKey(channel.getIdLong())) {
webhook = this.webhooks.get(channel.getIdLong());
} else if (!webhookData.containsKey("id")) {
return this.createWebhook(channel, message);
} else {
webhook = new WebhookClient(webhookData.getLong("id"), webhookData.getString("token"), this.executor, this.client);
this.webhooks.put(channel.getIdLong(), webhook);
}
return webhook.send(message).thenApply(webhookMessage -> new ReadonlyMessage(webhookMessage, webhook.getId(), webhook.getToken())).exceptionallyCompose(exception -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof HttpException && ((HttpException) cause).getCode() == 404) {
this.webhooks.remove(channel.getIdLong());
return this.createWebhook(channel, message);
}
return CompletableFuture.failedFuture(exception);
});
}
use of com.sx4.bot.annotations.command.Premium in project Sx4 by sx4-discord-bot.
the class AntiRegexCommand method add.
@Command(value = "add", description = "Add a custom regex to be checked on every message")
@CommandId(125)
@Examples({ "anti regex add [0-9]+", "anti regex add https://discord\\.com/channels/([0-9]+)/([0-9]+)/?" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void add(Sx4CommandEvent event, @Argument(value = "regex", endless = true) Pattern pattern) {
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", event.getGuild().getIdLong())));
List<Bson> pipeline = List.of(Aggregates.match(Filters.and(Filters.eq("guildId", event.getGuild().getIdLong()), Filters.exists("enabled", false), Filters.eq("type", RegexType.REGEX.getId()))), Aggregates.group(null, Accumulators.sum("count", 1)), Aggregates.limit(10), Aggregates.unionWith("guilds", guildPipeline), Aggregates.group(null, Accumulators.max("count", "$count"), Accumulators.max("premium", "$premium")), Aggregates.project(Projections.fields(Projections.computed("premium", Operators.ifNull("$premium", false)), Projections.computed("count", Operators.ifNull("$count", 0)))));
event.getMongo().aggregateRegexes(pipeline).thenCompose(documents -> {
Document counter = documents.isEmpty() ? null : documents.get(0);
int count = counter == null ? 0 : counter.getInteger("count");
if (count >= 3 && !counter.getBoolean("premium")) {
throw new IllegalArgumentException("You need to have Sx4 premium to have more than 3 enabled anti regexes, you can get premium at <https://www.patreon.com/Sx4>");
}
if (count == 10) {
throw new IllegalArgumentException("You cannot have any more than 10 anti regexes");
}
Document patternData = new Document("guildId", event.getGuild().getIdLong()).append("type", RegexType.REGEX.getId()).append("pattern", pattern.pattern());
return event.getMongo().insertRegex(patternData);
}).whenComplete((result, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
event.replyFailure("You already have that anti regex setup in this server").queue();
return;
} else if (cause instanceof IllegalArgumentException) {
event.replyFailure(cause.getMessage()).queue();
return;
}
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.replySuccess("The regex `" + result.getInsertedId().asObjectId().getValue().toHexString() + "` is now active").queue();
});
}
use of com.sx4.bot.annotations.command.Premium in project Sx4 by sx4-discord-bot.
the class AntiRegexCommand method add.
@Command(value = "add", description = "Add a regex from `anti regex template list` to be checked on every message")
@CommandId(106)
@Examples({ "anti regex add 5f023782ef9eba03390a740c" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void add(Sx4CommandEvent event, @Argument(value = "id") ObjectId id) {
Document regex = event.getMongo().getRegexTemplateById(id, Projections.include("pattern", "title", "type"));
if (regex == null) {
event.replyFailure("I could not find that regex template").queue();
return;
}
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", event.getGuild().getIdLong())));
List<Bson> pipeline = List.of(Aggregates.match(Filters.and(Filters.eq("guildId", event.getGuild().getIdLong()), Filters.exists("enabled", false), Filters.eq("type", RegexType.REGEX.getId()))), Aggregates.group(null, Accumulators.sum("count", 1)), Aggregates.limit(10), Aggregates.unionWith("guilds", guildPipeline), Aggregates.group(null, Accumulators.max("count", "$count"), Accumulators.max("premium", "$premium")), Aggregates.project(Projections.fields(Projections.computed("premium", Operators.ifNull("$premium", false)), Projections.computed("count", Operators.ifNull("$count", 0)))));
event.getMongo().aggregateRegexes(pipeline).thenCompose(documents -> {
Document counter = documents.isEmpty() ? null : documents.get(0);
int count = counter == null ? 0 : counter.getInteger("count");
if (count >= 3 && !counter.getBoolean("premium")) {
throw new IllegalArgumentException("You need to have Sx4 premium to have more than 3 enabled anti regexes, you can get premium at <https://www.patreon.com/Sx4>");
}
if (count == 10) {
throw new IllegalArgumentException("You cannot have any more than 10 anti regexes");
}
Document pattern = new Document("regexId", id).append("guildId", event.getGuild().getIdLong()).append("type", regex.getInteger("type", RegexType.REGEX.getId())).append("pattern", regex.getString("pattern"));
return event.getMongo().insertRegex(pattern);
}).thenCompose(result -> {
event.replySuccess("The regex `" + result.getInsertedId().asObjectId().getValue().toHexString() + "` is now active").queue();
return event.getMongo().updateRegexTemplateById(id, Updates.inc("uses", 1L));
}).whenComplete((result, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
event.replyFailure("You already have that anti regex setup in this server").queue();
return;
} else if (cause instanceof IllegalArgumentException) {
event.replyFailure(cause.getMessage()).queue();
return;
}
ExceptionUtility.sendExceptionally(event, exception);
});
}
Aggregations