Search in sources :

Example 66 with HttpCallback

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

the class UrbanDictionaryCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) String query) {
    Request request = new Request.Builder().url("http://api.urbandictionary.com/v0/define?term=" + URLEncoder.encode(query, StandardCharsets.UTF_8)).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        Document json = Document.parse(response.body().string());
        List<Document> list = json.getList("list", Document.class, Collections.emptyList());
        if (list.isEmpty()) {
            event.replyFailure("I could not find any results for that query").queue();
            return;
        }
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), list).setPerPage(1).setCustomFunction(page -> {
            EmbedBuilder embed = new EmbedBuilder();
            embed.setFooter(PagedResult.DEFAULT_FOOTER_TEXT, null);
            embed.setTitle("Page " + page.getPage() + "/" + page.getMaxPage());
            page.forEach((data, index) -> {
                String readMore = "... [Read more](" + data.getString("permalink") + ")";
                String definition = this.getUrbanText(data.getString("definition"), readMore);
                String example = this.getUrbanText(data.getString("example"), readMore);
                embed.setAuthor(data.getString("word"), data.getString("permalink"), null);
                embed.addField("Definition", definition, false);
                if (!example.isEmpty()) {
                    embed.addField("Example", example, false);
                }
                embed.addField("Upvotes", data.getInteger("thumbs_up") + " 👍", true);
                embed.addField("Downvotes", data.getInteger("thumbs_down") + " 👎", true);
            });
            return new MessageBuilder().setEmbeds(embed.build());
        });
        paged.execute(event);
    });
}
Also used : Document(org.bson.Document) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) PagedResult(com.sx4.bot.paged.PagedResult) StandardCharsets(java.nio.charset.StandardCharsets) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) List(java.util.List) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Collections(java.util.Collections) Argument(com.jockie.bot.core.argument.Argument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Request(okhttp3.Request) List(java.util.List) Document(org.bson.Document) PagedResult(com.sx4.bot.paged.PagedResult)

Example 67 with HttpCallback

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

the class UserBannerCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
    User user = member == null ? event.getAuthor() : member.getUser();
    user.retrieveProfile().queue(profile -> {
        String banner = profile.getBannerUrl();
        if (banner == null) {
            int accent = profile.getAccentColorRaw();
            if (accent == User.DEFAULT_ACCENT_COLOR_RAW) {
                event.replyFailure("That user does not have a banner").queue();
                return;
            }
            String accentBanner = event.getConfig().getImageWebserverUrl("colour") + "?colour=" + accent + "&w=1024&h=205";
            EmbedBuilder embed = new EmbedBuilder().setImage(accentBanner).setColor(accent).setAuthor(user.getAsTag(), accentBanner, user.getEffectiveAvatarUrl());
            event.reply(embed.build()).queue();
            return;
        }
        Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("median-colour")).addQuery("image", banner).build(event.getConfig().getImageWebserver());
        event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
            if (!response.isSuccessful()) {
                ImageUtility.getErrorMessage(event.getTextChannel(), response.code(), response.body().string()).queue();
                return;
            }
            Document data = Document.parse(response.body().string());
            String sizedAvatar = banner + "?size=1024";
            EmbedBuilder embed = new EmbedBuilder().setImage(sizedAvatar).setColor(data.getInteger("colour")).setAuthor(user.getAsTag(), sizedAvatar, user.getEffectiveAvatarUrl());
            event.reply(embed.build()).queue();
        });
    });
}
Also used : Document(org.bson.Document) 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) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Member(net.dv8tion.jda.api.entities.Member) Argument(com.jockie.bot.core.argument.Argument) User(net.dv8tion.jda.api.entities.User) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) User(net.dv8tion.jda.api.entities.User) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Document(org.bson.Document)

Example 68 with HttpCallback

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

