Search in sources :

Example 1 with PagedResult

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

the class LeaderboardCommand method networth.

@Command(value = "networth", description = "View the leaderboard for the networth of users")
@CommandId(370)
@Examples({ "leaderboard networth", "leaderboard networth --server" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void networth(Sx4CommandEvent event, @Option(value = "server", aliases = { "guild" }, description = "View the leaderboard with a server filter") boolean guild) {
    List<Bson> userPipeline = List.of(Aggregates.project(Projections.computed("total", "$economy.balance")), Aggregates.match(Filters.and(Filters.exists("total"), Filters.ne("total", 0))));
    List<Bson> pipeline = List.of(Aggregates.project(Projections.fields(Projections.computed("_id", "$userId"), Projections.computed("total", Operators.cond(Operators.exists("$item.durability"), Operators.toLong(Operators.multiply(Operators.divide("$item.price", "$item.maxDurability"), "$item.durability")), Operators.multiply("$item.price", "$amount"))))), Aggregates.match(Filters.and(Filters.ne("_id", event.getJDA().getSelfUser().getIdLong()), Filters.ne("amount", 0))), Aggregates.unionWith("users", userPipeline), Aggregates.group("$_id", Accumulators.sum("total", "$total")), Aggregates.sort(Sorts.descending("total")));
    event.getMongo().aggregateItems(pipeline).whenCompleteAsync((documents, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        List<Map.Entry<User, Long>> users = new ArrayList<>();
        AtomicInteger userIndex = new AtomicInteger(-1);
        int i = 0;
        for (Document data : documents) {
            User user = event.getShardManager().getUserById(data.getLong("_id"));
            if (user == null) {
                continue;
            }
            if (!event.getGuild().isMember(user) && guild) {
                continue;
            }
            i++;
            users.add(Map.entry(user, data.getLong("total")));
            if (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<User, Long>> paged = new PagedResult<>(event.getBot(), users).setPerPage(10).setCustomFunction(page -> {
            int rank = userIndex.get();
            EmbedBuilder embed = new EmbedBuilder().setTitle("Networth 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` - $%,d\n", index + 1, MarkdownSanitizer.escape(entry.getKey().getAsTag()), entry.getValue())));
            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) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) 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 2 with PagedResult

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

the class LeaderboardCommand method items.

@Command(value = "items", description = "View the leaderboard for a specific items count of users")
@CommandId(372)
@Examples({ "leaderboard items", "leaderboard items Shoe", "leaderboard items Diamond --server" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void items(Sx4CommandEvent event, @Argument(value = "item", endless = true, nullDefault = true) Item item, @Option(value = "server", aliases = { "guild" }, description = "View the leaderboard with a server filter") boolean guild) {
    Bson filter = Filters.and(Filters.ne("_id", event.getJDA().getSelfUser().getIdLong()), Filters.ne("amount", 0));
    if (item != null) {
        filter = Filters.and(filter, Filters.eq("item.id", item.getId()));
    }
    List<Bson> pipeline = List.of(Aggregates.project(Projections.include("amount", "userId", "item.id")), Aggregates.match(filter), Aggregates.group("$userId", Accumulators.sum("amount", "$amount")), Aggregates.sort(Sorts.descending("amount")));
    event.getMongo().aggregateItems(pipeline).whenCompleteAsync((documents, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        List<Map.Entry<User, Long>> users = new ArrayList<>();
        AtomicInteger userIndex = new AtomicInteger(-1);
        int i = 0;
        for (Document data : documents) {
            User user = event.getShardManager().getUserById(data.getLong("_id"));
            if (user == null) {
                continue;
            }
            if (!event.getGuild().isMember(user) && guild) {
                continue;
            }
            i++;
            users.add(Map.entry(user, data.getLong("amount")));
            if (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<User, Long>> paged = new PagedResult<>(event.getBot(), users).setPerPage(10).setCustomFunction(page -> {
            int rank = userIndex.get();
            EmbedBuilder embed = new EmbedBuilder().setTitle((item == null ? "All Items" : item.getName()) + " 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` - %,d %s\n", index + 1, MarkdownSanitizer.escape(entry.getKey().getAsTag()), entry.getValue(), item == null ? "Item" + (entry.getValue() == 1 ? "" : "s") : item.getName())));
            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) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) 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 3 with PagedResult

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

the class StarboardCommand method top.

@Command(value = "top", aliases = { "list" }, description = "View the top starred messages in the server")
@CommandId(205)
@Examples({ "starboard top" })
public void top(Sx4CommandEvent event) {
    Guild guild = event.getGuild();
    List<Document> starboards = event.getMongo().getStarboards(Filters.and(Filters.eq("guildId", guild.getIdLong()), Filters.ne("count", 0)), Projections.include("count", "channelId", "originalMessageId")).sort(Sorts.descending("count")).into(new ArrayList<>());
    PagedResult<Document> paged = new PagedResult<>(event.getBot(), starboards).setIncreasedIndex(true).setAuthor("Top Starboards", null, guild.getIconUrl()).setDisplayFunction(data -> {
        int count = data.getInteger("count");
        return String.format("[%s](https://discord.com/channels/%d/%d/%d) - **%d** star%s", data.getObjectId("_id").toHexString(), guild.getIdLong(), data.getLong("channelId"), data.getLong("originalMessageId"), count, count == 1 ? "" : "s");
    });
    paged.execute(event);
}
Also used : Guild(net.dv8tion.jda.api.entities.Guild) Document(org.bson.Document) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 4 with PagedResult

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

the class SuggestionCommand method view.

@Command(value = "view", aliases = { "list" }, description = "View a suggestion in the current channel")
@CommandId(87)
@Examples({ "suggestion view 5e45ce6d3688b30ee75201ae", "suggestion view" })
public void view(Sx4CommandEvent event, @Argument(value = "id | message", nullDefault = true, acceptEmpty = true) Or<MessageArgument, ObjectId> argument) {
    Bson filter = Filters.eq("guildId", event.getGuild().getIdLong());
    if (argument != null) {
        filter = Filters.and(filter, argument.hasFirst() ? Filters.eq("messageId", argument.getFirst().getMessageId()) : Filters.eq("_id", argument.getSecond()));
    }
    List<Bson> guildPipeline = List.of(Aggregates.project(Projections.computed("states", Operators.ifNull("$suggestion.states", SuggestionState.getDefaultStates()))), Aggregates.match(Filters.eq("_id", event.getGuild().getIdLong())));
    List<Bson> pipeline = List.of(Aggregates.match(filter), Aggregates.group(null, Accumulators.push("suggestions", Operators.ROOT)), Aggregates.unionWith("guilds", guildPipeline), Aggregates.group(null, Accumulators.max("states", "$states"), Accumulators.max("suggestions", Operators.ifNull("$suggestions", Collections.EMPTY_LIST))));
    event.getMongo().aggregateSuggestions(pipeline).whenComplete((documents, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        Document data = documents.isEmpty() ? MongoDatabase.EMPTY_DOCUMENT : documents.get(0);
        List<Document> suggestions = data.getList("suggestions", Document.class);
        if (suggestions.isEmpty()) {
            event.replyFailure("There are no suggestions in this server").queue();
            return;
        }
        List<Document> states = data.getList("states", Document.class);
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), suggestions).setIncreasedIndex(true).setDisplayFunction(d -> {
            long authorId = d.getLong("authorId");
            User author = event.getShardManager().getUserById(authorId);
            return String.format("`%s` by %s - **%s**", d.getObjectId("_id").toHexString(), author == null ? authorId : author.getAsTag(), d.getString("state"));
        });
        paged.onSelect(select -> {
            Suggestion suggestion = Suggestion.fromData(select.getSelected());
            event.reply(suggestion.getEmbed(event.getShardManager(), suggestion.getFullState(states))).queue();
        });
        paged.execute(event);
    });
}
Also used : Suggestion(com.sx4.bot.entities.management.Suggestion) User(net.dv8tion.jda.api.entities.User) Document(org.bson.Document) PagedResult(com.sx4.bot.paged.PagedResult) Bson(org.bson.conversions.Bson) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 5 with PagedResult

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

the class HelpCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "command | module", endless = true, nullDefault = true) String commandName) {
    boolean embed = !event.isFromGuild() || event.getGuild().getSelfMember().hasPermission(event.getTextChannel(), Permission.MESSAGE_EMBED_LINKS);
    if (commandName == null) {
        List<Sx4Category> categories = Arrays.stream(ModuleCategory.ALL_ARRAY).filter(category -> !category.getCommands(event.isAuthorDeveloper()).isEmpty()).collect(Collectors.toList());
        PagedResult<Sx4Category> paged = new PagedResult<>(event.getBot(), categories).setPerPage(categories.size()).setSelect(SelectType.OBJECT).setSelectablePredicate((content, category) -> category.getName().equalsIgnoreCase(content) || Arrays.stream(category.getAliases()).anyMatch(content::equalsIgnoreCase)).setCustomFunction(page -> {
            MessageBuilder builder = new MessageBuilder();
            EmbedBuilder embedBuilder = new EmbedBuilder();
            embedBuilder.setAuthor("Help", null, event.getSelfUser().getEffectiveAvatarUrl());
            embedBuilder.setFooter(event.getPrefix() + "help <module> or respond below with a name of a module", event.getAuthor().getEffectiveAvatarUrl());
            embedBuilder.setDescription("All commands are put in a set category also known as a module, use `" + event.getPrefix() + "help <module>` on the module of your choice, The bot will then " + "list all the commands in that module. If you need further help feel free to join the [support server](https://discord.gg/PqJNcfB).");
            embedBuilder.addField("Modules", "`" + categories.stream().map(Sx4Category::getName).collect(Collectors.joining("`, `")) + "`", false);
            return builder.setEmbeds(embedBuilder.build());
        });
        paged.onSelect(select -> {
            Sx4Category category = select.getSelected();
            List<Sx4Command> categoryCommands = category.getCommands(event.isAuthorDeveloper()).stream().map(Sx4Command.class::cast).sorted(Comparator.comparing(Sx4Command::getCommandTrigger)).collect(Collectors.toList());
            PagedResult<Sx4Command> categoryPaged = HelpUtility.getCommandsPaged(event.getBot(), categoryCommands).setAuthor(category.getName(), null, event.getAuthor().getEffectiveAvatarUrl());
            categoryPaged.onSelect(categorySelect -> event.reply(HelpUtility.getHelpMessage(categorySelect.getSelected(), embed)).queue());
            categoryPaged.execute(event);
        });
        paged.execute(event);
    } else {
        Sx4Category category = SearchUtility.getModule(commandName);
        List<Sx4Command> commands = SearchUtility.getCommands(event.getCommandListener(), commandName, event.isAuthorDeveloper());
        if (category != null) {
            List<Sx4Command> categoryCommands = category.getCommands(event.isAuthorDeveloper()).stream().map(Sx4Command.class::cast).sorted(Comparator.comparing(Sx4Command::getCommandTrigger)).collect(Collectors.toList());
            PagedResult<Sx4Command> paged = HelpUtility.getCommandsPaged(event.getBot(), categoryCommands).setAuthor(category.getName(), null, event.getAuthor().getEffectiveAvatarUrl());
            paged.onSelect(select -> event.reply(HelpUtility.getHelpMessage(select.getSelected(), embed)).queue());
            paged.execute(event);
        } else if (!commands.isEmpty()) {
            PagedResult<Sx4Command> paged = new PagedResult<>(event.getBot(), commands).setAuthor(commandName, null, event.getAuthor().getEffectiveAvatarUrl()).setAutoSelect(true).setPerPage(15).setSelectablePredicate((content, command) -> command.getCommandTrigger().equals(content)).setDisplayFunction(Sx4Command::getUsage);
            paged.onSelect(select -> event.reply(HelpUtility.getHelpMessage(select.getSelected(), embed)).queue());
            paged.execute(event);
        } else {
            event.replyFailure("I could not find that command/module").queue();
        }
    }
}
Also used : Arrays(java.util.Arrays) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) SearchUtility(com.sx4.bot.utility.SearchUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) PagedResult(com.sx4.bot.paged.PagedResult) Collectors(java.util.stream.Collectors) ModuleCategory(com.sx4.bot.category.ModuleCategory) HelpUtility(com.sx4.bot.utility.HelpUtility) Sx4Category(com.sx4.bot.core.Sx4Category) List(java.util.List) SelectType(com.sx4.bot.paged.PagedResult.SelectType) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Comparator(java.util.Comparator) Argument(com.jockie.bot.core.argument.Argument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Sx4Command(com.sx4.bot.core.Sx4Command) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Sx4Category(com.sx4.bot.core.Sx4Category) PagedResult(com.sx4.bot.paged.PagedResult)

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