Search in sources :

Example 16 with Argument

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

the class WarnCommand method set.

@Command(value = "set", description = "Set the amount of warns a user has")
@CommandId(242)
@Redirects({ "set warns", "set warnings" })
@Examples({ "warn set @Shea#6653 2", "warn set Shea#6653 0", "warn set 402557516728369153 1" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void set(Sx4CommandEvent event, @Argument(value = "user") Member member, @Argument(value = "warnings") int warnings) {
    if (member.canInteract(event.getMember())) {
        event.replyFailure("You cannot change the amount of warnings of someone higher or equal than your top role").queue();
        return;
    }
    Document warnData = event.getMongo().getGuildById(event.getGuild().getIdLong(), Projections.include("warn")).get("warn", MongoDatabase.EMPTY_DOCUMENT);
    boolean punishments = warnData.get("punishments", true);
    int maxWarning = punishments ? warnData.getList("config", Document.class, Warn.DEFAULT_CONFIG).stream().map(d -> d.getInteger("number")).max(Integer::compareTo).get() : Integer.MAX_VALUE;
    if (warnings > maxWarning) {
        event.replyFailure("The max amount of warnings you can give is **" + maxWarning + "**").queue();
        return;
    }
    Bson update = warnings == 0 ? Updates.unset("warnings") : Updates.combine(Updates.set("warnings", warnings), Updates.set("lastWarning", Clock.systemUTC().instant().getEpochSecond()));
    Bson filter = Filters.and(Filters.eq("userId", member.getIdLong()), Filters.eq("guildId", event.getGuild().getIdLong()));
    event.getMongo().updateWarnings(filter, update, new UpdateOptions().upsert(true)).whenComplete((result, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (result.getModifiedCount() == 0 && result.getUpsertedId() == null) {
            event.replyFailure("That user already had that amount of warnings").queue();
            return;
        }
        event.replySuccess("That user now has **" + warnings + "** warning" + (warnings == 1 ? "" : "s")).queue();
    });
}
Also used : Document(org.bson.Document) MarkdownSanitizer(net.dv8tion.jda.api.utils.MarkdownSanitizer) Command(com.jockie.bot.core.command.Command) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) ModAction(com.sx4.bot.entities.mod.action.ModAction) Member(net.dv8tion.jda.api.entities.Member) TimedArgument(com.sx4.bot.entities.argument.TimedArgument) PagedResult(com.sx4.bot.paged.PagedResult) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) TimeAction(com.sx4.bot.entities.mod.action.TimeAction) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) Duration(java.time.Duration) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) Reason(com.sx4.bot.entities.mod.Reason) com.mongodb.client.model(com.mongodb.client.model) com.sx4.bot.annotations.command(com.sx4.bot.annotations.command) Warn(com.sx4.bot.entities.mod.action.Warn) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) Action(com.sx4.bot.entities.mod.action.Action) Operators(com.sx4.bot.database.mongo.model.Operators) Sx4Command(com.sx4.bot.core.Sx4Command) NumberUtility(com.sx4.bot.utility.NumberUtility) ModUtility(com.sx4.bot.utility.ModUtility) CompletionException(java.util.concurrent.CompletionException) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) Clock(java.time.Clock) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) Comparator(java.util.Comparator) Document(org.bson.Document) Bson(org.bson.conversions.Bson) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 17 with Argument

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

the class SteamCommand method compare.

