Search in sources :

Example 16 with HttpCallback

use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.

the class HotCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "image url", endless = true, acceptEmpty = true) @ImageUrl String imageUrl) {
    Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("hot")).addQuery("image", imageUrl).build(event.getConfig().getImageWebserver());
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> ImageUtility.getImageMessage(event, response).queue());
}
Also used : ModuleCategory(com.sx4.bot.category.ModuleCategory) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest) HttpCallback(com.sx4.bot.http.HttpCallback) ImageUtility(com.sx4.bot.utility.ImageUtility) Sx4Command(com.sx4.bot.core.Sx4Command) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Permission(net.dv8tion.jda.api.Permission) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) Argument(com.jockie.bot.core.argument.Argument) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest)

Example 17 with HttpCallback

use of com.sx4.bot.http.HttpCallback 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 18 with HttpCallback

use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.

the class YouTubeCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) String query, @Option(value = "channel", description = "Only return a channel") boolean channel, @Option(value = "playlist", description = "Only return a playlist") boolean playlist, @Option(value = "video", description = "Only return a video") boolean video) {
    String type = channel ? "channel" : video ? "video" : playlist ? "playlist" : null;
    Request request = new Request.Builder().url(String.format("https://www.googleapis.com/youtube/v3/search?key=%s&part=snippet&maxResults=50&safeSearch=none&q=%s%s", event.getConfig().getYouTube(), URLEncoder.encode(query, StandardCharsets.UTF_8), type == null ? "" : "&type=" + type)).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        Document json = Document.parse(response.body().string());
        List<Document> items = json.getList("items", Document.class);
        if (items.isEmpty()) {
            event.replyFailure("I could not find any results").queue();
            return;
        }
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), items).setAuthor("YouTube Results", null, "https://media-thumbs.golden.com/4hBhjfnhOC6J3uJZglZG0quRsPU=/200x200/smart/golden-media.s3.amazonaws.com%2Ftopic_images%2F6c3fdb0966b049eba2b9c2331da224f0.png").setAutoSelect(true).setDisplayFunction(data -> {
            Document id = data.get("id", Document.class);
            String kind = id.getString("kind");
            return "[" + data.getEmbedded(List.of("snippet", "title"), String.class) + "](" + this.getUrlFromId(id) + ")" + " (" + StringUtility.title(kind.substring(kind.indexOf('#') + 1)) + ")";
        });
        paged.onSelect(select -> {
            Document result = select.getSelected();
            Document id = result.get("id", Document.class);
            Document snippet = result.get("snippet", Document.class);
            Document thumbnails = snippet.get("thumbnails", Document.class);
            ZonedDateTime uploadedAt = ZonedDateTime.parse(snippet.getString("publishedAt"));
            EmbedBuilder embed = new EmbedBuilder();
            embed.setColor(16711680);
            embed.setDescription(snippet.getString("description"));
            embed.setImage(thumbnails.getEmbedded(List.of("high", "url"), String.class));
            embed.setTitle(snippet.getString("title"), this.getUrlFromId(id));
            String kind = id.getString("kind");
            if (kind.equals("youtube#channel")) {
                embed.addField("Created At", uploadedAt.format(this.formatter), true);
            } else if (kind.equals("youtube#video")) {
                String state = snippet.getString("liveBroadcastContent");
                embed.addField("Uploaded By", "[" + snippet.getString("channelTitle") + "](https://www.youtube.com/channel/" + snippet.getString("channelId") + ")", true);
                embed.addField("Uploaded At", uploadedAt.format(this.formatter), true);
                embed.addField("State", state.equals("live") ? "Live Now" : state.equals("upcoming") ? "Scheduled" : "Uploaded", true);
                Request metaDataRequest = new Request.Builder().url("https://api.jockiemusic.com/v1/youtube/videos/" + id.getString("videoId") + "/metadata").build();
                event.reply(embed.build()).queue(message -> {
                    event.getHttpClient().newCall(metaDataRequest).enqueue((HttpCallback) metaDataResponse -> {
                        if (metaDataResponse.code() == 404) {
                            return;
                        }
                        Document data = Document.parse(metaDataResponse.body().string()).get("data", Document.class);
                        Document metaData = data.get("metadata", Document.class);
                        Document rating = metaData.get("rating", Document.class);
                        long likes = rating.get("likes", Number.class).longValue(), dislikes = rating.get("dislikes", Number.class).longValue();
                        double ratingPercent = ((double) likes / (likes + dislikes)) * 100D;
                        embed.addField("Duration", TimeUtility.getMusicTimeString(metaData.get("length", Number.class).longValue(), TimeUnit.MILLISECONDS), true);
                        embed.addField("Views", String.format("%,d", metaData.get("views", Number.class).longValue()), true);
                        embed.addField("Likes/Dislikes", String.format("%,d \\\uD83D\uDC4D\n%,d \\\uD83D\uDC4E", likes, dislikes), true);
                        embed.addField("Rating", NumberUtility.DEFAULT_DECIMAL_FORMAT.format(ratingPercent) + "%", true);
                        embed.setFooter("Views and Ratings last updated");
                        embed.setTimestamp(Instant.ofEpochSecond(data.get("lastUpdated", Number.class).longValue()));
                        message.editMessageEmbeds(embed.build()).queue();
                    });
                });
                return;
            } else {
                embed.addField("Uploaded By", "[" + snippet.getString("channelTitle") + "](https://www.youtube.com/channel/" + snippet.getString("channelId") + ")", true);
                embed.addField("Uploaded At", uploadedAt.format(this.formatter), true);
            }
            event.reply(embed.build()).queue();
        });
        paged.execute(event);
    });
}
Also used : Document(org.bson.Document) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) NumberUtility(com.sx4.bot.utility.NumberUtility) Permission(net.dv8tion.jda.api.Permission) ZonedDateTime(java.time.ZonedDateTime) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Instant(java.time.Instant) PagedResult(com.sx4.bot.paged.PagedResult) StandardCharsets(java.nio.charset.StandardCharsets) TimeUnit(java.util.concurrent.TimeUnit) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) List(java.util.List) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) DateTimeFormatter(java.time.format.DateTimeFormatter) Option(com.jockie.bot.core.option.Option) StringUtility(com.sx4.bot.utility.StringUtility) Argument(com.jockie.bot.core.argument.Argument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ZonedDateTime(java.time.ZonedDateTime) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) List(java.util.List) Document(org.bson.Document) PagedResult(com.sx4.bot.paged.PagedResult)

