Search in sources :

Example 1 with Lowercase

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

the class CSGOSkinCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "skin name", endless = true) String query, @Option(value = "sort", description = "You can sort by `price`, `age`, `deal`, `popularity`, `wear or `discount`") Sort sort, @Option(value = "reverse", description = "Reverse the order of the sorting") boolean reverse, @Option(value = "wear", description = "What wear you would like to filter by, options are `fn`, `mw`, `ft`, `ww` and `bs`") Wear wear, @Option(value = "phase", description = "Filter by phase of a knife") @Lowercase String phase, @Option(value = "currency", description = "What currency to use for the prices of items") @Uppercase @DefaultString("GBP") String currency) {
    SkinPortManager manager = event.getBot().getSkinPortManager();
    String cookie = manager.getCSRFCookie();
    double rate = manager.getCurrencyRate(currency);
    if (rate == -1D) {
        event.replyFailure("SkinPort does not support that currency").queue();
        return;
    }
    FormBody body = new FormBody.Builder().add("prefix", query).add("_csrf", manager.getCSRFToken()).build();
    Request suggestionRequest = new Request.Builder().url("https://skinport.com/api/suggestions/730").post(body).addHeader("Content-Type", "application/x-www-form-urlencoded").addHeader("Cookie", cookie).build();
    event.getHttpClient().newCall(suggestionRequest).enqueue((HttpCallback) suggestionResponse -> {
        Document data = Document.parse(suggestionResponse.body().string());
        List<Document> variants = data.getList("suggestions", Document.class);
        if (variants.isEmpty()) {
            event.replyFailure("I could not find any skins from that query").queue();
            return;
        }
        PagedResult<Document> suggestions = new PagedResult<>(event.getBot(), variants).setAuthor("SkinPort", null, "https://skinport.com/static/favicon-32x32.png").setDisplayFunction(suggestion -> {
            String type = suggestion.getString("type");
            return (type == null ? "" : type + " | ") + suggestion.getString("item");
        }).setIndexed(true).setAutoSelect(true);
        suggestions.onSelect(select -> {
            Document selected = select.getSelected();
            String type = selected.getString("type");
            StringBuilder url = new StringBuilder("https://skinport.com/api/browse/730?cat=" + URLEncoder.encode(selected.getString("category"), StandardCharsets.UTF_8) + (type != null ? "&type=" + URLEncoder.encode(type, StandardCharsets.UTF_8) : "") + "&item=" + URLEncoder.encode(selected.getString("item"), StandardCharsets.UTF_8));
            if (wear != null) {
                url.append("&exterior=").append(wear.getId());
            }
            if (sort != null) {
                url.append("&sort=").append(sort.getIdentifier()).append("&order=").append(reverse ? "desc" : "asc");
            }
            if (phase != null) {
                int phaseId = this.phases.getOrDefault(phase, -1);
                if (phaseId != -1) {
                    url.append("&phase=").append(phaseId);
                }
            }
            Request request = new Request.Builder().url(url.toString()).addHeader("Cookie", cookie).build();
            event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
                Document skinData = Document.parse(response.body().string());
                List<Document> items = skinData.getList("items", Document.class);
                if (items.isEmpty()) {
                    event.replyFailure("There are no skins listed with those filters").queue();
                    return;
                }
                PagedResult<Document> skins = new PagedResult<>(event.getBot(), items).setPerPage(1).setSelect().setCustomFunction(page -> {
                    List<MessageEmbed> embeds = new ArrayList<>();
                    EmbedBuilder embed = new EmbedBuilder();
                    embed.setFooter("Skin " + page.getPage() + "/" + page.getMaxPage());
                    page.forEach((d, index) -> {
                        double steamPrice = (d.getInteger("suggestedPrice") / 100D) * rate;
                        double price = (d.getInteger("salePrice") / 100D) * rate;
                        double increase = steamPrice - price;
                        embed.setTitle(d.getString("marketName"), "https://skinport.com/item/" + d.getString("url") + "/" + d.getInteger("saleId"));
                        embed.setImage("https://community.cloudflare.steamstatic.com/economy/image/" + d.getString("image"));
                        embed.addField("Price", String.format("~~%,.2f %s~~ %,.2f %2$s (%s%.2f%%)", steamPrice, currency, price, increase > 0 ? "-" : "+", Math.abs((increase / steamPrice) * 100D)), true);
                        String exterior = d.getString("exterior");
                        if (exterior != null) {
                            embed.addField("Wear", exterior, true);
                            embed.addField("Float", String.format("%.3f", d.get("wear", Number.class).doubleValue()), true);
                        }
                        String lock = d.getString("lock");
                        embed.addField("Trade Locked", lock == null ? "No" : this.formatter.parse(Duration.between(OffsetDateTime.now(ZoneOffset.UTC), OffsetDateTime.parse(lock))), true);
                        embeds.add(embed.build());
                        if (d.getBoolean("canHaveScreenshots")) {
                            embed.setImage("https://cdn.skinport.com/images/screenshots/" + d.getInteger("assetId") + "/backside_512x384.png");
                            embeds.add(embed.build());
                            embed.setImage("https://cdn.skinport.com/images/screenshots/" + d.getInteger("assetId") + "/playside_512x384.png");
                            embeds.add(embed.build());
                        }
                    });
                    return new MessageBuilder().setEmbeds(embeds);
                });
                skins.execute(event);
            });
        });
        suggestions.execute(event);
    });
}
Also used : Document(org.bson.Document) Uppercase(com.sx4.bot.annotations.argument.Uppercase) HashMap(java.util.HashMap) SkinPortManager(com.sx4.bot.managers.SkinPortManager) PagedResult(com.sx4.bot.paged.PagedResult) ArrayList(java.util.ArrayList) FormBody(okhttp3.FormBody) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) Duration(java.time.Duration) Map(java.util.Map) Option(com.jockie.bot.core.option.Option) TimeFormatter(com.sx4.bot.entities.utility.TimeFormatter) ZoneOffset(java.time.ZoneOffset) Argument(com.jockie.bot.core.argument.Argument) Lowercase(com.sx4.bot.annotations.argument.Lowercase) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) StandardCharsets(java.nio.charset.StandardCharsets) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) List(java.util.List) OffsetDateTime(java.time.OffsetDateTime) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) DefaultString(com.sx4.bot.annotations.argument.DefaultString) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) FormBody(okhttp3.FormBody) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) ArrayList(java.util.ArrayList) DefaultString(com.sx4.bot.annotations.argument.DefaultString) Document(org.bson.Document) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) SkinPortManager(com.sx4.bot.managers.SkinPortManager) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) ArrayList(java.util.ArrayList) List(java.util.List) PagedResult(com.sx4.bot.paged.PagedResult)