@Command(value = "compare", description = "Compare what games 2 steam accounts have in common")
@CommandId(279)
@Examples({ "steam compare dog cat", "steam compare https://steamcommunity.com/id/dog https://steamcommunity.com/id/cat" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void compare(Sx4CommandEvent event, @Argument(value = "first profile") String firstQuery, @Argument(value = "second profile", endless = true) String secondQuery) {
    String firstUrl = this.getProfileUrl(firstQuery), secondUrl = this.getProfileUrl(secondQuery);
    Request firstRequest = new Request.Builder().url(firstUrl + "games/?tab=all&xml=1").build();
    Request secondRequest = new Request.Builder().url(secondUrl + "games/?tab=all&xml=1").build();
    event.getHttpClient().newCall(firstRequest).enqueue((HttpCallback) firstResponse -> {
        JSONObject firstData = XML.toJSONObject(firstResponse.body().string()).getJSONObject("gamesList");
        if (firstData.has("error")) {
            event.replyFailure("The steam profile <https://steamcommunity.com/profiles/" + firstData.getLong("steamID64") + "> is private").queue();
            return;
        }
        event.getHttpClient().newCall(secondRequest).enqueue((HttpCallback) secondResponse -> {
            JSONObject secondData = XML.toJSONObject(secondResponse.body().string()).getJSONObject("gamesList");
            if (secondData.has("error")) {
                event.replyFailure("The steam profile <https://steamcommunity.com/profiles/" + secondData.getLong("steamID64") + "> is private").queue();
                return;
            }
            JSONArray firstGames = firstData.getJSONObject("games").getJSONArray("game"), secondGames = secondData.getJSONObject("games").getJSONArray("game");
            Map<Integer, String> commonGames = new HashMap<>();
            for (int x = 0; x < firstGames.length(); x++) {
                for (int y = 0; y < secondGames.length(); y++) {
                    JSONObject firstGame = firstGames.getJSONObject(x), secondGame = secondGames.getJSONObject(y);
                    if (firstGame.getInt("appID") == secondGame.getInt("appID")) {
                        commonGames.put(firstGame.getInt("appID"), firstGame.getString("name"));
                    }
                }
            }
            PagedResult<Map.Entry<Integer, String>> paged = new PagedResult<>(event.getBot(), new ArrayList<>(commonGames.entrySet())).setAuthor("Games In Common (" + commonGames.size() + ")", null, "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png").setPerPage(15).setIncreasedIndex(true).setDisplayFunction(d -> "[" + d.getValue() + "](https://store.steampowered.com/app/" + d.getKey() + ")");
            paged.execute(event);
        });
    });
}
Also used : Document(org.bson.Document) java.util(java.util) Command(com.jockie.bot.core.command.Command) Permission(net.dv8tion.jda.api.Permission) Projections(com.mongodb.client.model.Projections) CommandId(com.sx4.bot.annotations.command.CommandId) Cooldown(com.jockie.bot.core.command.Command.Cooldown) PagedResult(com.sx4.bot.paged.PagedResult) EmbedType(net.dv8tion.jda.api.entities.EmbedType) JSONObject(org.json.JSONObject) Matcher(java.util.regex.Matcher) Role(net.dv8tion.jda.api.entities.Role) XML(org.json.XML) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Option(com.jockie.bot.core.option.Option) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Argument(com.jockie.bot.core.argument.Argument) Request(okhttp3.Request) HmacUtility(com.sx4.bot.utility.HmacUtility) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) NumberUtility(com.sx4.bot.utility.NumberUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) Examples(com.sx4.bot.annotations.command.Examples) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) LocalDate(java.time.LocalDate) DateTimeFormatter(java.time.format.DateTimeFormatter) InvalidKeyException(java.security.InvalidKeyException) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Jsoup(org.jsoup.Jsoup) Pattern(java.util.regex.Pattern) StringUtility(com.sx4.bot.utility.StringUtility) JSONArray(org.json.JSONArray) SteamGameCache(com.sx4.bot.cache.SteamGameCache) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) JSONArray(org.json.JSONArray) JSONObject(org.json.JSONObject) 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 18 with Argument

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

