Search in sources :

Example 81 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(new byte[0], null)).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.getTwitchConfig().set("token", json.getString("access_token")).set("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)

Example 82 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 83 with HttpCallback

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

the class YouTubeNotificationCommand method add.

@Command(value = "add", description = "Add a youtube notification to be posted to a specific channel when the user uploads")
@CommandId(158)
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@Examples({ "youtube notification add videos mrbeast", "youtube notification add mrbeast", "youtube notification add #videos pewdiepie" })
public void add(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) TextChannel channel, @Argument(value = "youtube channel", endless = true) String channelQuery) {
    if (!event.getBot().getConnectionHandler().isReady()) {
        event.replyFailure("The bot has to be fully started to use this command, try again later").queue();
        return;
    }
    TextChannel effectiveChannel = channel == null ? event.getTextChannel() : channel;
    boolean id = this.id.matcher(channelQuery).matches();
    boolean search;
    String queryName, query;
    Matcher matcher = this.url.matcher(channelQuery);
    if (!id && matcher.matches()) {
        String path = matcher.group(1);
        search = false;
        queryName = path == null || path.equals("user") ? "forUsername" : "id";
        query = matcher.group(2);
    } else {
        search = !id;
        queryName = id ? "id" : "q";
        query = channelQuery;
    }
    Request channelRequest = new Request.Builder().url("https://www.googleapis.com/youtube/v3/" + (search ? "search" : "channels") + "?key=" + event.getConfig().getYouTube() + "&" + queryName + "=" + URLEncoder.encode(query, StandardCharsets.UTF_8) + "&part=snippet&type=channel&maxResults=1").build();
    event.getHttpClient().newCall(channelRequest).enqueue((HttpCallback) channelResponse -> {
        Document json = Document.parse(channelResponse.body().string());
        List<Document> items = json.getList("items", Document.class, Collections.emptyList());
        if (items.isEmpty()) {
            event.replyFailure("I could not find that youtube channel").queue();
            return;
        }
        Document item = items.get(0);
        String channelId = search ? item.getEmbedded(List.of("id", "channelId"), String.class) : item.getString("id");
        Document notificationData = new Document("uploaderId", channelId).append("channelId", effectiveChannel.getIdLong()).append("guildId", event.getGuild().getIdLong());
        if (!event.getBot().getYouTubeManager().hasExecutor(channelId)) {
            RequestBody body = new MultipartBody.Builder().addFormDataPart("hub.mode", "subscribe").addFormDataPart("hub.topic", "https://www.youtube.com/xml/feeds/videos.xml?channel_id=" + channelId).addFormDataPart("hub.callback", event.getConfig().getBaseUrl() + "/api/youtube").addFormDataPart("hub.verify", "sync").addFormDataPart("hub.verify_token", event.getConfig().getYouTube()).setType(MultipartBody.FORM).build();
            Request request = new Request.Builder().url("https://pubsubhubbub.appspot.com/subscribe").post(body).build();
            event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
                if (response.isSuccessful()) {
                    event.getMongo().insertYouTubeNotification(notificationData).whenComplete((result, exception) -> {
                        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
                        if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
                            event.replyFailure("You already have a notification setup for that youtube channel in " + effectiveChannel.getAsMention()).queue();
                            return;
                        }
                        if (ExceptionUtility.sendExceptionally(event, exception)) {
                            return;
                        }
                        event.replyFormat("Notifications will now be sent in %s when **%s** uploads with id `%s` %s", effectiveChannel.getAsMention(), item.getEmbedded(List.of("snippet", "title"), String.class), result.getInsertedId().asObjectId().getValue().toHexString(), event.getConfig().getSuccessEmote()).queue();
                    });
                } else {
                    event.replyFailure("Oops something went wrong there, try again. If this repeats report this to my developer (Message: " + response.body().string() + ")").queue();
                }
            });
        } else {
            event.getMongo().insertYouTubeNotification(notificationData).whenComplete((result, exception) -> {
                Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
                if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
                    event.replyFailure("You already have a notification setup for that youtube channel in " + effectiveChannel.getAsMention()).queue();
                    return;
                }
                if (ExceptionUtility.sendExceptionally(event, exception)) {
                    return;
                }
                event.replyFormat("Notifications will now be sent in %s when **%s** uploads with id `%s` %s", effectiveChannel.getAsMention(), item.getEmbedded(List.of("snippet", "title"), String.class), result.getInsertedId().asObjectId().getValue().toHexString(), event.getConfig().getSuccessEmote()).queue();
            });
        }
    });
}
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) Matcher(java.util.regex.Matcher) MongoWriteException(com.mongodb.MongoWriteException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Document(org.bson.Document) TextChannel(net.dv8tion.jda.api.entities.TextChannel) CompletionException(java.util.concurrent.CompletionException) RequestBody(okhttp3.RequestBody) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) 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)

Example 84 with HttpCallback

use of com.sx4.bot.http.HttpCallback 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)

Example 85 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)

Aggregations

HttpCallback (com.sx4.bot.http.HttpCallback)85 Request (okhttp3.Request)83 ModuleCategory (com.sx4.bot.category.ModuleCategory)68 Sx4Command (com.sx4.bot.core.Sx4Command)68 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)68 Permission (net.dv8tion.jda.api.Permission)67 Argument (com.jockie.bot.core.argument.Argument)63 Document (org.bson.Document)51 ImageRequest (com.sx4.bot.entities.image.ImageRequest)35 ImageUtility (com.sx4.bot.utility.ImageUtility)33 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)33 ImageUrl (com.sx4.bot.annotations.argument.ImageUrl)28 PagedResult (com.sx4.bot.paged.PagedResult)24 StandardCharsets (java.nio.charset.StandardCharsets)23 URLEncoder (java.net.URLEncoder)22 java.util (java.util)20 OffsetDateTime (java.time.OffsetDateTime)18 Collectors (java.util.stream.Collectors)18 Bson (org.bson.conversions.Bson)17 Command (com.jockie.bot.core.command.Command)16