Search in sources :

Example 31 with PagedResult

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

the class GoogleImageCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) String query) {
    boolean nsfw = event.getTextChannel().isNSFW();
    event.getBot().getGoogleCache().retrieveResultsByQuery(query, true, nsfw).whenComplete((results, exception) -> {
        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
        if (cause instanceof ForbiddenException) {
            event.replyFailure(cause.getMessage()).queue();
            return;
        }
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        String googleUrl = "https://google.com/search?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8) + "&tbm=isch" + (nsfw ? "" : "&safe=active");
        PagedResult<GoogleSearchResult> paged = new PagedResult<>(event.getBot(), results).setIndexed(false).setPerPage(4).setCustomFunction(page -> {
            List<MessageEmbed> embeds = new ArrayList<>();
            page.forEach((result, index) -> {
                EmbedBuilder embed = new EmbedBuilder().setTitle("Page " + page.getPage() + "/" + page.getMaxPage(), googleUrl).setAuthor("Google", googleUrl, "http://i.imgur.com/G46fm8J.png").setFooter(PagedResult.DEFAULT_FOOTER_TEXT).setImage(result.getLink());
                embeds.add(embed.build());
            });
            return new MessageBuilder().setEmbeds(embeds);
        });
        paged.execute(event);
    });
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) GoogleSearchResult(com.sx4.bot.cache.GoogleSearchCache.GoogleSearchResult) ArrayList(java.util.ArrayList) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) CompletionException(java.util.concurrent.CompletionException)

Example 32 with PagedResult

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

the class ReputationCommand method leaderboard.

