Search in sources :

Example 1 with Argument

use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.

the class AxeCommand method upgrade.

@Command(value = "upgrade", description = "Upgrade your axe by a certain attribute")
@CommandId(429)
@Examples({ "axe upgrade multiplier", "axe upgrade durability 5" })
public void upgrade(Sx4CommandEvent event, @Argument(value = "upgrade") Upgrade upgrade, @Argument(value = "upgrades") @DefaultNumber(1) @Limit(min = 1, max = 100) int upgrades) {
    if (!upgrade.containsType(ItemType.AXE)) {
        event.replyFailure("You can not use that upgrade on a axe").queue();
        return;
    }
    event.getMongo().withTransaction(session -> {
        Document data = event.getMongo().getItems().find(session, Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.type", ItemType.AXE.getId()))).first();
        if (data == null) {
            event.replyFailure("You do not have a axe").queue();
            session.abortTransaction();
            return null;
        }
        Document item = data.get("item", Document.class);
        Axe defaultAxe = event.getBot().getEconomyManager().getItemById(item.getInteger("id"), Axe.class);
        Axe axe = new Axe(item, defaultAxe);
        int currentUpgrades = axe.getUpgrades();
        long price = 0;
        for (int i = 0; i < upgrades; i++) {
            price += Math.round(0.015D * defaultAxe.getPrice() * currentUpgrades++ + 0.025D * defaultAxe.getPrice());
        }
        UpdateResult result = event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getAuthor().getIdLong()), List.of(EconomyUtility.decreaseBalanceUpdate(price)));
        if (result.getModifiedCount() == 0) {
            event.replyFormat("You do not have **$%,d** %s", price, event.getConfig().getFailureEmote()).queue();
            session.abortTransaction();
            return null;
        }
        List<Bson> update = new ArrayList<>();
        update.add(Operators.set("item.upgrades", Operators.add(Operators.ifNull("$item.upgrades", 0), upgrades)));
        update.add(Operators.set("item.price", Operators.add("$item.price", Math.round(defaultAxe.getPrice() * 0.015D) * upgrades)));
        if (upgrade == Upgrade.DURABILITY) {
            int increase = (int) upgrade.getValue() * upgrades;
            update.add(Operators.set("item.durability", Operators.add("$item.durability", increase)));
            update.add(Operators.set("item.maxDurability", Operators.add("$item.maxDurability", increase)));
        } else if (upgrade == Upgrade.MULTIPLIER) {
            double increase = defaultAxe.getMultiplier() * upgrade.getValue() * upgrades;
            update.add(Operators.set("item.multiplier", Operators.add("$item.multiplier", increase)));
        }
        event.getMongo().getItems().updateOne(session, Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", axe.getId())), update);
        return String.format("You just upgraded %s %d time%s for your `%s` for **$%,d**", upgrade.getName().toLowerCase(), upgrades, (upgrades == 1 ? "" : "s"), axe.getName(), price);
    }).whenComplete((message, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception) || message == null) {
            return;
        }
        event.replySuccess(message).queue();
    });
}
Also used : Document(org.bson.Document) EconomyUtility(com.sx4.bot.utility.EconomyUtility) Arrays(java.util.Arrays) CancelException(com.sx4.bot.waiter.exception.CancelException) Command(com.jockie.bot.core.command.Command) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) Permission(net.dv8tion.jda.api.Permission) CraftItem(com.sx4.bot.entities.economy.item.CraftItem) CommandId(com.sx4.bot.annotations.command.CommandId) CompletableFuture(java.util.concurrent.CompletableFuture) Member(net.dv8tion.jda.api.entities.Member) PagedResult(com.sx4.bot.paged.PagedResult) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) ItemStack(com.sx4.bot.entities.economy.item.ItemStack) ButtonUtility(com.sx4.bot.utility.ButtonUtility) UpdateResult(com.mongodb.client.result.UpdateResult) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) com.mongodb.client.model(com.mongodb.client.model) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) EnumSet(java.util.EnumSet) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) Upgrade(com.sx4.bot.entities.economy.upgrade.Upgrade) Operators(com.sx4.bot.database.mongo.model.Operators) ItemType(com.sx4.bot.entities.economy.item.ItemType) Sx4Command(com.sx4.bot.core.Sx4Command) NumberUtility(com.sx4.bot.utility.NumberUtility) CompletionException(java.util.concurrent.CompletionException) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Collectors(java.util.stream.Collectors) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) DefaultNumber(com.sx4.bot.annotations.argument.DefaultNumber) Examples(com.sx4.bot.annotations.command.Examples) Axe(com.sx4.bot.entities.economy.item.Axe) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) ArrayList(java.util.ArrayList) List(java.util.List) Document(org.bson.Document) UpdateResult(com.mongodb.client.result.UpdateResult) Axe(com.sx4.bot.entities.economy.item.Axe) 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 Argument

