Search in sources :

Example 51 with PagedResult

use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.

the class GiveawayCommand method list.

@Command(value = "list", description = "Lists all the giveaways which have happened in the server")
@CommandId(52)
@Examples({ "giveaway list" })
public void list(Sx4CommandEvent event) {
    List<Document> giveaways = event.getMongo().getGiveaways(Filters.eq("guildId", event.getGuild().getIdLong())).into(new ArrayList<>());
    if (giveaways.isEmpty()) {
        event.replyFailure("No giveaways have been setup in this server").queue();
        return;
    }
    PagedResult<Document> paged = new PagedResult<>(event.getBot(), giveaways).setAuthor("Giveaways", null, event.getGuild().getIconUrl()).setDisplayFunction(data -> {
        long endAt = data.getLong("endAt"), timeNow = Clock.systemUTC().instant().getEpochSecond();
        return data.getLong("messageId") + " - " + (endAt - timeNow < 0 ? "Ended" : TimeUtility.LONG_TIME_FORMATTER.parse(endAt - timeNow));
    });
    paged.onSelect(select -> {
        ShardManager shardManager = event.getShardManager();
        Document data = select.getSelected();
        List<Long> winners = data.getList("winners", Long.class, Collections.emptyList());
        String winnersString = winners.isEmpty() ? "None" : winners.stream().map(shardManager::getUserById).filter(Objects::nonNull).map(User::getAsMention).collect(Collectors.joining(", "));
        event.replyFormat("**Giveaway %d**\nItem: %s\nWinner%s: %s\nDuration: %s", data.getLong("messageId"), data.getString("item"), winners.size() == 1 ? "" : "s", winnersString, TimeUtility.LONG_TIME_FORMATTER.parse(data.getLong("duration"))).queue();
    });
    paged.execute(event);
}
Also used : User(net.dv8tion.jda.api.entities.User) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) PagedResult(com.sx4.bot.paged.PagedResult) 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 52 with PagedResult

use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.

the class LoggerCommand method list.

