Search in sources :

Example 1 with SteamGameCache

use of com.sx4.bot.cache.SteamGameCache in project Sx4 by sx4-discord-bot.

the class SteamCommand method game.

@Command(value = "game", description = "View information about a game on steam")
@CommandId(34)
@Examples({ "steam game Grand Theft Auto", "steam game 1293830", "steam game https://store.steampowered.com/app/1293830/Forza_Horizon_4/" })
@Cooldown(5)
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void game(Sx4CommandEvent event, @Argument(value = "query", endless = true, nullDefault = true) String query, @Option(value = "random", description = "Gets a random game") boolean random) {
    if (query == null && !random) {
        event.replyHelp().queue();
        return;
    }
    SteamGameCache cache = event.getBot().getSteamGameCache();
    if (cache.getGames().isEmpty()) {
        event.replyFailure("The steam cache is currently empty, try again").queue();
        return;
    }
    Matcher urlMatcher;
    List<Document> games;
    if (query == null) {
        List<Document> cacheGames = cache.getGames();
        games = List.of(cacheGames.get(event.getRandom().nextInt(cacheGames.size())));
    } else if (NumberUtility.isNumberUnsigned(query)) {
        games = List.of(new Document("appid", Integer.parseInt(query)));
    } else if ((urlMatcher = this.gamePattern.matcher(query)).matches()) {
        games = List.of(new Document("appid", Integer.parseInt(urlMatcher.group(1))));
    } else {
        games = cache.getGames(query);
        if (games.isEmpty()) {
            event.replyFailure("I could not find any games with that query").queue();
            return;
        }
    }
    PagedResult<Document> paged = new PagedResult<>(event.getBot(), games).setAuthor("Steam Search", null, "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png").setIncreasedIndex(true).setAutoSelect(true).setTimeout(60).setDisplayFunction(game -> game.getString("name"));
    paged.onSelect(select -> {
        Document game = select.getSelected();
        int appId = game.getInteger("appid");
        Request request = new Request.Builder().url("https://store.steampowered.com/api/appdetails?cc=gb&appids=" + appId).build();
        event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
            Document json = Document.parse(response.body().string()).get(String.valueOf(appId), Document.class);
            if (!json.getBoolean("success")) {
                event.replyFailure("Steam failed to get data for that game").queue();
                return;
            }
            List<MessageEmbed> embeds = new ArrayList<>();
            Document gameInfo = json.get("data", Document.class);
            String description = Jsoup.parse(gameInfo.getString("short_description")).text();
            String price;
            if (gameInfo.containsKey("price_overview")) {
                Document priceOverview = gameInfo.get("price_overview", Document.class);
                double initialPrice = priceOverview.getInteger("initial") / 100D, finalPrice = priceOverview.getInteger("final") / 100D;
                price = initialPrice == finalPrice ? String.format("£%,.2f", finalPrice) : String.format("~~£%,.2f~~ £%,.2f (-%d%%)", initialPrice, finalPrice, priceOverview.getInteger("discount_percent"));
            } else {
                price = gameInfo.getBoolean("is_free") ? "Free" : "Unknown";
            }
            EmbedBuilder embed = new EmbedBuilder();
            embed.setDescription(description);
            embed.setTitle(gameInfo.getString("name"), "https://store.steampowered.com/app/" + appId);
            embed.setAuthor("Steam", "https://steamcommunity.com", "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png");
            embed.setImage(gameInfo.getString("header_image"));
            embed.addField("Price", price, true);
            embed.setFooter("Developed by " + (gameInfo.containsKey("developers") ? String.join(", ", gameInfo.getList("developers", String.class)) : "Unknown"), null);
            Document releaseDate = gameInfo.get("release_date", Document.class);
            String date = releaseDate.getString("date");
            embed.addField("Release Date", String.format("%s%s", date.isBlank() ? "Unknown" : date, releaseDate.getBoolean("coming_soon") ? " (Coming Soon)" : ""), true);
            Object age = gameInfo.get("required_age");
            embed.addField("Required Age", age instanceof Integer ? ((int) age) == 0 ? "No Age Restriction" : String.valueOf((int) age) : (String) age, true);
            embed.addField("Recommendations", String.format("%,d", gameInfo.getEmbedded(List.of("recommendations", "total"), 0)), true);
            embed.addField("Supported Languages", gameInfo.containsKey("supported_languages") ? Jsoup.parse(gameInfo.getString("supported_languages")).text() : "Unknown", true);
            List<Document> genres = gameInfo.getList("genres", Document.class);
            embed.addField("Genres", genres == null ? "None" : genres.stream().map(genre -> genre.getString("description")).collect(Collectors.joining("\n")), true);
            embeds.add(embed.build());
            gameInfo.getList("screenshots", Document.class).stream().map(d -> d.getString("path_thumbnail")).limit(3).forEach(thumbnail -> {
                embeds.add(new MessageEmbed("https://store.steampowered.com/app/" + appId, null, null, EmbedType.RICH, null, Role.DEFAULT_COLOR_RAW, null, null, null, null, null, new MessageEmbed.ImageInfo(thumbnail, null, 0, 0), List.of()));
            });
            event.getChannel().sendMessageEmbeds(embeds).queue();
        });
    });
    paged.onTimeout(() -> event.reply("Response timed out :stopwatch:").queue());
    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) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Matcher(java.util.regex.Matcher) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) Document(org.bson.Document) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) SteamGameCache(com.sx4.bot.cache.SteamGameCache) JSONObject(org.json.JSONObject) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) Cooldown(com.jockie.bot.core.command.Command.Cooldown) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Aggregations

Argument (com.jockie.bot.core.argument.Argument)1 Command (com.jockie.bot.core.command.Command)1 Cooldown (com.jockie.bot.core.command.Command.Cooldown)1 Option (com.jockie.bot.core.option.Option)1 Projections (com.mongodb.client.model.Projections)1 BotPermissions (com.sx4.bot.annotations.command.BotPermissions)1 CommandId (com.sx4.bot.annotations.command.CommandId)1 Examples (com.sx4.bot.annotations.command.Examples)1 SteamGameCache (com.sx4.bot.cache.SteamGameCache)1 ModuleCategory (com.sx4.bot.category.ModuleCategory)1 Sx4Command (com.sx4.bot.core.Sx4Command)1 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)1 HttpCallback (com.sx4.bot.http.HttpCallback)1 PagedResult (com.sx4.bot.paged.PagedResult)1 HmacUtility (com.sx4.bot.utility.HmacUtility)1 NumberUtility (com.sx4.bot.utility.NumberUtility)1 StringUtility (com.sx4.bot.utility.StringUtility)1 URLEncoder (java.net.URLEncoder)1 StandardCharsets (java.nio.charset.StandardCharsets)1 InvalidKeyException (java.security.InvalidKeyException)1