Example 19 with HttpCallback

use of com.sx4.bot.http.HttpCallback 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 HttpCallback

use of com.sx4.bot.http.HttpCallback 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) TextNode(org.jsoup.nodes.TextNode) 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) JSONObject(org.json.JSONObject) Matcher(java.util.regex.Matcher) XML(org.json.XML) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Element(org.jsoup.nodes.Element) 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) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) 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) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) 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)

Aggregations

HttpCallback (com.sx4.bot.http.HttpCallback)85 Request (okhttp3.Request)83 ModuleCategory (com.sx4.bot.category.ModuleCategory)68 Sx4Command (com.sx4.bot.core.Sx4Command)68 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)68 Permission (net.dv8tion.jda.api.Permission)67 Argument (com.jockie.bot.core.argument.Argument)63 Document (org.bson.Document)51 ImageRequest (com.sx4.bot.entities.image.ImageRequest)35 ImageUtility (com.sx4.bot.utility.ImageUtility)33 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)33 ImageUrl (com.sx4.bot.annotations.argument.ImageUrl)28 PagedResult (com.sx4.bot.paged.PagedResult)24 StandardCharsets (java.nio.charset.StandardCharsets)23 URLEncoder (java.net.URLEncoder)22 java.util (java.util)20 OffsetDateTime (java.time.OffsetDateTime)18 Collectors (java.util.stream.Collectors)18 Bson (org.bson.conversions.Bson)17 Command (com.jockie.bot.core.command.Command)16