@Command(value = "list", description = "List and get info about loggers in the current server")
@CommandId(458)
@Examples({ "logger list" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void list(Sx4CommandEvent event, @Argument(value = "channel", endless = true, nullDefault = true) TextChannel channel) {
    Bson filter = channel == null ? Filters.eq("guildId", event.getGuild().getIdLong()) : Filters.eq("channelId", channel.getIdLong());
    List<Document> loggers = event.getMongo().getLoggers(filter, MongoDatabase.EMPTY_DOCUMENT).into(new ArrayList<>());
    if (loggers.isEmpty()) {
        event.replyFailure(channel == null ? "There are not any loggers setup" : "There is not a logger setup in " + channel.getAsMention()).queue();
        return;
    }
    PagedResult<Document> paged = new PagedResult<>(event.getBot(), loggers).setAuthor("Loggers", null, event.getGuild().getIconUrl()).setAutoSelect(true).setDisplayFunction(data -> "<#" + data.getLong("channelId") + ">");
    paged.onSelect(select -> {
        Document data = select.getSelected();
        EnumSet<LoggerEvent> events = LoggerEvent.getEvents(data.get("events", LoggerEvent.ALL));
        PagedResult<LoggerEvent> loggerPaged = new PagedResult<>(event.getBot(), new ArrayList<>(events)).setSelect().setPerPage(20).setCustomFunction(page -> {
            EmbedBuilder embed = new EmbedBuilder().setAuthor("Logger Settings", null, event.getGuild().getIconUrl()).setTitle("Page " + page.getPage() + "/" + page.getMaxPage()).setFooter(PagedResult.DEFAULT_FOOTER_TEXT).addField("Status", data.getBoolean("enabled", true) ? "Enabled" : "Disabled", true).addField("Channel", "<#" + data.getLong("channelId") + ">", true);
            StringJoiner content = new StringJoiner("\n");
            page.forEach((loggerEvent, index) -> content.add(loggerEvent.name()));
            embed.addField("Enabled Events", content.toString(), false);
            return new MessageBuilder().setEmbeds(embed.build());
        });
        loggerPaged.execute(event);
    });
    paged.execute(event);
}
Also used : LoggerEvent(com.sx4.bot.entities.management.LoggerEvent) Document(org.bson.Document) Bson(org.bson.conversions.Bson) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 53 with PagedResult

use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.

the class ReminderCommand method remove.

@Command(value = "remove", aliases = { "delete" }, description = "Remove a reminder from being notified about")
@CommandId(154)
@Examples({ "reminder remove 5ec67a3b414d8776950f0eee" })
public void remove(Sx4CommandEvent event, @Argument(value = "id", nullDefault = true) ObjectId id) {
    if (id == null) {
        if (!event.getBot().getConnectionHandler().isReady()) {
            event.replyFailure("You cannot view reminders while the bot is starting up").queue();
            return;
        }
        List<Document> reminders = event.getMongo().getReminders(Filters.eq("userId", event.getAuthor().getIdLong()), Projections.include("reminder", "remindAt")).into(new ArrayList<>());
        if (reminders.isEmpty()) {
            event.replyFailure("You do not have any active reminders").queue();
            return;
        }
        long now = Clock.systemUTC().instant().getEpochSecond();
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), reminders).setAuthor("Reminders", null, event.getAuthor().getEffectiveAvatarUrl()).setPerPage(10).setIndexed(true).setDisplayFunction(data -> StringUtility.limit(data.getString("reminder"), 150) + " in `" + TimeUtility.LONG_TIME_FORMATTER.parse(data.getLong("remindAt") - now) + "`");
        paged.onSelect(select -> {
            ObjectId selected = select.getSelected().getObjectId("_id");
            event.getMongo().deleteReminder(Filters.eq("_id", selected)).whenComplete((result, exception) -> {
                if (ExceptionUtility.sendExceptionally(event, exception)) {
                    return;
                }
                if (result.getDeletedCount() == 0) {
                    event.replyFailure("You do not have a reminder with that id").queue();
                    return;
                }
                event.getBot().getReminderManager().deleteExecutor(selected);
                event.replySuccess("You will no longer be reminded about that reminder").queue();
            });
        });
        paged.execute(event);
    } else {
        event.getMongo().deleteReminder(Filters.and(Filters.eq("_id", id), Filters.eq("userId", event.getAuthor().getIdLong()))).whenComplete((result, exception) -> {
            if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            if (result.getDeletedCount() == 0) {
                event.replyFailure("You do not have a reminder with that id").queue();
                return;
            }
            event.getBot().getReminderManager().deleteExecutor(id);
            event.replySuccess("You will no longer be reminded about that reminder").queue();
        });
    }
}
Also used : ObjectId(org.bson.types.ObjectId) Document(org.bson.Document) PagedResult(com.sx4.bot.paged.PagedResult) 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 54 with PagedResult

use of com.sx4.bot.paged.PagedResult 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)

Example 55 with PagedResult

use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.

the class SteamCommand method game.

