Search in sources :

Example 1 with GoogleSearchResult

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

the class GoogleSearchCache method retrieveResultsByQuery.

public CompletableFuture<List<GoogleSearchResult>> retrieveResultsByQuery(String query, boolean imageSearch, boolean includeNSFW) {
    CompletableFuture<List<GoogleSearchResult>> future = new CompletableFuture<>();
    Map<Boolean, Map<String, List<GoogleSearchResult>>> cache = imageSearch ? this.imageCache : this.cache;
    Map<String, List<GoogleSearchResult>> actualCache = cache.get(includeNSFW);
    if (actualCache != null && actualCache.containsKey(query)) {
        future.complete(actualCache.get(query));
    } else {
        Request request = new Request.Builder().url("https://www.googleapis.com/customsearch/v1?key=" + this.bot.getConfig().getGoogle() + "&cx=014023765838117903829:mm334tqd3kg" + (imageSearch ? "&searchType=image" : "") + "&safe=" + (includeNSFW ? "off" : "active") + "&q=" + query).build();
        this.bot.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
            Document json = Document.parse(response.body().string());
            if (json.containsKey("error")) {
                Document error = json.get("error", Document.class);
                int code = error.getInteger("code");
                if (code == 429) {
                    future.completeExceptionally(new ForbiddenException("Daily quota reached (100)"));
                } else {
                    future.completeExceptionally(new HttpException(error.get("message", "Unknown error occurred with status " + code)));
                }
                return;
            }
            List<Document> items = json.getList("items", Document.class, Collections.emptyList());
            List<GoogleSearchResult> results = items.stream().map(GoogleSearchResult::new).collect(Collectors.toList());
            cache.compute(includeNSFW, (key, value) -> {
                if (value == null) {
                    Map<String, List<GoogleSearchResult>> newCache = new HashMap<>();
                    newCache.put(query, results);
                    return newCache;
                } else {
                    value.put(query, results);
                    return value;
                }
            });
            future.complete(results);
        });
    }
    return future;
}
Also used : HttpException(net.dv8tion.jda.api.exceptions.HttpException) Document(org.bson.Document) Request(okhttp3.Request) List(java.util.List) ForbiddenException(javax.ws.rs.ForbiddenException) Sx4(com.sx4.bot.core.Sx4) HttpCallback(com.sx4.bot.http.HttpCallback) Map(java.util.Map) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Collections(java.util.Collections) Collectors(java.util.stream.Collectors) ForbiddenException(javax.ws.rs.ForbiddenException) Request(okhttp3.Request) Document(org.bson.Document) CompletableFuture(java.util.concurrent.CompletableFuture) List(java.util.List) HttpException(net.dv8tion.jda.api.exceptions.HttpException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with GoogleSearchResult

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

the class GoogleCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) String query) {
    MessageChannel channel = event.getChannel();
    boolean nsfw = channel instanceof BaseGuildMessageChannel && ((BaseGuildMessageChannel) channel).isNSFW();
    event.getBot().getGoogleCache().retrieveResultsByQuery(query, 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://www.google.co.uk/search?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8) + (nsfw ? "" : "&safe=active");
        PagedResult<GoogleSearchResult> paged = new PagedResult<>(event.getBot(), results).setIndexed(false).setPerPage(3).setAuthor("Google", googleUrl, "http://i.imgur.com/G46fm8J.png").setDisplayFunction(result -> {
            String title = result.getTitle(), link = result.getLink(), snippet = result.getSnippet();
            return "**[" + StringUtility.limit(title, 32) + "](" + link + ")**\n" + StringUtility.limit(snippet, 246, " ...") + "\n";
        });
        paged.execute(event);
    });
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) CompletionException(java.util.concurrent.CompletionException) GoogleSearchResult(com.sx4.bot.cache.GoogleSearchCache.GoogleSearchResult) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) PagedResult(com.sx4.bot.paged.PagedResult)

Example 3 with GoogleSearchResult

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

the class GoogleImageCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) String query) {
    MessageChannel channel = event.getChannel();
    boolean nsfw = channel instanceof BaseGuildMessageChannel && ((BaseGuildMessageChannel) channel).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) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) CompletionException(java.util.concurrent.CompletionException) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel)

Aggregations

ForbiddenException (javax.ws.rs.ForbiddenException)3 GoogleSearchResult (com.sx4.bot.cache.GoogleSearchCache.GoogleSearchResult)2 CompletionException (java.util.concurrent.CompletionException)2 BaseGuildMessageChannel (net.dv8tion.jda.api.entities.BaseGuildMessageChannel)2 MessageChannel (net.dv8tion.jda.api.entities.MessageChannel)2 Sx4 (com.sx4.bot.core.Sx4)1 HttpCallback (com.sx4.bot.http.HttpCallback)1 PagedResult (com.sx4.bot.paged.PagedResult)1 ArrayList (java.util.ArrayList)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 Collectors (java.util.stream.Collectors)1 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)1 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)1 MessageEmbed (net.dv8tion.jda.api.entities.MessageEmbed)1 HttpException (net.dv8tion.jda.api.exceptions.HttpException)1 Request (okhttp3.Request)1