@Command(value = "leaderboard", aliases = { "lb" }, description = "View the leaderboard for reputation across the bot")
@CommandId(421)
@Redirects({ "leaderboard reputation", "lb rep", "lb reputation", "leaderboard rep" })
@Examples({ "reputation leaderboard", "reputation leaderboard --server" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void leaderboard(Sx4CommandEvent event, @Option(value = "server", aliases = { "guild" }, description = "View the leaderboard with a server filter") boolean guild) {
    List<Bson> pipeline = List.of(Aggregates.project(Projections.computed("reputation", "$reputation.amount")), Aggregates.match(Filters.exists("reputation")), Aggregates.sort(Sorts.descending("reputation")));
    event.getMongo().aggregateUsers(pipeline).whenComplete((documents, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        List<Map.Entry<User, Integer>> users = new ArrayList<>();
        AtomicInteger userIndex = new AtomicInteger(-1);
        int i = 0;
        for (Document data : documents) {
            User user = event.getShardManager().getUserById(data.getLong("_id"));
            if (user == null) {
                continue;
            }
            if (!event.getGuild().isMember(user) && guild) {
                continue;
            }
            i++;
            users.add(Map.entry(user, data.getInteger("reputation")));
            if (user.getIdLong() == event.getAuthor().getIdLong()) {
                userIndex.set(i);
            }
        }
        if (users.isEmpty()) {
            event.replyFailure("There are no users which fit into this leaderboard").queue();
            return;
        }
        PagedResult<Map.Entry<User, Integer>> paged = new PagedResult<>(event.getBot(), users).setPerPage(10).setCustomFunction(page -> {
            int rank = userIndex.get();
            EmbedBuilder embed = new EmbedBuilder().setTitle("Reputation Leaderboard").setFooter(event.getAuthor().getName() + "'s Rank: " + (rank == -1 ? "N/A" : NumberUtility.getSuffixed(rank)) + " | Page " + page.getPage() + "/" + page.getMaxPage(), event.getAuthor().getEffectiveAvatarUrl());
            page.forEach((entry, index) -> embed.appendDescription(String.format("%d. `%s` - %,d reputation\n", index + 1, MarkdownSanitizer.escape(entry.getKey().getAsTag()), entry.getValue())));
            return new MessageBuilder().setEmbeds(embed.build());
        });
        paged.execute(event);
    });
}
Also used : User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Document(org.bson.Document) Bson(org.bson.conversions.Bson) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PagedResult(com.sx4.bot.paged.PagedResult) Redirects(com.sx4.bot.annotations.command.Redirects) 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 33 with PagedResult

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

the class CSGOSkinCommand method skinBaron.

public void skinBaron(Sx4CommandEvent event, @Argument(value = "skin name", endless = true, nullDefault = true) String query, @Option(value = "sort", description = "You can sort by `expensive`, `cheapest`, `best_deal`, `newest`, `rarest`, `best_float` or `popularity`") Sort sort, @Option(value = "wear", description = "What wear you would like to filter by, options are `fn`, `mw`, `ft`, `ww` and `bs`") Wear wear) {
    Request suggestionRequest = new Request.Builder().url("https://skinbaron.de/api/v2/Browsing/QuickSearch?variantName=" + URLEncoder.encode(query, StandardCharsets.UTF_8) + "&appId=730&language=en").build();
    event.getHttpClient().newCall(suggestionRequest).enqueue((HttpCallback) suggestionResponse -> {
        Document data = Document.parse(suggestionResponse.body().string());
        List<Document> variants = data.getList("variants", 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("SkinBaron", null, "https://skinbaron.de/favicon.png").setDisplayFunction(suggestion -> suggestion.getString("variantName")).setIndexed(true).setAutoSelect(true);
        suggestions.onSelect(select -> {
            Document selected = select.getSelected();
            StringBuilder url = new StringBuilder("https://skinbaron.de/api/v2/Browsing/FilterOffers?appId=730&language=en&otherCurrency=GBP&variantId=" + selected.getInteger("id") + "&sort=" + (sort == null ? Sort.DEAL : sort).getIdentifier());
            if (wear != null) {
                url.append("&wf=").append(wear.getId());
            }
            Request request = new Request.Builder().url(url.toString()).build();
            event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
                Document skinData = Document.parse(response.body().string());
                List<Document> offers = skinData.getList("aggregatedMetaOffers", Document.class);
                if (offers.isEmpty()) {
                    event.replyFailure("There are no skins listed with those filters").queue();
                    return;
                }
                PagedResult<Document> skins = new PagedResult<>(event.getBot(), offers).setPerPage(1).setSelect().setCustomFunction(page -> {
                    EmbedBuilder embed = new EmbedBuilder();
                    embed.setFooter("Skin " + page.getPage() + "/" + page.getMaxPage());
                    page.forEach((d, index) -> {
                        Document skin = d.containsKey("singleOffer") ? d.get("singleOffer", Document.class) : d.get("variant", Document.class);
                        Number steamPrice = d.get("steamMarketPrice", Number.class);
                        String priceString;
                        if (skin.containsKey("itemPrice")) {
                            double price = skin.get("itemPrice", Number.class).doubleValue();
                            if (steamPrice == null) {
                                priceString = String.format("£%,.2f", price);
                            } else {
                                double increase = price - steamPrice.doubleValue();
                                priceString = String.format("~~£%,.2f~~ £%,.2f (%.2f%%)", steamPrice.doubleValue(), price, (increase / (increase > 0 ? steamPrice.doubleValue() : price)) * 100D);
                            }
                        } else {
                            priceString = String.format("£%,.2f", steamPrice.doubleValue());
                        }
                        int tradeLockHours = skin.getInteger("tradeLockHoursLeft", 0);
                        embed.setTitle(skin.getString("localizedName") + (skin.containsKey("statTrakString") ? " (StatTrak)" : ""), "https://skinbaron.de" + d.getString("offerLink"));
                        embed.setImage(skin.getString("imageUrl"));
                        embed.addField("Price", priceString, true);
                        String wearName = skin.getString("localizedExteriorName");
                        if (wearName != null) {
                            embed.addField("Wear", wearName, true);
                            embed.addField("Float", String.format("%.4f", skin.get("wearPercent", Number.class).doubleValue() / 100D), true);
                        }
                        embed.addField("Trade Locked", tradeLockHours == 0 ? "No" : "Yes (" + this.formatter.parse(Duration.ofHours(tradeLockHours)) + ")", true);
                    });
                    return new MessageBuilder().setEmbeds(embed.build());
                });
                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) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) DefaultString(com.sx4.bot.annotations.argument.DefaultString) Document(org.bson.Document) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) ArrayList(java.util.ArrayList) List(java.util.List) PagedResult(com.sx4.bot.paged.PagedResult)

Example 34 with PagedResult

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

the class GameCommand method list.

@Command(value = "list", aliases = { "game list", "game list @Shea#6653", "game list Shea" }, description = "Lists basic info on all games a user has played on Sx4")
@CommandId(297)
@Redirects({ "games" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void list(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
    User user = member == null ? event.getAuthor() : member.getUser();
    List<Document> games = event.getMongo().getGames(Filters.eq("userId", user.getIdLong()), Projections.include("type", "state")).into(new ArrayList<>());
    if (games.isEmpty()) {
        event.replyFailure("That user has not played any games yet").queue();
        return;
    }
    PagedResult<Document> paged = new PagedResult<>(event.getBot(), games).setAuthor("Game List", null, user.getEffectiveAvatarUrl()).setIndexed(false).setPerPage(15).setSelect().setDisplayFunction(game -> "`" + GameType.fromId(game.getInteger("type")).getName() + "` - " + StringUtility.title(GameState.fromId(game.getInteger("state")).name()));
    paged.execute(event);
}
Also used : User(net.dv8tion.jda.api.entities.User) Document(org.bson.Document) Redirects(com.sx4.bot.annotations.command.Redirects) 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)

Example 35 with PagedResult

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

the class YouTubeNotificationCommand method list.

@Command(value = "list", description = "View all the notifications you have setup throughout your server")
@CommandId(165)
@Examples({ "youtube notification list" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void list(Sx4CommandEvent event) {
    List<Document> notifications = event.getMongo().getYouTubeNotifications(Filters.eq("guildId", event.getGuild().getIdLong()), Projections.include("uploaderId", "channelId", "message")).into(new ArrayList<>());
    if (notifications.isEmpty()) {
        event.replyFailure("You have no notifications setup in this server").queue();
        return;
    }
    int size = notifications.size();
    List<CompletableFuture<Map<String, String>>> futures = new ArrayList<>();
    for (int i = 0; i < Math.ceil(size / 50D); i++) {
        List<Document> splitNotifications = notifications.subList(i * 50, Math.min((i + 1) * 50, size));
        String ids = splitNotifications.stream().map(d -> d.getString("uploaderId")).collect(Collectors.joining(","));
        Request request = new Request.Builder().url("https://www.googleapis.com/youtube/v3/channels?key=" + event.getConfig().getYouTube() + "&id=" + ids + "&part=snippet&maxResults=50").build();
        CompletableFuture<Map<String, String>> future = new CompletableFuture<>();
        event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
            Document data = Document.parse(response.body().string());
            List<Document> items = data.getList("items", Document.class);
            Map<String, String> names = new HashMap<>();
            for (Document item : items) {
                names.put(item.getString("id"), item.getEmbedded(List.of("snippet", "title"), String.class));
            }
            future.complete(names);
        });
        futures.add(future);
    }
    FutureUtility.allOf(futures).whenComplete((maps, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        Map<String, String> names = new HashMap<>();
        for (Map<String, String> map : maps) {
            names.putAll(map);
        }
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), notifications).setIncreasedIndex(true).setAutoSelect(false).setAuthor("YouTube Notifications", null, event.getGuild().getIconUrl()).setDisplayFunction(data -> {
            String uploaderId = data.getString("uploaderId");
            return String.format("%s - [%s](https://youtube.com/channel/%s)", data.getObjectId("_id").toHexString(), names.getOrDefault(uploaderId, "Unknown"), uploaderId);
        }).setSelect(SelectType.INDEX);
        paged.onSelect(selected -> this.sendStats(event, selected.getSelected()));
        paged.execute(event);
    });
}
Also used : Document(org.bson.Document) FormatterVariable(com.sx4.bot.formatter.function.FormatterVariable) MongoWriteException(com.mongodb.MongoWriteException) Permission(net.dv8tion.jda.api.Permission) TextChannel(net.dv8tion.jda.api.entities.TextChannel) PagedResult(com.sx4.bot.paged.PagedResult) JSONObject(org.json.JSONObject) Matcher(java.util.regex.Matcher) ZoneOffset(java.time.ZoneOffset) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) CompletionException(java.util.concurrent.CompletionException) FormatterManager(com.sx4.bot.formatter.FormatterManager) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Examples(com.sx4.bot.annotations.command.Examples) OffsetDateTime(java.time.OffsetDateTime) YouTubeChannel(com.sx4.bot.entities.youtube.YouTubeChannel) MultipartBody(okhttp3.MultipartBody) Pattern(java.util.regex.Pattern) java.util(java.util) Command(com.jockie.bot.core.command.Command) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) CommandId(com.sx4.bot.annotations.command.CommandId) CompletableFuture(java.util.concurrent.CompletableFuture) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) RequestBody(okhttp3.RequestBody) Bson(org.bson.conversions.Bson) AdvancedMessage(com.sx4.bot.annotations.argument.AdvancedMessage) XML(org.json.XML) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) com.mongodb.client.model(com.mongodb.client.model) YouTubeManager(com.sx4.bot.managers.YouTubeManager) FutureUtility(com.sx4.bot.utility.FutureUtility) Argument(com.jockie.bot.core.argument.Argument) Operators(com.sx4.bot.database.mongo.model.Operators) MessageUtility(com.sx4.bot.utility.MessageUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) SelectType(com.sx4.bot.paged.PagedResult.SelectType) YouTubeVideo(com.sx4.bot.entities.youtube.YouTubeVideo) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) JSONArray(org.json.JSONArray) ErrorCategory(com.mongodb.ErrorCategory) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) Document(org.bson.Document) CompletableFuture(java.util.concurrent.CompletableFuture) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Sx4Command(com.sx4.bot.core.Sx4Command) Command(com.jockie.bot.core.command.Command) 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