Search in sources :

Example 11 with ButtonClickEvent

use of net.dv8tion.jda.api.events.interaction.ButtonClickEvent in project Sx4 by sx4-discord-bot.

the class PremiumCommand method add.

@Command(value = "add", description = "Make a server premium")
@CommandId(177)
@Examples({ "premium add", "premium add 31", "premium add 20 Sx4 | Support Server" })
@Premium
public void add(Sx4CommandEvent event, @Argument(value = "days") @DefaultNumber(31) @Limit(min = 1, max = 365) int days, @Argument(value = "server", endless = true, nullDefault = true) Guild guild) {
    if (guild == null) {
        guild = event.getGuild();
    }
    long guildId = guild.getIdLong();
    String guildName = guild.getName();
    int monthPrice = event.getConfig().getPremiumPrice();
    int price = (int) Math.round((monthPrice / (double) event.getConfig().getPremiumDays()) * days);
    long endAtPrior = event.getMongo().getGuildById(guildId, Projections.include("premium.endAt")).getEmbedded(List.of("premium", "endAt"), 0L);
    boolean hasPremium = endAtPrior != 0;
    MessageEmbed embed = new EmbedBuilder().setColor(event.getConfig().getOrange()).setAuthor("Premium", null, event.getAuthor().getEffectiveAvatarUrl()).setDescription(String.format("Buying %d day%s of premium will:\n\n• Make you unable to use this credit on the other version of the bot\n• Use **$%.2f** of your credit\n• %s %1$s day%2$s of premium to the server\n\n:warning: **This action cannot be reversed** :warning:", days, days == 1 ? "" : "s", price / 100D, hasPremium ? "Add an extra" : "Give")).build();
    List<Button> buttons = List.of(Button.success("confirm", "Confirm"), Button.danger("cancel", "Cancel"));
    event.reply(embed).setActionRow(buttons).submit().thenCompose(message -> {
        return new Waiter<>(event.getBot(), ButtonClickEvent.class).setPredicate(e -> ButtonUtility.handleButtonConfirmation(e, message, event.getAuthor(), "confirm")).setCancelPredicate(e -> ButtonUtility.handleButtonCancellation(e, message, event.getAuthor(), "cancel")).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;
        }
        List<Bson> update = List.of(Operators.set("premium.credit", Operators.cond(Operators.gt(price, Operators.ifNull("$premium.credit", 0)), "$premium.credit", Operators.subtract("$premium.credit", price))));
        FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).projection(Projections.include("premium.credit")).upsert(true);
        event.getMongoMain().findAndUpdateUserById(event.getAuthor().getIdLong(), update, options).thenCompose(data -> {
            int credit = data == null ? 0 : data.getEmbedded(List.of("premium", "credit"), 0);
            if (price > credit) {
                e.reply("You do not have enough credit to buy premium for that long " + event.getConfig().getFailureEmote()).queue();
                return CompletableFuture.completedFuture(MongoDatabase.EMPTY_DOCUMENT);
            }
            List<Bson> guildUpdate = List.of(Operators.set("premium.endAt", Operators.add(TimeUnit.DAYS.toSeconds(days), Operators.ifNull("$premium.endAt", Operators.nowEpochSecond()))));
            FindOneAndUpdateOptions guildOptions = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).projection(Projections.include("premium.endAt")).upsert(true);
            return event.getMongo().findAndUpdateGuildById(guildId, guildUpdate, guildOptions);
        }).whenComplete((data, databaseException) -> {
            if (ExceptionUtility.sendExceptionally(event, databaseException) || (data != null && data.isEmpty())) {
                return;
            }
            long endAt = data == null ? 0L : data.getEmbedded(List.of("premium", "endAt"), 0L);
            e.replyFormat("**%s** now has premium for %s%d day%s %s", guildName, endAt == 0 ? "" : "another ", days, days == 1 ? "" : "s", event.getConfig().getSuccessEmote()).queue();
        });
    });
}
Also used : Document(org.bson.Document) CancelException(com.sx4.bot.waiter.exception.CancelException) MarkdownSanitizer(net.dv8tion.jda.api.utils.MarkdownSanitizer) Command(com.jockie.bot.core.command.Command) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) CommandId(com.sx4.bot.annotations.command.CommandId) CompletableFuture(java.util.concurrent.CompletableFuture) PagedResult(com.sx4.bot.paged.PagedResult) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Bson(org.bson.conversions.Bson) Redirects(com.sx4.bot.annotations.command.Redirects) ButtonUtility(com.sx4.bot.utility.ButtonUtility) Guild(net.dv8tion.jda.api.entities.Guild) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) Map(java.util.Map) Option(com.jockie.bot.core.option.Option) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) com.mongodb.client.model(com.mongodb.client.model) ZoneOffset(java.time.ZoneOffset) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) Operators(com.sx4.bot.database.mongo.model.Operators) 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) Instant(java.time.Instant) Premium(com.sx4.bot.annotations.command.Premium) TimeUnit(java.util.concurrent.TimeUnit) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) DefaultNumber(com.sx4.bot.annotations.argument.DefaultNumber) Examples(com.sx4.bot.annotations.command.Examples) OffsetDateTime(java.time.OffsetDateTime) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) DateTimeFormatter(java.time.format.DateTimeFormatter) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Bson(org.bson.conversions.Bson) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Button(net.dv8tion.jda.api.interactions.components.Button) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) CompletionException(java.util.concurrent.CompletionException) ArrayList(java.util.ArrayList) List(java.util.List) 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) Premium(com.sx4.bot.annotations.command.Premium) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 12 with ButtonClickEvent

