Search in sources :

Example 11 with Limit

use of com.sx4.bot.annotations.argument.Limit in project Sx4 by sx4-discord-bot.

the class TemporaryBanCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user") String userArgument, @Argument(value = "time", nullDefault = true) Duration time, @Argument(value = "reason", endless = true, nullDefault = true) Reason reason, @Option(value = "days", description = "Set how many days of messages should be deleted from the user") @DefaultNumber(1) @Limit(min = 0, max = 7) int days) {
    SearchUtility.getUser(event.getShardManager(), userArgument).thenAccept(user -> {
        if (user == null) {
            event.replyFailure("I could not find that user").queue();
            return;
        }
        if (user.getIdLong() == event.getSelfUser().getIdLong()) {
            event.replyFailure("You cannot ban me, that is illegal").queue();
            return;
        }
        Guild guild = event.getGuild();
        Member member = guild.getMember(user);
        if (member != null) {
            if (!event.getMember().canInteract(member)) {
                event.replyFailure("You cannot ban someone higher or equal than your top role").queue();
                return;
            }
            if (!event.getSelfMember().canInteract(member)) {
                event.replyFailure("I cannot ban someone higher or equal than my top role").queue();
                return;
            }
        }
        event.getGuild().retrieveBan(user).submit().whenComplete((ban, exception) -> {
            if (exception instanceof ErrorResponseException && ((ErrorResponseException) exception).getErrorResponse() == ErrorResponse.UNKNOWN_BAN) {
                Document data = event.getMongo().getGuildById(guild.getIdLong(), Projections.include("temporaryBan.defaultTime")).get("temporaryBan", MongoDatabase.EMPTY_DOCUMENT);
                long duration = time == null ? data.get("defaultTime", ModUtility.DEFAULT_TEMPORARY_BAN_DURATION) : time.toSeconds();
                List<Bson> update = List.of(Operators.set("unbanAt", Operators.add(Operators.nowEpochSecond(), duration)));
                Bson filter = Filters.and(Filters.eq("userId", event.getMember().getIdLong()), Filters.eq("guildId", event.getGuild().getIdLong()));
                event.getMongo().updateTemporaryBan(filter, update, new UpdateOptions().upsert(true)).whenComplete((result, resultException) -> {
                    if (ExceptionUtility.sendExceptionally(event, resultException)) {
                        return;
                    }
                    event.getGuild().ban(user, days).reason(ModUtility.getAuditReason(reason, event.getAuthor())).queue($ -> {
                        event.replySuccess("**" + user.getAsTag() + "** has been temporarily banned for " + TimeUtility.LONG_TIME_FORMATTER.parse(duration)).queue();
                        event.getBot().getModActionManager().onModAction(new TemporaryBanEvent(event.getMember(), user, reason, member != null, duration));
                        event.getBot().getTemporaryBanManager().putBan(event.getGuild().getIdLong(), user.getIdLong(), duration);
                    });
                });
            } else {
                if (ExceptionUtility.sendExceptionally(event, exception)) {
                    return;
                }
                event.replyFailure("That user is already banned").queue();
            }
        });
    });
}
Also used : ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Guild(net.dv8tion.jda.api.entities.Guild) Document(org.bson.Document) TemporaryBanEvent(com.sx4.bot.events.mod.TemporaryBanEvent) Member(net.dv8tion.jda.api.entities.Member) UpdateOptions(com.mongodb.client.model.UpdateOptions) Bson(org.bson.conversions.Bson)

Example 12 with Limit

use of com.sx4.bot.annotations.argument.Limit in project Sx4 by sx4-discord-bot.

the class AntiInviteCommand method resetAfter.

@Command(value = "reset after", description = "The time it should take for attempts to be taken away")
@CommandId(308)
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@Examples({ "antiinvite reset after 1 1 day", "antiinvite reset after 3 5h 20s", "antiinvite reset after 3 5h 20s" })
public void resetAfter(Sx4CommandEvent event, @Argument(value = "amount") @Limit(min = 0) int amount, @Argument(value = "time", endless = true, nullDefault = true) Duration time) {
    if (time != null && time.toMinutes() < 5) {
        event.replyFailure("The duration has to be 5 minutes or above").queue();
        return;
    }
    if (amount != 0 && time == null) {
        event.reply("You need to provide a duration if attempts is more than 0").queue();
        return;
    }
    Bson update = amount == 0 ? Updates.unset("attempts.reset") : Updates.set("attempts.reset", new Document("amount", amount).append("after", time.toSeconds()));
    Bson filter = Filters.and(Filters.eq("regexId", AntiInviteCommand.REGEX_ID), Filters.eq("guildId", event.getGuild().getIdLong()));
    event.getMongo().updateRegex(filter, update).whenComplete((result, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (result.getMatchedCount() == 0) {
            event.replyFailure("You do not have anti-invite setup").queue();
            return;
        }
        if (result.getModifiedCount() == 0) {
            event.replyFailure("Your reset attempts configuration was already set to that").queue();
            return;
        }
        event.reply(amount == 0 ? "Users attempts will no longer reset" + event.getConfig().getSuccessEmote() : String.format("Users attempts will now reset **%d** time%s after `%s` %s", amount, amount == 1 ? "" : "s", TimeUtility.LONG_TIME_FORMATTER.parse(time.toSeconds()), event.getConfig().getSuccessEmote())).queue();
    });
}
Also used : Document(org.bson.Document) Bson(org.bson.conversions.Bson) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 13 with Limit