use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.

the class GiveItemCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user") Member member, @Argument(value = "item", endless = true) ItemStack<Item> stack) {
    User user = member.getUser();
    if (user.isBot()) {
        event.replyFailure("You can not give items to bots").queue();
        return;
    }
    if (user.getIdLong() == event.getAuthor().getIdLong()) {
        event.replyFailure("You can not give items to yourself").queue();
        return;
    }
    long amount = stack.getAmount();
    if (amount < 1) {
        event.replyFailure("You need to give at least 1 item").queue();
        return;
    }
    Item item = stack.getItem();
    if (item instanceof Tool) {
        event.replyFailure("You cannot give tools").queue();
        return;
    }
    long price = stack.getTotalPrice();
    long tax = (long) Math.ceil(price * 0.05D);
    event.getMongo().withTransaction(session -> {
        UpdateResult balanceResult = event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getAuthor().getIdLong()), List.of(EconomyUtility.decreaseBalanceUpdate(tax)));
        if (balanceResult.getModifiedCount() == 0) {
            event.replyFormat("You do not have enough to pay the tax for this item (**$%,d**) %s", tax, event.getConfig().getFailureEmote()).queue();
            session.abortTransaction();
            return null;
        }
        FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).projection(Projections.include("amount", "resets"));
        Bson authorFilter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", item.getId()));
        List<Bson> authorUpdate = List.of(Operators.set("amount", Operators.let(new Document("amount", Operators.ifNull("$amount", 0L)), Operators.cond(Operators.lt(Operators.subtract("$$amount", Operators.sum(Operators.map(Operators.filter(Operators.ifNull("$resets", Collections.EMPTY_LIST), Operators.gt("$$this.time", Operators.nowEpochSecond())), "$$this.amount"))), amount), "$$amount", Operators.subtract("$$amount", amount)))));
        Document authorData = event.getMongo().getItems().findOneAndUpdate(session, authorFilter, authorUpdate, options);
        long authorAmount = authorData == null ? 0L : authorData.get("amount", 0L);
        if (authorAmount < amount) {
            event.replyFailure("You do not have `" + amount + " " + item.getName() + "`").queue();
            session.abortTransaction();
            return null;
        }
        CooldownItemStack<Item> cooldownStack = new CooldownItemStack<>(item, authorData);
        long cooldownAmount = cooldownStack.getCooldownAmount();
        if (authorAmount - cooldownAmount < amount) {
            event.replyFormat("You have `%,d %s` but **%,d** %s on cooldown %s", authorAmount, item.getName(), cooldownAmount, cooldownAmount == 1 ? "is" : "are", event.getConfig().getFailureEmote()).queue();
            session.abortTransaction();
            return null;
        }
        Bson userFilter = Filters.and(Filters.eq("userId", member.getIdLong()), Filters.eq("item.id", item.getId()));
        List<Bson> userUpdate = List.of(Operators.set("item", item.toData()), Operators.set("amount", Operators.add(Operators.ifNull("$amount", 0L), stack.getAmount())));
        Document userData = event.getMongo().getItems().findOneAndUpdate(session, userFilter, userUpdate, options.upsert(true));
        event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getSelfUser().getIdLong()), Updates.inc("economy.balance", tax));
        EmbedBuilder embed = new EmbedBuilder().setColor(event.getMember().getColor()).setAuthor(event.getAuthor().getName() + " → " + member.getUser().getName(), null, "https://cdn0.iconfinder.com/data/icons/social-messaging-ui-color-shapes/128/money-circle-green-3-512.png").setDescription(String.format("You have gifted **%,d %s** to **%s**\n\n%s's new %s amount: **%,d %s**\n%s's new %s amount: **%,d %s**", amount, item.getName(), user.getName(), event.getAuthor().getName(), item.getName(), authorAmount - amount, item.getName(), user.getName(), item.getName(), (userData == null ? 0L : userData.getLong("amount")) + amount, item.getName())).setFooter(String.format("$%,d (%d%%) tax was taken", tax, Math.round((double) tax / price * 100)), null);
        return embed.build();
    }).whenComplete((embed, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception) || embed == null) {
            return;
        }
        event.reply(embed).queue();
    });
}
Also used : CooldownItemStack(com.sx4.bot.entities.economy.item.CooldownItemStack) Document(org.bson.Document) Operators(com.sx4.bot.database.mongo.model.Operators) EconomyUtility(com.sx4.bot.utility.EconomyUtility) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Member(net.dv8tion.jda.api.entities.Member) User(net.dv8tion.jda.api.entities.User) Bson(org.bson.conversions.Bson) ModuleCategory(com.sx4.bot.category.ModuleCategory) ItemStack(com.sx4.bot.entities.economy.item.ItemStack) List(java.util.List) UpdateResult(com.mongodb.client.result.UpdateResult) Item(com.sx4.bot.entities.economy.item.Item) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) com.mongodb.client.model(com.mongodb.client.model) Collections(java.util.Collections) Argument(com.jockie.bot.core.argument.Argument) Tool(com.sx4.bot.entities.economy.item.Tool) User(net.dv8tion.jda.api.entities.User) Document(org.bson.Document) CooldownItemStack(com.sx4.bot.entities.economy.item.CooldownItemStack) Bson(org.bson.conversions.Bson) Item(com.sx4.bot.entities.economy.item.Item) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) List(java.util.List) UpdateResult(com.mongodb.client.result.UpdateResult) Tool(com.sx4.bot.entities.economy.item.Tool)