the class RedditCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "subreddit") String subreddit, @Option(value = "sort", description = "What to sort the subreddit by") @Options({ "new", "hot", "top" }) @DefaultString("hot") @Lowercase String sort, @Option(value = "time", description = "If sort is top will choose the top posts after the set amount of time") @Options({ "day", "week", "month", "year", "all" }) @DefaultString("day") @Lowercase String time, @Option(value = "limit", description = "How many posts to show") @DefaultNumber(25) @Limit(min = 1, max = 100) int limit) {
    Request request = new Request.Builder().url("https://reddit.com/r/" + subreddit + "/" + sort + ".json?t=" + time + "&limit=" + limit).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        if (response.code() == 302 || response.code() == 404) {
            event.replyFailure("I could not find that subreddit").queue();
            return;
        }
        List<Document> posts = Document.parse(response.body().string()).getEmbedded(List.of("data", "children"), Collections.emptyList());
        posts = posts.stream().filter(post -> {
            if (!event.getTextChannel().isNSFW()) {
                return !post.getEmbedded(List.of("data", "over_18"), false);
            }
            return true;
        }).map(post -> post.get("data", Document.class)).collect(Collectors.toList());
        if (posts.isEmpty()) {
            event.replyFailure("I could not find any posts with those filters").queue();
            return;
        }
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), posts).setPerPage(1).setSelect().setCustomFunction(page -> {
            MessageBuilder builder = new MessageBuilder();
            EmbedBuilder embed = new EmbedBuilder().setTitle("Page " + page.getPage() + "/" + page.getMaxPage());
            page.forEach((data, index) -> {
                String url = "https://reddit.com" + data.getString("permalink");
                embed.setFooter(data.getString("subreddit_name_prefixed") + " | Upvotes: " + data.getInteger("ups"));
                embed.setAuthor(StringUtility.limit(data.getString("title"), 50, "..."), url, "http://i.imgur.com/sdO8tAw.png");
                String postHint = data.getString("post_hint");
                if (postHint != null && postHint.equals("image")) {
                    embed.setImage(data.getString("url"));
                } else if (postHint != null && postHint.equals("hosted:video")) {
                    embed.setImage(data.getString("thumbnail"));
                    builder.setContent("<" + data.getEmbedded(List.of("media", "reddit_video", "fallback_url"), String.class) + ">");
                } else if (postHint != null && postHint.equals("rich:video")) {
                    embed.setImage(data.getEmbedded(List.of("media", "oembed", "thumbnail"), String.class));
                    builder.setContent("<" + data.getEmbedded(List.of("secure_media_embed", "media_domain_url"), String.class) + ">");
                }
                if (data.containsKey("selftext")) {
                    embed.setDescription(StringUtility.limit(data.getString("selftext"), MessageEmbed.DESCRIPTION_MAX_LENGTH, "... [Read more](" + url + ")"));
                }
            });
            return builder.setEmbeds(embed.build());
        });
        paged.execute(event);
    });
}
Also used : Document(org.bson.Document) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) PagedResult(com.sx4.bot.paged.PagedResult) Collectors(java.util.stream.Collectors) com.sx4.bot.annotations.argument(com.sx4.bot.annotations.argument) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Option(com.jockie.bot.core.option.Option) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) StringUtility(com.sx4.bot.utility.StringUtility) Collections(java.util.Collections) Argument(com.jockie.bot.core.argument.Argument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Request(okhttp3.Request) List(java.util.List) PagedResult(com.sx4.bot.paged.PagedResult)

Example 69 with HttpCallback

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

the class ServerAvatarCommand method onCommand.

public void onCommand(Sx4CommandEvent event) {
    String icon = event.getGuild().getIconUrl();
    if (icon == null) {
        event.replyFailure("This server does not have an icon").queue();
        return;
    }
    Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("median-colour")).addQuery("image", icon).build(event.getConfig().getImageWebserver());
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        if (!response.isSuccessful()) {
            ImageUtility.getErrorMessage(event.getTextChannel(), response.code(), response.body().string()).queue();
            return;
        }
        Document data = Document.parse(response.body().string());
        String sizedIcon = icon + "?size=1024";
        EmbedBuilder embed = new EmbedBuilder().setImage(sizedIcon).setColor(data.getInteger("colour")).setAuthor(event.getGuild().getName(), sizedIcon, sizedIcon);
        event.reply(embed.build()).queue();
    });
}
Also used : Document(org.bson.Document) 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) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Document(org.bson.Document)

