Search in sources :

Example 6 with Premium

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);
    });
}
Also used : HolderType(com.sx4.bot.entities.settings.HolderType) Document(org.bson.Document) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) FormatterVariable(com.sx4.bot.formatter.function.FormatterVariable) MarkdownSanitizer(net.dv8tion.jda.api.utils.MarkdownSanitizer) Command(com.jockie.bot.core.command.Command) MongoWriteException(com.mongodb.MongoWriteException) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) ModAction(com.sx4.bot.entities.mod.action.ModAction) CompletableFuture(java.util.concurrent.CompletableFuture) TimedArgument(com.sx4.bot.entities.argument.TimedArgument) PagedResult(com.sx4.bot.paged.PagedResult) ArrayList(java.util.ArrayList) MatchAction(com.sx4.bot.entities.mod.auto.MatchAction) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) Duration(java.time.Duration) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) com.mongodb.client.model(com.mongodb.client.model) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Operators(com.sx4.bot.database.mongo.model.Operators) Sx4Command(com.sx4.bot.core.Sx4Command) WhitelistType(com.sx4.bot.entities.management.WhitelistType) CompletionException(java.util.concurrent.CompletionException) FormatterManager(com.sx4.bot.formatter.FormatterManager) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) Examples(com.sx4.bot.annotations.command.Examples) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) StringJoiner(java.util.StringJoiner) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) RegexType(com.sx4.bot.entities.mod.auto.RegexType) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) ErrorCategory(com.mongodb.ErrorCategory) MongoWriteException(com.mongodb.MongoWriteException) CompletionException(java.util.concurrent.CompletionException) Document(org.bson.Document) Bson(org.bson.conversions.Bson) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 7 with Premium

use of com.sx4.bot.annotations.command.Premium in project Sx4 by sx4-discord-bot.

the class PremiumCommand method perks.

