Search in sources :

Example 71 with HttpCallback

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

the class EmoteCommand method getBytes.

private void getBytes(OkHttpClient httpClient, String url, TriConsumer<byte[], Boolean, Integer> bytes) {
    Request request = new Request.Builder().url(RequestUtility.getWorkerUrl(url)).build();
    httpClient.newCall(request).enqueue((HttpCallback) response -> {
        if (response.code() == 200) {
            String contentType = response.header("Content-Type"), extension = null;
            if (contentType != null && contentType.contains("/")) {
                extension = contentType.split("/")[1].toLowerCase();
            }
            bytes.accept(response.body().bytes(), extension == null ? null : extension.equals("gif"), 200);
            return;
        } else if (response.code() == 415) {
            int periodIndex = url.lastIndexOf('.');
            if (periodIndex != -1) {
                String extension = url.substring(periodIndex + 1);
                if (extension.equalsIgnoreCase("gif")) {
                    this.getBytes(httpClient, url.substring(0, periodIndex + 1) + "png", bytes);
                    return;
                }
            }
        }
        bytes.accept(null, null, response.code());
    });
}
Also used : Arrays(java.util.Arrays) Command(com.jockie.bot.core.command.Command) Permission(net.dv8tion.jda.api.Permission) Cooldown(com.jockie.bot.core.command.Command.Cooldown) PagedResult(com.sx4.bot.paged.PagedResult) HashSet(java.util.HashSet) Role(net.dv8tion.jda.api.entities.Role) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) RequestUtility(com.sx4.bot.utility.RequestUtility) TimeUtility(com.sx4.bot.utility.TimeUtility) Icon(net.dv8tion.jda.api.entities.Icon) RateLimitedException(net.dv8tion.jda.api.exceptions.RateLimitedException) TriConsumer(com.jockie.bot.core.utility.function.TriConsumer) com.sx4.bot.annotations.command(com.sx4.bot.annotations.command) Argument(com.jockie.bot.core.argument.Argument) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) PartialEmote(com.sx4.bot.entities.mod.PartialEmote) Predicate(java.util.function.Predicate) Set(java.util.Set) CompletionException(java.util.concurrent.CompletionException) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) OkHttpClient(okhttp3.OkHttpClient) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) Emote(net.dv8tion.jda.api.entities.Emote) Request(okhttp3.Request)

Example 72 with HttpCallback

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

the class WelcomerUtility method getWelcomerMessage.

public static void getWelcomerMessage(OkHttpClient httpClient, Document messageData, String bannerId, Member member, boolean canary, boolean image, boolean gif, BiConsumer<WebhookMessageBuilder, Throwable> consumer) {
    Guild guild = member.getGuild();
    User user = member.getUser();
    OffsetDateTime now = OffsetDateTime.now();
    Formatter<Document> formatter = new JsonFormatter(messageData).member(member).user(user).guild(guild).addVariable(User.class, "age", TimeUtility.LONG_TIME_FORMATTER.parse(Duration.between(user.getTimeCreated(), now).toSeconds())).addVariable("now", now);
    if (!image) {
        WebhookMessageBuilder builder;
        if (messageData != null) {
            try {
                builder = MessageUtility.fromJson(formatter.parse());
            } catch (IllegalArgumentException e) {
                consumer.accept(null, e);
                return;
            }
        } else {
            builder = new WebhookMessageBuilder();
        }
        consumer.accept(builder, null);
    } else {
        ImageRequest request = new ImageRequest(Config.get().getImageWebserverUrl("welcomer")).addQuery("avatar", user.getEffectiveAvatarUrl()).addQuery("name", user.getAsTag()).addQuery("gif", gif).addQuery("directory", canary ? "sx4-canary" : "sx4-main");
        if (bannerId != null) {
            request.addQuery("banner_id", bannerId);
        }
        httpClient.newCall(request.build(Config.get().getImageWebserver())).enqueue((HttpCallback) response -> {
            if (response.isSuccessful()) {
                String fileName = "welcomer." + response.header("Content-Type").split("/")[1];
                formatter.addVariable("file.name", fileName).addVariable("file.url", "attachment://" + fileName);
                WebhookMessageBuilder builder;
                if (messageData == null) {
                    builder = new WebhookMessageBuilder();
                } else {
                    try {
                        builder = MessageUtility.fromJson(formatter.parse());
                    } catch (IllegalArgumentException e) {
                        consumer.accept(null, e);
                        return;
                    }
                }
                builder.addFile(fileName, response.body().bytes());
                consumer.accept(builder, null);
            } else {
                response.close();
            }
        });
    }
}
Also used : JsonFormatter(com.sx4.bot.formatter.JsonFormatter) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) Document(org.bson.Document) Config(com.sx4.bot.config.Config) ImageRequest(com.sx4.bot.entities.image.ImageRequest) HttpCallback(com.sx4.bot.http.HttpCallback) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) Member(net.dv8tion.jda.api.entities.Member) User(net.dv8tion.jda.api.entities.User) Guild(net.dv8tion.jda.api.entities.Guild) OkHttpClient(okhttp3.OkHttpClient) OffsetDateTime(java.time.OffsetDateTime) Formatter(com.sx4.bot.formatter.Formatter) Duration(java.time.Duration) BiConsumer(java.util.function.BiConsumer) User(net.dv8tion.jda.api.entities.User) OffsetDateTime(java.time.OffsetDateTime) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Guild(net.dv8tion.jda.api.entities.Guild) Document(org.bson.Document)

Example 73 with HttpCallback

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

the class TwitchTokenManager method retrieveToken.

public void retrieveToken() {
    Request request = new Request.Builder().post(RequestBody.create(null, new byte[0])).url("https://id.twitch.tv/oauth2/token?client_id=" + this.bot.getConfig().getTwitchClientId() + "&client_secret=" + this.bot.getConfig().getTwitchClientSecret() + "&grant_type=client_credentials").build();
    this.bot.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        Document json = Document.parse(response.body().string());
        this.bot.getConfig().set("token.twitch.token", json.getString("access_token")).set("token.twitch.expiresAt", Clock.systemUTC().instant().getEpochSecond() + json.getInteger("expires_in")).update();
        this.schedule(json.getInteger("expires_in"));
    });
}
Also used : Document(org.bson.Document) TimeUnit(java.util.concurrent.TimeUnit) Request(okhttp3.Request) Sx4(com.sx4.bot.core.Sx4) HttpCallback(com.sx4.bot.http.HttpCallback) Clock(java.time.Clock) RequestBody(okhttp3.RequestBody) Request(okhttp3.Request) Document(org.bson.Document)

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