use of com.sx4.bot.annotations.argument.Limit in project Sx4 by sx4-discord-bot.

the class AntiRegexCommand method resetAfter.

@Command(value = "reset after", description = "The time it should take for attempts to be taken away")
@CommandId(109)
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@Examples({ "anti regex reset after 5f023782ef9eba03390a740c 1 1 day", "anti regex reset after 5f023782ef9eba03390a740c 3 5h 20s", "anti regex reset after 5f023782ef9eba03390a740c 3 5h 20s" })
public void resetAfter(Sx4CommandEvent event, @Argument(value = "id") ObjectId id, @Argument(value = "amount") @Limit(min = 0) int amount, @Argument(value = "time", endless = true, nullDefault = true) Duration time) {
    if (time != null && time.toMinutes() < 5) {
        event.replyFailure("The duration has to be 5 minutes or above").queue();
        return;
    }
    if (amount != 0 && time == null) {
        event.reply("You need to provide a duration if attempts is more than 0").queue();
        return;
    }
    Bson update = amount == 0 ? Updates.unset("attempts.reset") : Updates.set("attempts.reset", new Document("amount", amount).append("after", time.toSeconds()));
    event.getMongo().updateRegex(Filters.and(Filters.eq("_id", id), Filters.eq("guildId", event.getGuild().getIdLong())), update).whenComplete((result, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (result.getMatchedCount() == 0) {
            event.replyFailure("I could not find that anti regex").queue();
            return;
        }
        if (result.getModifiedCount() == 0) {
            event.replyFailure("Your reset attempts configuration was already set to that").queue();
            return;
        }
        event.reply(amount == 0 ? "Users attempts will no longer reset" + event.getConfig().getSuccessEmote() : String.format("Users attempts will now reset **%d** time%s after `%s` %s", amount, amount == 1 ? "" : "s", TimeUtility.LONG_TIME_FORMATTER.parse(time.toSeconds()), event.getConfig().getSuccessEmote())).queue();
    });
}
Also used : Document(org.bson.Document) Bson(org.bson.conversions.Bson) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 14 with Limit

use of com.sx4.bot.annotations.argument.Limit in project Sx4 by sx4-discord-bot.

the class YouTubeManager method resubscribeBulk.

public DeleteOneModel<Document> resubscribeBulk(String channelId) {
    long amount = this.bot.getMongo().countYouTubeNotifications(Filters.eq("uploaderId", channelId), new CountOptions().limit(1));
    this.deleteExecutor(channelId);
    DeleteOneModel<Document> model = null;
    if (amount != 0) {
        RequestBody body = new MultipartBody.Builder().addFormDataPart("hub.mode", "subscribe").addFormDataPart("hub.topic", "https://www.youtube.com/xml/feeds/videos.xml?channel_id=" + channelId).addFormDataPart("hub.callback", this.bot.getConfig().getBaseUrl() + "/api/youtube").addFormDataPart("hub.verify", "sync").addFormDataPart("hub.verify_token", this.bot.getConfig().getYouTube()).setType(MultipartBody.FORM).build();
        Request request = new Request.Builder().url("https://pubsubhubbub.appspot.com/subscribe").post(body).build();
        this.bot.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
            if (response.isSuccessful()) {
                System.out.println("Resubscribed to " + channelId + " for YouTube notifications");
            } else {
                System.err.printf("Failed to resubscribe to %s for YouTube notifications, Code: %d, Message: %s%n", channelId, response.code(), response.body().string());
            }
            response.close();
        });
    } else {
        model = new DeleteOneModel<>(Filters.eq("_id", channelId));
        this.deleteExecutor(channelId);
    }
    return model;
}
Also used : Document(org.bson.Document) BotPermissionException(com.sx4.bot.exceptions.mod.BotPermissionException) Request(okhttp3.Request) java.util(java.util) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) HttpCallback(com.sx4.bot.http.HttpCallback) java.util.concurrent(java.util.concurrent) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) Channel(net.dv8tion.jda.api.entities.Channel) RequestBody(okhttp3.RequestBody) HttpException(club.minnced.discord.webhook.exception.HttpException) WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) Bson(org.bson.conversions.Bson) OkHttpClient(okhttp3.OkHttpClient) MultipartBody(okhttp3.MultipartBody) Sx4(com.sx4.bot.core.Sx4) YouTubeListener(com.sx4.bot.hooks.YouTubeListener) com.sx4.bot.events.youtube(com.sx4.bot.events.youtube) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) Clock(java.time.Clock) com.mongodb.client.model(com.mongodb.client.model) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage) MultipartBody(okhttp3.MultipartBody) Request(okhttp3.Request) Document(org.bson.Document) RequestBody(okhttp3.RequestBody)