Example 3 with Argument

use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.

the class CrateCommand method buy.

@Command(value = "buy", description = "Buy a crate from the `crate shop`")
@CommandId(412)
@Examples({ "crate buy 2 Shoe Crate", "crate buy Shoe Crate", "crate buy 5 Shoe" })
public void buy(Sx4CommandEvent event, @Argument(value = "crates", endless = true) ItemStack<Crate> stack) {
    long amount = stack.getAmount();
    if (amount < 1) {
        event.replyFailure("You need to buy at least 1 crate").queue();
        return;
    }
    long price = stack.getTotalPrice();
    Crate crate = stack.getItem();
    event.getMongo().withTransaction(session -> {
        UpdateResult result = event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getAuthor().getIdLong()), List.of(EconomyUtility.decreaseBalanceUpdate(price)));
        if (result.getModifiedCount() == 0) {
            event.replyFormat("You do not have **$%,d** %s", price, event.getConfig().getFailureEmote()).queue();
            session.abortTransaction();
            return;
        }
        Bson filter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", crate.getId()));
        List<Bson> update = List.of(Operators.set("item", crate.toData()), Operators.set("amount", Operators.add(Operators.ifNull("$amount", 0L), amount)));
        event.getMongo().getItems().updateOne(session, filter, update, new UpdateOptions().upsert(true));
    }).whenComplete((updated, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception) || !updated) {
            return;
        }
        event.replyFormat("You just bought `%,d %s` for **$%,d** %s", amount, crate.getName(), price, event.getConfig().getSuccessEmote()).queue();
    });
}
Also used : Document(org.bson.Document) EconomyUtility(com.sx4.bot.utility.EconomyUtility) Command(com.jockie.bot.core.command.Command) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) PagedResult(com.sx4.bot.paged.PagedResult) Filters(com.mongodb.client.model.Filters) Bson(org.bson.conversions.Bson) ItemStack(com.sx4.bot.entities.economy.item.ItemStack) UpdateResult(com.mongodb.client.result.UpdateResult) Item(com.sx4.bot.entities.economy.item.Item) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) UpdateOptions(com.mongodb.client.model.UpdateOptions) Argument(com.jockie.bot.core.argument.Argument) Operators(com.sx4.bot.database.mongo.model.Operators) Sx4Command(com.sx4.bot.core.Sx4Command) Predicate(java.util.function.Predicate) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Collectors(java.util.stream.Collectors) 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) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) Crate(com.sx4.bot.entities.economy.item.Crate) Comparator(java.util.Comparator) Collections(java.util.Collections) Crate(com.sx4.bot.entities.economy.item.Crate) List(java.util.List) UpdateResult(com.mongodb.client.result.UpdateResult) UpdateOptions(com.mongodb.client.model.UpdateOptions) Bson(org.bson.conversions.Bson) 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 4 with Argument