Example 70 with HttpCallback

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

the class SourceCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "command", endless = true) Sx4Command command, @Option(value = "display", aliases = { "raw" }, description = "Sends the full command in discord") boolean display) {
    Method method = command.getCommandMethod();
    String path = method.getDeclaringClass().getName();
    String className = path.substring(path.lastIndexOf('.'));
    String[] classes = className.split("\\$");
    String lastClassName = classes[classes.length - 1];
    String filePath = path.replace(".", "/").substring(0, classes.length == 1 ? path.length() : path.indexOf("$")) + ".java";
    String fullPath = Sx4.GIT_HASH + "/Sx4/src/main/java/" + filePath;
    Request request = new Request.Builder().url("https://raw.githubusercontent.com/sx4-discord-bot/Sx4/" + fullPath).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        String code = response.body().string();
        String[] lines = code.split("\n");
        int classIndex = code.indexOf("class " + lastClassName);
        int startBracketCount = 0, endBracketCount = 0, startLine = -1, leading = 0;
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            if (code.indexOf(line) < classIndex && startLine == -1) {
                continue;
            }
            if (!line.contains(method.getName() + "(Sx4CommandEvent") && startLine == -1) {
                continue;
            }
            if (startLine == -1) {
                leading = line.indexOf("public");
                startLine = i;
            }
            if (!line.isBlank()) {
                lines[i] = line.substring(leading);
            }
            for (char character : line.toCharArray()) {
                if (character == '{') {
                    startBracketCount++;
                }
                if (character == '}') {
                    endBracketCount++;
                }
            }
            if (endBracketCount == startBracketCount) {
                if (display) {
                    String commandCode = String.join("\n", Arrays.copyOfRange(lines, startLine, i + 1));
                    event.replyFile(commandCode.getBytes(StandardCharsets.UTF_8), className + ".java").queue();
                } else {
                    event.reply("https://sx4.dev/github/Sx4/blob/" + fullPath + "#L" + (startLine + 1) + "-L" + (i + 1)).queue();
                }
                return;
            }
        }
    });
}
Also used : ModuleCategory(com.sx4.bot.category.ModuleCategory) Request(okhttp3.Request) Arrays(java.util.Arrays) Sx4(com.sx4.bot.core.Sx4) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Option(com.jockie.bot.core.option.Option) Method(java.lang.reflect.Method) StandardCharsets(java.nio.charset.StandardCharsets) Argument(com.jockie.bot.core.argument.Argument) Request(okhttp3.Request) Method(java.lang.reflect.Method)

Aggregations

HttpCallback (com.sx4.bot.http.HttpCallback)73 Request (okhttp3.Request)71 ModuleCategory (com.sx4.bot.category.ModuleCategory)62 Sx4Command (com.sx4.bot.core.Sx4Command)62 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)62 Argument (com.jockie.bot.core.argument.Argument)57 Permission (net.dv8tion.jda.api.Permission)57 Document (org.bson.Document)40 ImageRequest (com.sx4.bot.entities.image.ImageRequest)35 ImageUtility (com.sx4.bot.utility.ImageUtility)33 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)27 ImageUrl (com.sx4.bot.annotations.argument.ImageUrl)24 PagedResult (com.sx4.bot.paged.PagedResult)18 StandardCharsets (java.nio.charset.StandardCharsets)17 URLEncoder (java.net.URLEncoder)16 List (java.util.List)16 Option (com.jockie.bot.core.option.Option)13 OffsetDateTime (java.time.OffsetDateTime)11 ZoneOffset (java.time.ZoneOffset)11 Limit (com.sx4.bot.annotations.argument.Limit)10