Example 15 with Limit

use of com.sx4.bot.annotations.argument.Limit in project Sx4 by sx4-discord-bot.

the class FishingRodCommand method upgrade.

@Command(value = "upgrade", description = "Upgrade your fishing rod by a certain attribute")
@CommandId(431)
@Examples({ "fishing rod upgrade money", "fishing rod 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.ROD)) {
        event.replyFailure("You can not use that upgrade on a fishing rod").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.ROD.getId()))).first();
        if (data == null) {
            event.replyFailure("You do not have a fishing rod").queue();
            session.abortTransaction();
            return null;
        }
        Document item = data.get("item", Document.class);
        Rod defaultRod = event.getBot().getEconomyManager().getItemById(item.getInteger("id"), Rod.class);
        Rod rod = new Rod(item, defaultRod);
        int currentUpgrades = rod.getUpgrades();
        long price = 0;
        for (int i = 0; i < upgrades; i++) {
            price += Math.round(0.015D * defaultRod.getPrice() * currentUpgrades++ + 0.025D * defaultRod.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(defaultRod.getPrice() * 0.015D) * upgrades)));
        if (upgrade == Upgrade.MONEY) {
            int increase = (int) Math.round(defaultRod.getMinYield() * upgrade.getValue()) * upgrades;
            update.add(Operators.set("item.minYield", Operators.add("$item.minYield", increase)));
            update.add(Operators.set("item.maxYield", Operators.add("$item.maxYield", increase)));
        } else 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)));
        }
        event.getMongo().getItems().updateOne(session, Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", rod.getId())), update);
        return String.format("You just upgraded %s %d time%s for your `%s` for **$%,d**", upgrade.getName().toLowerCase(), upgrades, (upgrades == 1 ? "" : "s"), rod.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) Command(com.jockie.bot.core.command.Command) Permission(net.dv8tion.jda.api.Permission) Projections(com.mongodb.client.model.Projections) CraftItem(com.sx4.bot.entities.economy.item.CraftItem) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) CommandId(com.sx4.bot.annotations.command.CommandId) Member(net.dv8tion.jda.api.entities.Member) PagedResult(com.sx4.bot.paged.PagedResult) 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) ItemStack(com.sx4.bot.entities.economy.item.ItemStack) Button(net.dv8tion.jda.api.interactions.components.buttons.Button) UpdateResult(com.mongodb.client.result.UpdateResult) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) 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) ReturnDocument(com.mongodb.client.model.ReturnDocument) 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) CustomButtonId(com.sx4.bot.entities.interaction.CustomButtonId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) ButtonType(com.sx4.bot.entities.interaction.ButtonType) Rod(com.sx4.bot.entities.economy.item.Rod) ArrayList(java.util.ArrayList) List(java.util.List) Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) UpdateResult(com.mongodb.client.result.UpdateResult) 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

Sx4Command (com.sx4.bot.core.Sx4Command)27 Permission (net.dv8tion.jda.api.Permission)20 Argument (com.jockie.bot.core.argument.Argument)19 ModuleCategory (com.sx4.bot.category.ModuleCategory)19 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)19 Document (org.bson.Document)17 Limit (com.sx4.bot.annotations.argument.Limit)16 Command (com.jockie.bot.core.command.Command)14 HttpCallback (com.sx4.bot.http.HttpCallback)14 Request (okhttp3.Request)13 CommandId (com.sx4.bot.annotations.command.CommandId)12 Examples (com.sx4.bot.annotations.command.Examples)12 Bson (org.bson.conversions.Bson)11 PagedResult (com.sx4.bot.paged.PagedResult)9 List (java.util.List)9 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)9 DefaultNumber (com.sx4.bot.annotations.argument.DefaultNumber)8 ImageRequest (com.sx4.bot.entities.image.ImageRequest)8 ImageUtility (com.sx4.bot.utility.ImageUtility)8 Collectors (java.util.stream.Collectors)8