Search in sources :

Example 26 with PagedResult

use of com.sx4.bot.paged.PagedResult 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 27 with PagedResult

use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.

the class PagedHandler method handleMessage.

public void handleMessage(Message message) {
    MessageChannel channel = message.getChannel();
    User author = message.getAuthor();
    PagedResult<?> pagedResult = this.bot.getPagedManager().getPagedResult(channel.getIdLong(), author.getIdLong());
    if (pagedResult == null) {
        return;
    }
    if (author.getIdLong() != pagedResult.getOwnerId()) {
        return;
    }
    String content = message.getContentRaw();
    String contentLower = content.toLowerCase();
    EnumSet<SelectType> selectTypes = pagedResult.getSelect();
    if (this.next.contains(contentLower)) {
        if (pagedResult.getNextPage() != pagedResult.getPage()) {
            pagedResult.nextPage().ensure(channel);
            this.attemptDelete(message);
        }
    } else if (this.previous.contains(contentLower)) {
        if (pagedResult.getPreviousPage() != pagedResult.getPage()) {
            pagedResult.previousPage().ensure(channel);
            this.attemptDelete(message);
        }
    } else if (this.cancel.contains(contentLower)) {
        this.attemptDelete(message);
        pagedResult.delete();
    } else if (selectTypes.contains(SelectType.INDEX) && NumberUtility.isNumberUnsigned(content)) {
        try {
            int index = Integer.parseInt(content);
            if (index > pagedResult.getLowerPageBound() && index <= pagedResult.getHigherPageBound()) {
                pagedResult.select(pagedResult.isIncreasedIndex() ? index - 1 : (pagedResult.getPage() * pagedResult.getPerPage() - pagedResult.getPerPage()) + (index - 1));
                this.attemptDelete(message);
            }
        } catch (NumberFormatException ignored) {
        }
    } else {
        int index = contentLower.lastIndexOf(' ');
        if (index != -1 && this.skip.contains(contentLower.substring(0, index))) {
            try {
                int page = Integer.parseInt(contentLower.substring(index + 1));
                if (page > 0 && page <= pagedResult.getMaxPage() && page != pagedResult.getPage()) {
                    pagedResult.setPage(page).ensure(channel);
                    this.attemptDelete(message);
                    return;
                }
            } catch (NumberFormatException ignored) {
            }
        }
        if (selectTypes.contains(SelectType.OBJECT)) {
            for (int i = pagedResult.getPage() * pagedResult.getPerPage() - pagedResult.getPerPage(); i < (pagedResult.getPage() == pagedResult.getMaxPage() ? pagedResult.getList().size() : pagedResult.getPage() * pagedResult.getPerPage()); i++) {
                if (pagedResult.runSelectablePredicate(content, i)) {
                    pagedResult.select(i);
                    this.attemptDelete(message);
                }
            }
        }
    }
}
Also used : User(net.dv8tion.jda.api.entities.User) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) SelectType(com.sx4.bot.paged.PagedResult.SelectType)

Example 28 with PagedResult

use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.

the class DiscordBotCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "bot", endless = true, nullDefault = true) String query) {
    CompletableFuture<String> future = new CompletableFuture<>();
    if (query == null) {
        future.complete("440996323156819968");
    } else {
        Matcher mentionMatch = SearchUtility.USER_MENTION.matcher(query);
        if (NumberUtility.isNumber(query)) {
            future.complete(query);
        } else if (mentionMatch.matches()) {
            future.complete(mentionMatch.group(1));
        } else if (query.length() <= 32) {
            Request request = new Request.Builder().url("https://top.gg/api/search?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8) + "&type=bot").build();
            event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
                Document data = Document.parse(response.body().string());
                PagedResult<Document> paged = new PagedResult<>(event.getBot(), data.getList("results", Document.class)).setAutoSelect(true).setDisplayFunction(d -> d.getString("name") + " (" + d.getString("id") + ")");
                paged.onSelect(select -> future.complete(select.getSelected().getString("id")));
                paged.execute(event);
            });
        } else {
            event.replyFailure("I could not find that bot").queue();
            return;
        }
    }
    future.whenComplete((id, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        Request request = new Request.Builder().url("https://top.gg/api/bots/" + id).addHeader("Authorization", event.getConfig().getTopGG()).build();
        event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
            if (response.code() == 404) {
                event.replyFailure("I could not find that bot").queue();
                return;
            }
            Document bot = Document.parse(response.body().string());
            String botAvatarUrl = "https://cdn.discordapp.com/avatars/" + bot.getString("id") + "/" + bot.getString("avatar");
            String botInviteUrl = !bot.getString("invite").isEmpty() ? bot.getString("invite") : "https://discord.com/oauth2/authorize?client_id=" + bot.getString("id") + "&scope=bot";
            String guildCount = bot.containsKey("server_count") ? String.format("%,d", bot.getInteger("server_count")) : "N/A";
            String ownerId = bot.getList("owners", String.class).get(0);
            User owner = event.getShardManager().getUserById(ownerId);
            EmbedBuilder embed = new EmbedBuilder().setAuthor(bot.getString("username") + "#" + bot.getString("discriminator"), "https://top.gg/bot/" + bot.getString("id"), botAvatarUrl).setThumbnail(botAvatarUrl).setDescription((bot.getBoolean("certifiedBot") ? "<:certified:438392214545235978> | " : "") + bot.getString("shortdesc")).addField("Guilds", guildCount, true).addField("Prefix", bot.getString("prefix"), true).addField("Library", bot.getString("lib"), true).addField("Approval Date", OffsetDateTime.parse(bot.getString("date")).format(this.formatter), true).addField("Monthly Votes", String.format("%,d :thumbsup:", bot.getInteger("monthlyPoints")), true).addField("Total Votes", String.format("%,d :thumbsup:", bot.getInteger("points")), true).addField("Invite", "**[Invite " + bot.getString("username") + " to your server](" + botInviteUrl + ")**", true);
            if (owner == null) {
                embed.setFooter("Primary Owner ID: " + ownerId, null);
            } else {
                embed.setFooter("Primary Owner: " + owner.getAsTag(), owner.getEffectiveAvatarUrl());
            }
            event.reply(embed.build()).queue();
        });
    });
}
Also used : Document(org.bson.Document) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) NumberUtility(com.sx4.bot.utility.NumberUtility) Permission(net.dv8tion.jda.api.Permission) SearchUtility(com.sx4.bot.utility.SearchUtility) CompletableFuture(java.util.concurrent.CompletableFuture) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) PagedResult(com.sx4.bot.paged.PagedResult) StandardCharsets(java.nio.charset.StandardCharsets) User(net.dv8tion.jda.api.entities.User) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) OffsetDateTime(java.time.OffsetDateTime) Matcher(java.util.regex.Matcher) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) DateTimeFormatter(java.time.format.DateTimeFormatter) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) Argument(com.jockie.bot.core.argument.Argument) User(net.dv8tion.jda.api.entities.User) Matcher(java.util.regex.Matcher) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) Document(org.bson.Document) CompletableFuture(java.util.concurrent.CompletableFuture) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) PagedResult(com.sx4.bot.paged.PagedResult)