@Command(value = "perks", description = "View the perks you get when you or a server has premium")
@CommandId(462)
@Examples({ "premium perks" })
public void perks(Sx4CommandEvent event) {
    List<String> userPerks = event.getConfig().getPremiumUserPerks(), serverPerks = event.getConfig().getPremiumServerPerks();
    EmbedBuilder embed = new EmbedBuilder().setAuthor("Premium Perks", null, event.getSelfUser().getEffectiveAvatarUrl()).addField("Personal Perks", "• " + String.join("\n• ", userPerks), false).addField("Server Perks", "• " + String.join("\n• ", serverPerks), false);
    event.reply(embed.build()).queue();
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 8 with Premium

use of com.sx4.bot.annotations.command.Premium in project Sx4 by sx4-discord-bot.

the class PremiumCommand method check.

@Command(value = "check", description = "Checks when the current premium in the server expires")
@CommandId(178)
@Examples({ "premium check" })
public void check(Sx4CommandEvent event) {
    long endAt = event.getMongo().getGuildById(event.getGuild().getIdLong(), Projections.include("premium.endAt")).getEmbedded(List.of("premium", "endAt"), 0L);
    if (endAt == 0) {
        event.replyFailure("This server currently doesn't have premium, you can give it premium with credit <https://patreon.com/Sx4>").queue();
        return;
    }
    OffsetDateTime expire = OffsetDateTime.ofInstant(Instant.ofEpochSecond(endAt), ZoneOffset.UTC);
    if (expire.isBefore(OffsetDateTime.now(ZoneOffset.UTC))) {
        event.replyFailure("Premium for this server expired on the **" + String.format(expire.format(this.formatter), NumberUtility.getSuffix(expire.getDayOfMonth())) + "**, you can renew it with more credit <https://patreon.com/Sx4>").queue();
        return;
    }
    event.replyFormat("Premium for this server will expire on the **" + String.format(expire.format(this.formatter), NumberUtility.getSuffix(expire.getDayOfMonth())) + "**").queue();
}
Also used : OffsetDateTime(java.time.OffsetDateTime) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 9 with Premium

use of com.sx4.bot.annotations.command.Premium in project Sx4 by sx4-discord-bot.

the class PremiumCommand method leaderboard.

@Command(value = "leaderboard", aliases = { "lb" }, description = "Leaderboard for Sx4s biggest donors")
@CommandId(446)
@Redirects({ "lb premium", "leaderboard premium" })
@Examples({ "premium leaderboard" })
public void leaderboard(Sx4CommandEvent event, @Option(value = "server", aliases = { "guild" }, description = "Filters the results to only people in the current server") boolean guild) {
    List<Bson> pipeline = List.of(Aggregates.project(Projections.computed("total", "$premium.total")), Aggregates.match(Filters.and(Filters.exists("total"), Filters.ne("total", 0))), Aggregates.sort(Sorts.descending("total")));
    event.getMongoMain().aggregateUsers(pipeline).whenCompleteAsync((documents, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        List<Map.Entry<String, Integer>> users = new ArrayList<>();
        AtomicInteger userIndex = new AtomicInteger(-1);
        int i = 0;
        for (Document data : documents) {
            long id = data.getLong("_id");
            User user = event.getShardManager().getUserById(data.getLong("_id"));
            if ((user == null || !event.getGuild().isMember(user)) && guild) {
                continue;
            }
            i++;
            users.add(Map.entry(user == null ? "Anonymous#0000 (" + id + ")" : MarkdownSanitizer.escape(user.getAsTag()), data.getInteger("total")));
            if (user != null && user.getIdLong() == event.getAuthor().getIdLong()) {
                userIndex.set(i);
            }
        }
        if (users.isEmpty()) {
            event.replyFailure("There are no users which fit into this leaderboard").queue();
            return;
        }
        PagedResult<Map.Entry<String, Integer>> paged = new PagedResult<>(event.getBot(), users).setPerPage(10).setCustomFunction(page -> {
            int rank = userIndex.get();
            EmbedBuilder embed = new EmbedBuilder().setTitle("Donors Leaderboard").setFooter(event.getAuthor().getName() + "'s Rank: " + (rank == -1 ? "N/A" : NumberUtility.getSuffixed(rank)) + " | Page " + page.getPage() + "/" + page.getMaxPage(), event.getAuthor().getEffectiveAvatarUrl());
            page.forEach((entry, index) -> embed.appendDescription(String.format("%d. `%s` - $%,.2f\n", index + 1, entry.getKey(), entry.getValue() / 100D)));
            return new MessageBuilder().setEmbeds(embed.build());
        });
        paged.execute(event);
    });
}
Also used : User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Document(org.bson.Document) Bson(org.bson.conversions.Bson) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PagedResult(com.sx4.bot.paged.PagedResult) Redirects(com.sx4.bot.annotations.command.Redirects) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 10 with Premium

use of com.sx4.bot.annotations.command.Premium in project Sx4 by sx4-discord-bot.

the class SuggestionManager method sendSuggestion.

public CompletableFuture<ReadonlyMessage> sendSuggestion(BaseGuildMessageChannel channel, Document webhookData, boolean premium, WebhookEmbed embed) {
    User selfUser = channel.getJDA().getSelfUser();
    WebhookMessage message = new WebhookMessageBuilder().setAvatarUrl(webhookData.get("avatar", selfUser.getEffectiveAvatarUrl())).setUsername(webhookData.get("name", "Sx4 - Suggestions")).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);
    });
}
Also used : WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) Document(org.bson.Document) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) BotPermissionException(com.sx4.bot.exceptions.mod.BotPermissionException) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) Updates(com.mongodb.client.model.Updates) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) CompletionException(java.util.concurrent.CompletionException) Executors(java.util.concurrent.Executors) HttpException(club.minnced.discord.webhook.exception.HttpException) WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) Bson(org.bson.conversions.Bson) OkHttpClient(okhttp3.OkHttpClient) Sx4(com.sx4.bot.core.Sx4) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) Map(java.util.Map) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage) WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) CompletionException(java.util.concurrent.CompletionException) HttpException(club.minnced.discord.webhook.exception.HttpException) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage)

Aggregations

Document (org.bson.Document)26 Sx4Command (com.sx4.bot.core.Sx4Command)23 Command (com.jockie.bot.core.command.Command)22 Bson (org.bson.conversions.Bson)22 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)17 CompletableFuture (java.util.concurrent.CompletableFuture)17 CompletionException (java.util.concurrent.CompletionException)17 com.mongodb.client.model (com.mongodb.client.model)16 Operators (com.sx4.bot.database.mongo.model.Operators)16 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)16 Permission (net.dv8tion.jda.api.Permission)16 ErrorCategory (com.mongodb.ErrorCategory)13 MongoWriteException (com.mongodb.MongoWriteException)13 WebhookEmbed (club.minnced.discord.webhook.send.WebhookEmbed)12 WebhookMessage (club.minnced.discord.webhook.send.WebhookMessage)12 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)12 BaseGuildMessageChannel (net.dv8tion.jda.api.entities.BaseGuildMessageChannel)12 WebhookMessageBuilder (club.minnced.discord.webhook.send.WebhookMessageBuilder)11 Sx4 (com.sx4.bot.core.Sx4)11 ErrorResponseException (net.dv8tion.jda.api.exceptions.ErrorResponseException)11