Example 2 with Lowercase

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

the class RedditCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "subreddit") String subreddit, @Option(value = "sort", description = "What to sort the subreddit by") @Options({ "new", "hot", "top" }) @DefaultString("hot") @Lowercase String sort, @Option(value = "time", description = "If sort is top will choose the top posts after the set amount of time") @Options({ "day", "week", "month", "year", "all" }) @DefaultString("day") @Lowercase String time, @Option(value = "limit", description = "How many posts to show") @DefaultNumber(25) @Limit(min = 1, max = 100) int limit) {
    Request request = new Request.Builder().url("https://reddit.com/r/" + subreddit + "/" + sort + ".json?t=" + time + "&limit=" + limit).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        if (response.code() == 302 || response.code() == 404) {
            event.replyFailure("I could not find that subreddit").queue();
            return;
        }
        List<Document> posts = Document.parse(response.body().string()).getEmbedded(List.of("data", "children"), Collections.emptyList());
        posts = posts.stream().filter(post -> {
            if (!event.getTextChannel().isNSFW()) {
                return !post.getEmbedded(List.of("data", "over_18"), false);
            }
            return true;
        }).map(post -> post.get("data", Document.class)).collect(Collectors.toList());
        if (posts.isEmpty()) {
            event.replyFailure("I could not find any posts with those filters").queue();
            return;
        }
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), posts).setPerPage(1).setSelect().setCustomFunction(page -> {
            MessageBuilder builder = new MessageBuilder();
            EmbedBuilder embed = new EmbedBuilder().setTitle("Page " + page.getPage() + "/" + page.getMaxPage());
            page.forEach((data, index) -> {
                String url = "https://reddit.com" + data.getString("permalink");
                embed.setFooter(data.getString("subreddit_name_prefixed") + " | Upvotes: " + data.getInteger("ups"));
                embed.setAuthor(StringUtility.limit(data.getString("title"), 50, "..."), url, "http://i.imgur.com/sdO8tAw.png");
                String postHint = data.getString("post_hint");
                if (postHint != null && postHint.equals("image")) {
                    embed.setImage(data.getString("url"));
                } else if (postHint != null && postHint.equals("hosted:video")) {
                    embed.setImage(data.getString("thumbnail"));
                    builder.setContent("<" + data.getEmbedded(List.of("media", "reddit_video", "fallback_url"), String.class) + ">");
                } else if (postHint != null && postHint.equals("rich:video")) {
                    embed.setImage(data.getEmbedded(List.of("media", "oembed", "thumbnail"), String.class));
                    builder.setContent("<" + data.getEmbedded(List.of("secure_media_embed", "media_domain_url"), String.class) + ">");
                }
                if (data.containsKey("selftext")) {
                    embed.setDescription(StringUtility.limit(data.getString("selftext"), MessageEmbed.DESCRIPTION_MAX_LENGTH, "... [Read more](" + url + ")"));
                }
            });
            return builder.setEmbeds(embed.build());
        });
        paged.execute(event);
    });
}
Also used : Document(org.bson.Document) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) PagedResult(com.sx4.bot.paged.PagedResult) Collectors(java.util.stream.Collectors) com.sx4.bot.annotations.argument(com.sx4.bot.annotations.argument) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Option(com.jockie.bot.core.option.Option) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) StringUtility(com.sx4.bot.utility.StringUtility) Collections(java.util.Collections) Argument(com.jockie.bot.core.argument.Argument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Request(okhttp3.Request) List(java.util.List) PagedResult(com.sx4.bot.paged.PagedResult)

Aggregations

Argument (com.jockie.bot.core.argument.Argument)2 Option (com.jockie.bot.core.option.Option)2 ModuleCategory (com.sx4.bot.category.ModuleCategory)2 Sx4Command (com.sx4.bot.core.Sx4Command)2 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)2 HttpCallback (com.sx4.bot.http.HttpCallback)2 PagedResult (com.sx4.bot.paged.PagedResult)2 List (java.util.List)2 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)2 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)2 MessageEmbed (net.dv8tion.jda.api.entities.MessageEmbed)2 Request (okhttp3.Request)2 Document (org.bson.Document)2 com.sx4.bot.annotations.argument (com.sx4.bot.annotations.argument)1 DefaultString (com.sx4.bot.annotations.argument.DefaultString)1 Lowercase (com.sx4.bot.annotations.argument.Lowercase)1 Uppercase (com.sx4.bot.annotations.argument.Uppercase)1 TimeFormatter (com.sx4.bot.entities.utility.TimeFormatter)1 SkinPortManager (com.sx4.bot.managers.SkinPortManager)1 StringUtility (com.sx4.bot.utility.StringUtility)1