use of net.dv8tion.jda.api.events.interaction.ButtonClickEvent in project Sx4 by sx4-discord-bot.

the class FishingRodCommand method repair.

@Command(value = "repair", description = "Repair your current fishing rod with the material it is made from")
@CommandId(383)
@Examples({ "fishing rod repair 10", "fishing rod repair all" })
public void repair(Sx4CommandEvent event, @Argument(value = "durability") @AlternativeOptions("all") Alternative<Integer> option) {
    Bson filter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.type", ItemType.ROD.getId()));
    Document data = event.getMongo().getItem(filter, Projections.include("item"));
    if (data == null) {
        event.replyFailure("You do not have a fishing rod").queue();
        return;
    }
    Rod rod = Rod.fromData(event.getBot().getEconomyManager(), data.get("item", Document.class));
    CraftItem item = rod.getRepairItem();
    if (item == null) {
        event.replyFailure("That fishing rod is not repairable").queue();
        return;
    }
    int maxDurability = rod.getMaxDurability() - rod.getDurability();
    if (maxDurability <= 0) {
        event.replyFailure("Your fishing rod is already at full durability").queue();
        return;
    }
    int durability;
    if (option.isAlternative()) {
        durability = maxDurability;
    } else {
        int amount = option.getValue();
        if (amount > maxDurability) {
            event.reply("You can only repair your fishing rod by **" + maxDurability + "** durability :no_entry:").queue();
            return;
        }
        durability = amount;
    }
    int itemCount = (int) Math.ceil((((double) rod.getPrice() / item.getPrice()) / rod.getMaxDurability()) * durability);
    List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
    event.reply("It will cost you `" + itemCount + " " + item.getName() + "` to repair your fishing rod by **" + durability + "** durability, are you sure you want to repair it?").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;
        }
        List<Bson> update = List.of(Operators.set("amount", Operators.let(new Document("amount", Operators.ifNull("$amount", 0L)), Operators.cond(Operators.lte(itemCount, "$$amount"), Operators.subtract("$$amount", itemCount), "$$amount"))));
        event.getMongo().updateItem(Filters.and(Filters.eq("item.id", item.getId()), Filters.eq("userId", event.getAuthor().getIdLong())), update, new UpdateOptions()).thenCompose(result -> {
            if (result.getMatchedCount() == 0 || result.getModifiedCount() == 0) {
                e.reply("You do not have `" + itemCount + " " + item.getName() + "` " + event.getConfig().getFailureEmote()).queue();
                return CompletableFuture.completedFuture(null);
            }
            List<Bson> itemUpdate = List.of(Operators.set("item.durability", Operators.cond(Operators.eq("$item.durability", rod.getDurability()), Operators.add("$item.durability", durability), "$item.durability")));
            return event.getMongo().updateItem(Filters.and(Filters.eq("item.id", rod.getId()), Filters.eq("userId", event.getAuthor().getIdLong())), itemUpdate, new UpdateOptions());
        }).whenComplete((result, databaseException) -> {
            if (ExceptionUtility.sendExceptionally(event, databaseException) || result == null) {
                return;
            }
            if (result.getMatchedCount() == 0) {
                e.reply("You no longer have that fishing rod " + event.getConfig().getFailureEmote()).queue();
                return;
            }
            if (result.getMatchedCount() == 0) {
                e.reply("The durability of your fishing rod has changed " + event.getConfig().getFailureEmote()).queue();
                return;
            }
            e.reply("You just repaired your fishing rod by **" + durability + "** durability " + event.getConfig().getSuccessEmote()).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) 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) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Rod(com.sx4.bot.entities.economy.item.Rod) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) Rod(com.sx4.bot.entities.economy.item.Rod) Document(org.bson.Document) CraftItem(com.sx4.bot.entities.economy.item.CraftItem) Bson(org.bson.conversions.Bson) Button(net.dv8tion.jda.api.interactions.components.Button) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) CompletionException(java.util.concurrent.CompletionException) ArrayList(java.util.ArrayList) List(java.util.List) 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) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 13 with ButtonClickEvent