the class WeatherCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) String query) {
    Request request = new Request.Builder().url(event.getConfig().getSearchWebserverUrl("weather") + "?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8)).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        if (response.code() == 404) {
            event.replyFailure("I could not find that location").queue();
            return;
        }
        Document document = Document.parse(response.body().string());
        if (!response.isSuccessful()) {
            StringBuilder builder = new StringBuilder("Command failed with status " + response.code());
            if (document.containsKey("message")) {
                builder.append(" with message `").append(document.getString("message")).append("`");
            }
            event.replyFailure(builder.toString()).queue();
            return;
        }
        Document now = document.get("now", Document.class);
        Document today = document.get("today", Document.class);
        int windDegrees = now.getInteger("wdir");
        Integer maxTemp = today.getInteger("max_temp");
        EmbedBuilder embed = new EmbedBuilder();
        embed.setAuthor(document.getString("location"), document.getString("url"), null);
        embed.setTitle(now.getString("phrase_32char"));
        embed.addField("Temperature", String.format("Maximum: %s°C\nCurrent: %d°C\nMinimum: %d°C", maxTemp == null ? "--" : maxTemp, now.getInteger("temp"), today.getInteger("min_temp")), true);
        embed.addBlankField(true);
        embed.addField("Wind", String.format("Direction: %d° (%s)\nSpeed: %d mph", windDegrees, Direction.getDirection(windDegrees).getName(), now.getInteger("wspd")), true);
        embed.addField("Humidity", now.getInteger("rh") + "%", true);
        embed.addBlankField(true);
        embed.addField("Precipitation", now.getInteger("pop") + "%", true);
        embed.setThumbnail(now.getString("icon"));
        embed.setFooter(now.getString("dow") + " " + OffsetDateTime.parse(now.getString("fcst_valid_local"), this.parseFormatter).format(this.formatter));
        event.reply(embed.build()).queue();
    });
}
Also used : Document(org.bson.Document) Request(okhttp3.Request) Arrays(java.util.Arrays) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) StandardCharsets(java.nio.charset.StandardCharsets) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) OffsetDateTime(java.time.OffsetDateTime) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) DateTimeFormatter(java.time.format.DateTimeFormatter) Comparator(java.util.Comparator) Argument(com.jockie.bot.core.argument.Argument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) Document(org.bson.Document)

Example 19 with Argument

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

the class ShortenCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "url") String url) {
    Request request = new Request.Builder().url("https://api-ssl.bitly.com/v4/shorten").post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Document("long_url", url).toJson())).addHeader("Authorization", "Bearer " + event.getConfig().getBitly()).addHeader("Content-Type", "application/json").build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        Document json = Document.parse(response.body().string());
        event.replyFormat("<" + json.getString("link") + ">").queue();
    });
}
Also used : Document(org.bson.Document) ModuleCategory(com.sx4.bot.category.ModuleCategory) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) MediaType(okhttp3.MediaType) Argument(com.jockie.bot.core.argument.Argument) RequestBody(okhttp3.RequestBody) Request(okhttp3.Request) Document(org.bson.Document)

Example 20 with Argument

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

the class PickaxeCommand method repair.

@Command(value = "repair", description = "Repair your current pickaxe with the material it is made from")
@CommandId(363)
@Examples({ "pickaxe repair 10", "pickaxe 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.PICKAXE.getId()));
    Document data = event.getMongo().getItem(filter, Projections.include("item"));
    if (data == null) {
        event.replyFailure("You do not have a pickaxe").queue();
        return;
    }
    Pickaxe pickaxe = Pickaxe.fromData(event.getBot().getEconomyManager(), data.get("item", Document.class));
    CraftItem item = pickaxe.getRepairItem();
    if (item == null) {
        event.replyFailure("That pickaxe is not repairable").queue();
        return;
    }
    int maxDurability = pickaxe.getMaxDurability() - pickaxe.getDurability();
    if (maxDurability <= 0) {
        event.replyFailure("Your pickaxe 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 pickaxe by **" + maxDurability + "** durability :no_entry:").queue();
            return;
        }
        durability = amount;
    }
    int itemCount = (int) Math.ceil((((double) pickaxe.getPrice() / item.getPrice()) / pickaxe.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 pickaxe 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", pickaxe.getDurability()), Operators.add("$item.durability", durability), "$item.durability")));
            return event.getMongo().updateItem(Filters.and(Filters.eq("item.id", pickaxe.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 pickaxe " + event.getConfig().getFailureEmote()).queue();
                return;
            }
            if (result.getMatchedCount() == 0) {
                e.reply("The durability of your pickaxe has changed " + event.getConfig().getFailureEmote()).queue();
                return;
            }
            e.reply("You just repaired your pickaxe 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) Pickaxe(com.sx4.bot.entities.economy.item.Pickaxe) 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) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) Pickaxe(com.sx4.bot.entities.economy.item.Pickaxe) 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)

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