@Command(value = "profile", description = "Look up information about a steam profile")
@CommandId(212)
@Examples({ "steam profile dog", "steam profile https://steamcommunity.com/id/dog" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void game(Sx4CommandEvent event, @Argument(value = "query", endless = true, nullDefault = true) String query) {
    List<Document> profiles;
    if (query == null) {
        List<Document> connections = event.getMongo().getUserById(event.getAuthor().getIdLong(), Projections.include("connections.steam")).getEmbedded(List.of("connections", "steam"), Collections.emptyList());
        if (connections.isEmpty()) {
            event.replyFailure("You do not have a steam account linked, use `steam connect` to link an account or provide an argument to search").queue();
            return;
        }
        profiles = connections.stream().map(data -> data.append("url", "https://steamcommunity.com/profiles/" + data.getLong("id"))).collect(Collectors.toList());
    } else {
        profiles = List.of(new Document("url", this.getProfileUrl(query)));
    }
    PagedResult<Document> paged = new PagedResult<>(event.getBot(), profiles).setAutoSelect(true).setAuthor("Steam Profiles", null, "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png").setDisplayFunction(data -> "[" + data.getString("name") + "](" + data.getString("url") + ")");
    paged.onSelect(select -> {
        String url = select.getSelected().getString("url");
        Request request = new Request.Builder().url(url + "?xml=1").build();
        event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
            JSONObject json = XML.toJSONObject(response.body().string());
            if (json.has("response")) {
                event.replyFailure("I could not find that steam user").queue();
                return;
            }
            JSONObject profile = json.getJSONObject("profile");
            if (profile.getInt("visibilityState") == 1) {
                event.replyFailure("That profile is private").queue();
                return;
            }
            JSONObject mostPlayedGames = profile.optJSONObject("mostPlayedGames");
            JSONArray gamesArray = mostPlayedGames == null ? new JSONArray() : mostPlayedGames.optJSONArray("mostPlayedGame");
            if (gamesArray == null) {
                gamesArray = new JSONArray().put(mostPlayedGames.getJSONObject("mostPlayedGame"));
            }
            double hours = 0D;
            StringBuilder gamesString = new StringBuilder();
            for (int i = 0; i < gamesArray.length(); i++) {
                JSONObject game = gamesArray.getJSONObject(i);
                hours += game.getDouble("hoursPlayed");
                gamesString.append(String.format("[%s](%s) - **%.1f** hours\n", game.getString("gameName"), game.getString("gameLink"), game.getDouble("hoursPlayed")));
            }
            String stateMessage = profile.getString("stateMessage");
            String location = profile.getString("location");
            String realName = profile.getString("realname");
            EmbedBuilder embed = new EmbedBuilder();
            embed.setAuthor(profile.getString("steamID"), url, profile.getString("avatarFull"));
            embed.setDescription(Jsoup.parse(profile.getString("summary")).text());
            embed.setFooter("ID: " + profile.getLong("steamID64"));
            embed.setThumbnail(profile.getString("avatarFull"));
            embed.addField("Real Name", realName.isBlank() ? "None Given" : realName, true);
            embed.addField("Created At", LocalDate.parse(profile.getString("memberSince"), DateTimeFormatter.ofPattern("LLLL d, yyyy")).format(this.formatter), true);
            embed.addField("Status", StringUtility.title(profile.getString("onlineState")), true);
            embed.addField("State Message", Jsoup.parse(stateMessage).text(), true);
            embed.addField("Vac Bans", String.valueOf(profile.getInt("vacBanned")), true);
            if (!location.isBlank()) {
                embed.addField("Location", location, true);
            }
            if (hours != 0) {
                gamesString.append(String.format("\nTotal - **%.1f** hours", hours));
                embed.addField("Games Played (2 Weeks)", gamesString.toString(), false);
            }
            event.reply(embed.build()).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) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) JSONObject(org.json.JSONObject) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) JSONArray(org.json.JSONArray) Document(org.bson.Document) 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

Sx4Command (com.sx4.bot.core.Sx4Command)54 PagedResult (com.sx4.bot.paged.PagedResult)50 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)43 Document (org.bson.Document)43 Command (com.jockie.bot.core.command.Command)41 CommandId (com.sx4.bot.annotations.command.CommandId)35 Examples (com.sx4.bot.annotations.command.Examples)33 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)32 ModuleCategory (com.sx4.bot.category.ModuleCategory)26 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)26 User (net.dv8tion.jda.api.entities.User)26 Argument (com.jockie.bot.core.argument.Argument)25 Bson (org.bson.conversions.Bson)23 Permission (net.dv8tion.jda.api.Permission)22 BotPermissions (com.sx4.bot.annotations.command.BotPermissions)20 List (java.util.List)19 ArrayList (java.util.ArrayList)18 HttpCallback (com.sx4.bot.http.HttpCallback)15 Request (okhttp3.Request)15 Collectors (java.util.stream.Collectors)13