use of net.dv8tion.jda.api.events.interaction.ButtonClickEvent in project Sx4 by sx4-discord-bot.

the class AxeCommand method repair.

@Command(value = "repair", description = "Repair your current axe with the material it is made from")
@CommandId(392)
@Examples({ "axe repair 10", "axe repair all" })
public void repair(Sx4CommandEvent event, @Argument(value = "durability") @AlternativeOptions("all") Alternative<Integer> option) {
    Bson filter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.type", ItemType.AXE.getId()));
    Document data = event.getMongo().getItem(filter, Projections.include("item"));
    if (data == null) {
        event.replyFailure("You do not have a axe").queue();
        return;
    }
    Axe axe = Axe.fromData(event.getBot().getEconomyManager(), data.get("item", Document.class));
    CraftItem item = axe.getRepairItem();
    if (item == null) {
        event.replyFailure("That axe is not repairable").queue();
        return;
    }
    int maxDurability = axe.getMaxDurability() - axe.getDurability();
    if (maxDurability <= 0) {
        event.replyFailure("Your axe is already at full durability").queue();
        return;
    }
    int durability;
    if (option.isAlternative()) {
        durability = maxDurability;
    } else {
        int amount = option.getValue();
        if (amount > maxDurability) {
            event.reply("You can only repair your axe by **" + maxDurability + "** durability :no_entry:").queue();
            return;
        }
        durability = amount;
    }
    int itemCount = (int) Math.ceil((((double) axe.getPrice() / item.getPrice()) / axe.getMaxDurability()) * durability);
    List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
    event.reply("It will cost you `" + itemCount + " " + item.getName() + "` to repair your axe by **" + durability + "** durability, are you sure you want to repair it?").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;
        }
        List<Bson> update = List.of(Operators.set("amount", Operators.let(new Document("amount", Operators.ifNull("$amount", 0L)), Operators.cond(Operators.lte(itemCount, "$$amount"), Operators.subtract("$$amount", itemCount), "$$amount"))));
        event.getMongo().updateItem(Filters.and(Filters.eq("item.id", item.getId()), Filters.eq("userId", event.getAuthor().getIdLong())), update, new UpdateOptions()).thenCompose(result -> {
            if (result.getMatchedCount() == 0 || result.getModifiedCount() == 0) {
                e.reply("You do not have `" + itemCount + " " + item.getName() + "` " + event.getConfig().getFailureEmote()).queue();
                return CompletableFuture.completedFuture(null);
            }
            List<Bson> itemUpdate = List.of(Operators.set("item.durability", Operators.cond(Operators.eq("$item.durability", axe.getDurability()), Operators.add("$item.durability", durability), "$item.durability")));
            return event.getMongo().updateItem(Filters.and(Filters.eq("item.id", axe.getId()), Filters.eq("userId", event.getAuthor().getIdLong())), itemUpdate, new UpdateOptions());
        }).whenComplete((result, databaseException) -> {
            if (ExceptionUtility.sendExceptionally(event, databaseException) || result == null) {
                return;
            }
            if (result.getMatchedCount() == 0) {
                e.reply("You no longer have that axe " + event.getConfig().getFailureEmote()).queue();
                return;
            }
            if (result.getMatchedCount() == 0) {
                e.reply("The durability of your axe has changed " + event.getConfig().getFailureEmote()).queue();
                return;
            }
            e.reply("You just repaired your axe by **" + durability + "** durability " + event.getConfig().getSuccessEmote()).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) Document(org.bson.Document) CraftItem(com.sx4.bot.entities.economy.item.CraftItem) Bson(org.bson.conversions.Bson) Axe(com.sx4.bot.entities.economy.item.Axe) Button(net.dv8tion.jda.api.interactions.components.Button) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) CompletionException(java.util.concurrent.CompletionException) ArrayList(java.util.ArrayList) List(java.util.List) 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) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 14 with ButtonClickEvent