use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.

the class SuggestionCommand method remove.

@Command(value = "remove", aliases = { "delete" }, description = "Removes a suggestion, can be your own or anyones if you have the manage server permission")
@CommandId(85)
@Examples({ "suggestion remove 5e45ce6d3688b30ee75201ae", "suggestion remove all" })
public void remove(Sx4CommandEvent event, @Argument(value = "id | message | all", acceptEmpty = true) @AlternativeOptions("all") Alternative<Or<MessageArgument, ObjectId>> option) {
    User author = event.getAuthor();
    if (option.isAlternative()) {
        if (!event.hasPermission(event.getMember(), Permission.MANAGE_SERVER)) {
            event.replyFailure("You are missing the permission " + Permission.MANAGE_SERVER.getName() + " to execute this, you can remove your own suggestions only").queue();
            return;
        }
        List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
        event.reply(author.getName() + ", are you sure you want to delete **all** the suggestions in this server?").setActionRow(buttons).submit().thenCompose(message -> {
            return new Waiter<>(event.getBot(), ButtonClickEvent.class).setPredicate(e -> ButtonUtility.handleButtonConfirmation(e, message, event.getAuthor())).setCancelPredicate(e -> ButtonUtility.handleButtonCancellation(e, message, event.getAuthor())).onFailure(e -> ButtonUtility.handleButtonFailure(e, message)).setTimeout(60).start();
        }).whenComplete((e, exception) -> {
            Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
            if (cause instanceof CancelException) {
                GenericEvent cancelEvent = ((CancelException) cause).getEvent();
                if (cancelEvent != null) {
                    ((ButtonClickEvent) cancelEvent).reply("Cancelled " + event.getConfig().getSuccessEmote()).queue();
                }
                return;
            } else if (cause instanceof TimeoutException) {
                event.reply("Timed out :stopwatch:").queue();
                return;
            } else if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            event.getMongo().deleteManySuggestions(Filters.eq("guildId", event.getGuild().getIdLong())).whenComplete((result, databaseException) -> {
                if (ExceptionUtility.sendExceptionally(event, databaseException)) {
                    return;
                }
                if (result.getDeletedCount() == 0) {
                    e.reply("This server has no suggestions " + event.getConfig().getFailureEmote()).queue();
                    return;
                }
                e.reply("All suggestions have been deleted in this server " + event.getConfig().getSuccessEmote()).queue();
            });
        });
    } else {
        Or<MessageArgument, ObjectId> argument = option.getValue();
        boolean hasPermission = event.hasPermission(event.getMember(), Permission.MANAGE_SERVER);
        Bson filter = Filters.and(argument.hasFirst() ? Filters.eq("messageId", argument.getFirst().getMessageId()) : Filters.eq("_id", argument.getSecond()), Filters.eq("guildId", event.getGuild().getIdLong()));
        if (!hasPermission) {
            filter = Filters.and(Filters.eq("authorId", author.getIdLong()), filter);
        }
        event.getMongo().findAndDeleteSuggestion(filter).whenComplete((data, exception) -> {
            if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            if (data == null) {
                event.replyFailure("I could not find that suggestion").queue();
                return;
            }
            if (data.getLong("authorId") != author.getIdLong() && !hasPermission) {
                event.replyFailure("You do not own that suggestion").queue();
                return;
            }
            WebhookClient webhook = event.getBot().getSuggestionManager().getWebhook(data.getLong("channelId"));
            if (webhook != null) {
                webhook.delete(data.getLong("messageId"));
            }
            event.replySuccess("That suggestion has been removed").queue();
        });
    }
}
Also used : Document(org.bson.Document) CancelException(com.sx4.bot.waiter.exception.CancelException) WebhookClient(club.minnced.discord.webhook.WebhookClient) Command(com.jockie.bot.core.command.Command) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) MessageArgument(com.sx4.bot.entities.argument.MessageArgument) Suggestion(com.sx4.bot.entities.management.Suggestion) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) TextChannel(net.dv8tion.jda.api.entities.TextChannel) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) PagedResult(com.sx4.bot.paged.PagedResult) User(net.dv8tion.jda.api.entities.User) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) ColourUtility(com.sx4.bot.utility.ColourUtility) ButtonUtility(com.sx4.bot.utility.ButtonUtility) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) com.mongodb.client.model(com.mongodb.client.model) com.sx4.bot.annotations.command(com.sx4.bot.annotations.command) Or(com.sx4.bot.entities.argument.Or) Argument(com.jockie.bot.core.argument.Argument) Message(net.dv8tion.jda.api.entities.Message) Operators(com.sx4.bot.database.mongo.model.Operators) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Sx4Command(com.sx4.bot.core.Sx4Command) CompletionException(java.util.concurrent.CompletionException) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) Colour(com.sx4.bot.annotations.argument.Colour) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) ObjectId(org.bson.types.ObjectId) Clock(java.time.Clock) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) SuggestionState(com.sx4.bot.entities.management.SuggestionState) Collections(java.util.Collections) User(net.dv8tion.jda.api.entities.User) WebhookClient(club.minnced.discord.webhook.WebhookClient) ObjectId(org.bson.types.ObjectId) Bson(org.bson.conversions.Bson) MessageArgument(com.sx4.bot.entities.argument.MessageArgument) Button(net.dv8tion.jda.api.interactions.components.Button) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) CompletionException(java.util.concurrent.CompletionException) CancelException(com.sx4.bot.waiter.exception.CancelException) Waiter(com.sx4.bot.waiter.Waiter) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 5 with Argument

use of com.jockie.bot.core.argument.Argument 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

Argument (com.jockie.bot.core.argument.Argument)109 ModuleCategory (com.sx4.bot.category.ModuleCategory)109 Sx4Command (com.sx4.bot.core.Sx4Command)109 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)109 Permission (net.dv8tion.jda.api.Permission)96 Document (org.bson.Document)67 PagedResult (com.sx4.bot.paged.PagedResult)57 HttpCallback (com.sx4.bot.http.HttpCallback)54 Request (okhttp3.Request)53 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)50 Command (com.jockie.bot.core.command.Command)48 List (java.util.List)47 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)42 Bson (org.bson.conversions.Bson)42 Operators (com.sx4.bot.database.mongo.model.Operators)40 User (net.dv8tion.jda.api.entities.User)40 CommandId (com.sx4.bot.annotations.command.CommandId)39 Examples (com.sx4.bot.annotations.command.Examples)39 Alternative (com.sx4.bot.entities.argument.Alternative)37 AlternativeOptions (com.sx4.bot.annotations.argument.AlternativeOptions)36