Example 29 with PagedResult

use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.

the class FreeGamesCommand method list.

@Command(value = "list", description = "Lists the current free games")
@CommandId(473)
@Examples({ "free games list" })
public void list(Sx4CommandEvent event) {
    List<Document> games = event.getMongo().getAnnouncedGames(Filters.gte("promotion.end", Instant.now().getEpochSecond()), new Document()).into(new ArrayList<>());
    if (games.isEmpty()) {
        event.replyFailure("There are currently no free games").queue();
        return;
    }
    List<FreeGame<?>> freeGames = games.stream().map(FreeGameUtility::getFreeGame).collect(Collectors.toList());
    PagedResult<FreeGame<?>> paged = new PagedResult<>(event.getBot(), freeGames).setSelect().setPerPage(1).setCustomFunction(page -> {
        EmbedBuilder embed = new EmbedBuilder();
        embed.setFooter("Game " + page.getPage() + "/" + page.getMaxPage());
        page.forEach((game, index) -> this.setGameEmbed(embed, game));
        return new MessageBuilder().setEmbeds(embed.build());
    });
    paged.execute(event);
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Document(org.bson.Document) EpicFreeGame(com.sx4.bot.entities.info.EpicFreeGame) FreeGame(com.sx4.bot.entities.info.FreeGame) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 30 with PagedResult

use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.

the class FreeGamesCommand method upcoming.

@Command(value = "upcoming", description = "Lists the free games on Epic Games coming in the future")
@CommandId(482)
@Examples({ "free games upcoming" })
public void upcoming(Sx4CommandEvent event) {
    FreeGameUtility.retrieveUpcomingFreeGames(event.getHttpClient(), freeGames -> {
        if (freeGames.isEmpty()) {
            event.replyFailure("There are currently no upcoming free games").queue();
            return;
        }
        PagedResult<EpicFreeGame> paged = new PagedResult<>(event.getBot(), freeGames).setSelect().setPerPage(1).setCustomFunction(page -> {
            EmbedBuilder embed = new EmbedBuilder();
            embed.setFooter("Game " + page.getPage() + "/" + page.getMaxPage());
            page.forEach((game, index) -> this.setGameEmbed(embed, game));
            return new MessageBuilder().setEmbeds(embed.build());
        });
        paged.execute(event);
    });
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) EpicFreeGame(com.sx4.bot.entities.info.EpicFreeGame) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Aggregations

Sx4Command (com.sx4.bot.core.Sx4Command)54 PagedResult (com.sx4.bot.paged.PagedResult)50 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)43 Document (org.bson.Document)43 Command (com.jockie.bot.core.command.Command)41 CommandId (com.sx4.bot.annotations.command.CommandId)35 Examples (com.sx4.bot.annotations.command.Examples)33 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)32 ModuleCategory (com.sx4.bot.category.ModuleCategory)26 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)26 User (net.dv8tion.jda.api.entities.User)26 Argument (com.jockie.bot.core.argument.Argument)25 Bson (org.bson.conversions.Bson)23 Permission (net.dv8tion.jda.api.Permission)22 BotPermissions (com.sx4.bot.annotations.command.BotPermissions)20 List (java.util.List)19 ArrayList (java.util.ArrayList)18 HttpCallback (com.sx4.bot.http.HttpCallback)15 Request (okhttp3.Request)15 Collectors (java.util.stream.Collectors)13