use of net.dv8tion.jda.api.events.interaction.ButtonClickEvent in project Sx4 by sx4-discord-bot.

the class AutoRoleCommand method remove.

@Command(value = "remove", aliases = { "delete" }, description = "Remove a role from being given when a user joins")
@CommandId(40)
@Examples({ "auto role remove @Role", "auto role remove Role", "auto role remove all" })
@AuthorPermissions(permissions = { Permission.MANAGE_ROLES })
public void remove(Sx4CommandEvent event, @Argument(value = "role | all", endless = true) @AlternativeOptions("all") Alternative<Role> option) {
    if (option.isAlternative()) {
        List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
        event.reply(event.getAuthor().getName() + ", are you sure you want to remove every auto role in the 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().deleteManyAutoRoles(Filters.eq("guildId", event.getGuild().getIdLong())).whenComplete((result, databaseException) -> {
                if (ExceptionUtility.sendExceptionally(event, databaseException)) {
                    return;
                }
                if (result.getDeletedCount() == 0) {
                    e.reply("There are no auto roles in this server " + event.getConfig().getFailureEmote()).queue();
                    return;
                }
                e.reply("All auto roles have been removed " + event.getConfig().getSuccessEmote()).queue();
            });
        });
    } else {
        Role role = option.getValue();
        event.getMongo().deleteAutoRole(Filters.eq("roleId", role.getIdLong())).whenComplete((result, exception) -> {
            if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            if (result.getDeletedCount() == 0) {
                event.replyFailure("That role is not an auto role").queue();
                return;
            }
            event.replySuccess(role.getAsMention() + " is no longer an auto role").queue();
        });
    }
}
Also used : Document(org.bson.Document) java.util(java.util) CancelException(com.sx4.bot.waiter.exception.CancelException) Command(com.jockie.bot.core.command.Command) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) MongoWriteException(com.mongodb.MongoWriteException) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) CompletableFuture(java.util.concurrent.CompletableFuture) Member(net.dv8tion.jda.api.entities.Member) TimedArgument(com.sx4.bot.entities.argument.TimedArgument) PagedResult(com.sx4.bot.paged.PagedResult) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) AutoRoleFilter(com.sx4.bot.entities.management.AutoRoleFilter) Role(net.dv8tion.jda.api.entities.Role) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) com.sx4.bot.utility(com.sx4.bot.utility) 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) Argument(com.jockie.bot.core.argument.Argument) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Operators(com.sx4.bot.database.mongo.model.Operators) Sx4Command(com.sx4.bot.core.Sx4Command) 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) Examples(com.sx4.bot.annotations.command.Examples) ErrorCategory(com.mongodb.ErrorCategory) Role(net.dv8tion.jda.api.entities.Role) 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) 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 15 with ButtonClickEvent

use of net.dv8tion.jda.api.events.interaction.ButtonClickEvent in project Sx4 by sx4-discord-bot.

the class GiveawayCommand method delete.

@Command(value = "delete", aliases = { "remove" }, description = "Deletes a giveaway")
@CommandId(51)
@Examples({ "giveaway delete 727224132202397726", "giveaway delete all" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void delete(Sx4CommandEvent event, @Argument(value = "message id | all") @AlternativeOptions("all") Alternative<MessageArgument> option) {
    if (option.isAlternative()) {
        List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
        event.reply(event.getAuthor().getName() + ", are you sure you want to delete **all** giveaways 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().deleteManyGiveaways(Filters.eq("guildId", event.getGuild().getIdLong())).whenComplete((result, databaseException) -> {
                if (ExceptionUtility.sendExceptionally(event, databaseException)) {
                    return;
                }
                if (result.getDeletedCount() == 0) {
                    e.reply("There are no giveaways in this server " + event.getConfig().getFailureEmote()).queue();
                    return;
                }
                e.reply("All giveaways in this server have been deleted " + event.getConfig().getSuccessEmote()).queue();
            });
        });
    } else {
        long messageId = option.getValue().getMessageId();
        event.getMongo().deleteGiveawayById(messageId).whenComplete((result, exception) -> {
            if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            if (result.getDeletedCount() == 0) {
                event.replyFailure("There was no giveaway with that id").queue();
                return;
            }
            event.replySuccess("That giveaway has been deleted").queue();
        });
    }
}
Also used : Document(org.bson.Document) CancelException(com.sx4.bot.waiter.exception.CancelException) Command(com.jockie.bot.core.command.Command) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) MessageArgument(com.sx4.bot.entities.argument.MessageArgument) Permission(net.dv8tion.jda.api.Permission) Projections(com.mongodb.client.model.Projections) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) CommandId(com.sx4.bot.annotations.command.CommandId) CompletableFuture(java.util.concurrent.CompletableFuture) TextChannel(net.dv8tion.jda.api.entities.TextChannel) PagedResult(com.sx4.bot.paged.PagedResult) AtomicReference(java.util.concurrent.atomic.AtomicReference) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Filters(com.mongodb.client.model.Filters) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) Duration(java.time.Duration) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) com.sx4.bot.utility(com.sx4.bot.utility) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) 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) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Sx4Command(com.sx4.bot.core.Sx4Command) ReturnDocument(com.mongodb.client.model.ReturnDocument) CompletionException(java.util.concurrent.CompletionException) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) DefaultNumber(com.sx4.bot.annotations.argument.DefaultNumber) Examples(com.sx4.bot.annotations.command.Examples) Clock(java.time.Clock) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) Collections(java.util.Collections) 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) 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)

Aggregations

ButtonClickEvent (net.dv8tion.jda.api.events.interaction.ButtonClickEvent)19 Button (net.dv8tion.jda.api.interactions.components.Button)18 Argument (com.jockie.bot.core.argument.Argument)16 ModuleCategory (com.sx4.bot.category.ModuleCategory)16 Sx4Command (com.sx4.bot.core.Sx4Command)16 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)16 Waiter (com.sx4.bot.waiter.Waiter)16 CancelException (com.sx4.bot.waiter.exception.CancelException)16 TimeoutException (com.sx4.bot.waiter.exception.TimeoutException)16 CompletionException (java.util.concurrent.CompletionException)16 GenericEvent (net.dv8tion.jda.api.events.GenericEvent)16 Document (org.bson.Document)16 List (java.util.List)15 User (net.dv8tion.jda.api.entities.User)15 Command (com.jockie.bot.core.command.Command)14 PagedResult (com.sx4.bot.paged.PagedResult)14 ButtonUtility (com.sx4.bot.utility.ButtonUtility)14 AlternativeOptions (com.sx4.bot.annotations.argument.AlternativeOptions)13 Alternative (com.sx4.bot.entities.argument.Alternative)13 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)13