diff --git a/src/main/java/de/presti/ree6/commands/CommandManager.java b/src/main/java/de/presti/ree6/commands/CommandManager.java index 072e1a88d..c76c0ae4c 100644 --- a/src/main/java/de/presti/ree6/commands/CommandManager.java +++ b/src/main/java/de/presti/ree6/commands/CommandManager.java @@ -93,6 +93,8 @@ public CommandManager() throws CommandInitializerException { //Fun addCommand(new Record()); addCommand(new RandomAnswer()); + addCommand(new Anime()); + addCommand(new Manga()); addCommand(new FunFact()); addCommand(new CatImage()); addCommand(new DogImage()); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java b/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java new file mode 100644 index 000000000..3959a370b --- /dev/null +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Anime.java @@ -0,0 +1,170 @@ +package de.presti.ree6.commands.impl.fun; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import de.presti.ree6.commands.Category; +import de.presti.ree6.commands.CommandEvent; +import de.presti.ree6.commands.interfaces.Command; +import de.presti.ree6.commands.interfaces.ICommand; +import de.presti.ree6.main.Data; +import de.presti.ree6.main.Main; +import de.presti.ree6.utils.external.RequestUtility; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.Message; +import net.dv8tion.jda.api.interactions.commands.OptionMapping; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.CommandData; +import net.dv8tion.jda.internal.interactions.CommandDataImpl; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +/** + * A command used to search for animes! + */ +@Command(name = "anime", description = "Search for animes on kitsu.io!", category = Category.FUN) +public class Anime implements ICommand { + + /** + * @inheritDoc + */ + @Override + public void onPerform(CommandEvent commandEvent) { + Message message = commandEvent.isSlashCommand() ? + commandEvent.getInteractionHook().sendMessage("Searching for the Anime...").complete() : + commandEvent.getChannel().sendMessage("Searching for the Anime...").complete(); + + String[] args = commandEvent.getArguments(); + + if (commandEvent.isSlashCommand()) { + OptionMapping searchQueryMapping = commandEvent.getSlashCommandInteractionEvent().getOption("search"); + if (searchQueryMapping != null) + args = searchQueryMapping.getAsString().split(" "); + } + + StringBuilder builder = new StringBuilder(); + + for (final String string : args) + builder.append(string).append(' '); + + if (builder.toString().endsWith(" ")) + builder = new StringBuilder(builder.substring(0, builder.length() - 1)); + + if (args.length > 0) { + sendAnime(commandEvent, message, builder.toString()); + } else { + message.editMessage("Please provide a query!").queue(); + } + } + + /** + * Send the anime to the channel. + * @param commandEvent the CommandEvent. + * @param message the Message. + * @param query the query. + */ + public void sendAnime(CommandEvent commandEvent, Message message, String query) { + RequestUtility.Request request = RequestUtility.Request.builder() + .url("https://kitsu.io/api/edge/anime?filter[text]=" + URLEncoder.encode(query, StandardCharsets.UTF_8)) + .build(); + JsonElement jsonElement = RequestUtility.request(request); + + if (jsonElement != null && + jsonElement.isJsonObject() && + jsonElement.getAsJsonObject().has("data") && + jsonElement.getAsJsonObject().get("data").isJsonArray()) { + JsonArray dataArray = jsonElement.getAsJsonObject().getAsJsonArray("data"); + + JsonObject data = !dataArray.isEmpty() && dataArray.get(0).isJsonObject() ? + dataArray.get(0).getAsJsonObject() : new JsonObject(); + + JsonObject attributes = data.has("attributes") && data.get("attributes").isJsonObject() + ? data.getAsJsonObject("attributes") : new JsonObject(); + + String url = data.has("links") && + data.get("links").isJsonObject() && data.getAsJsonObject("links").has("self") ? + data.getAsJsonObject("links").get("self").getAsString() : null; + + String name = attributes.has("canonicalTitle") ? + attributes.get("canonicalTitle").getAsString() : "Error while resolving the Name!"; + + String thumbnailUrl = attributes.has("posterImage") && + attributes.get("posterImage").isJsonObject() && + attributes.getAsJsonObject("posterImage").has("large") ? + attributes.getAsJsonObject("posterImage").get("large").getAsString() : null; + + String description = attributes.has("synopsis") ? + attributes.get("synopsis").getAsString() : "?"; + + String status = attributes.has("status") ? + attributes.get("status").getAsString() : "?"; + + String type = attributes.has("showType") ? + attributes.get("showType").getAsString() : "?"; + + String genres = attributes.has("genres") && + attributes.get("genres").isJsonArray() ? + attributes.getAsJsonArray("genres").toString() : "?"; + + String startDate = attributes.has("startDate") ? + attributes.get("startDate").getAsString() : "?"; + + String endDate = attributes.has("endDate") ? + attributes.get("endDate").getAsString() : "?"; + + String episodes = attributes.has("episodeCount") ? + attributes.get("episodeCount").getAsString() : "?"; + + String duration = attributes.has("totalLength") ? + attributes.get("totalLength").getAsInt() + " minutes" : "?"; + + String rating = attributes.has("averageRating") ? + attributes.get("averageRating").getAsString() : "?"; + + String rank = attributes.has("ratingRank") ? + attributes.get("ratingRank").getAsString() : "?"; + + EmbedBuilder em = new EmbedBuilder(); + + em.setTitle(name, url); + em.setThumbnail(thumbnailUrl); + em.setDescription(description); + em.addField(":hourglass_flowing_sand: **Status**", status, true); + em.addField(":dividers: **Type**", type, true); + em.addField(":arrow_right: **Genres**", genres, false); + em.addField(":calendar: **Aired**", "from **" + startDate + "** to **" + endDate + "**", false); + em.addField(":minidisc: **Episodes**", episodes, true); + em.addField(":stopwatch: **Duration**", duration, true); + em.addField(":star: **Average Rating**", " **" + rating + "/100**", true); + em.addField(":trophy: **Rank**", "**TOP " + rank + "**", true); + em.setFooter(commandEvent.getMember().getUser().getAsTag() + " - " + Data.ADVERTISEMENT, commandEvent.getMember().getUser().getAvatarUrl()); + + if (commandEvent.isSlashCommand()) { + message.editMessage("Anime found!").queue(); + Main.getInstance().getCommandManager().sendMessage(em, commandEvent.getChannel(), null); + } else { + message.editMessageEmbeds(em.build()).queue(message1 -> message1.editMessage("Anime found!").queue()); + } + } else { + message.editMessage("There was an error while trying to get the Anime!").queue(); + } + } + + /** + * @inheritDoc + */ + @Override + public CommandData getCommandData() { + return new CommandDataImpl("anime", "Search for animes on kitsu.io!") + .addOption(OptionType.STRING, "search", "The search query to search for.", true); + } + + /** + * @inheritDoc + */ + @Override + public String[] getAlias() { + return new String[0]; + } +} diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/CatImage.java b/src/main/java/de/presti/ree6/commands/impl/fun/CatImage.java index 5ad51b695..016853827 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/CatImage.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/CatImage.java @@ -18,7 +18,7 @@ public class CatImage implements ICommand { @Override public void onPerform(CommandEvent commandEvent) { - JsonArray js = RequestUtility.request(new RequestUtility.Request("https://api.thecatapi.com/v1/images/search")).getAsJsonArray(); + JsonArray js = RequestUtility.request(RequestUtility.Request.builder().url("https://api.thecatapi.com/v1/images/search").build()).getAsJsonArray(); EmbedBuilder em = new EmbedBuilder(); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/DogImage.java b/src/main/java/de/presti/ree6/commands/impl/fun/DogImage.java index fc72bdd86..5de7d47b7 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/DogImage.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/DogImage.java @@ -17,7 +17,7 @@ public class DogImage implements ICommand { @Override public void onPerform(CommandEvent commandEvent) { - JsonObject js = RequestUtility.request(new RequestUtility.Request("https://dog.ceo/api/breeds/image/random")).getAsJsonObject(); + JsonObject js = RequestUtility.request(RequestUtility.Request.builder().url("https://dog.ceo/api/breeds/image/random").build()).getAsJsonObject(); EmbedBuilder em = new EmbedBuilder(); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/FunFact.java b/src/main/java/de/presti/ree6/commands/impl/fun/FunFact.java index 4376dea55..c7ee0e6bc 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/FunFact.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/FunFact.java @@ -14,7 +14,7 @@ public class FunFact implements ICommand { @Override public void onPerform(CommandEvent commandEvent) { - JsonObject js = RequestUtility.request(new RequestUtility.Request("https://useless-facts.sameerkumar.website/api")).getAsJsonObject(); + JsonObject js = RequestUtility.request(RequestUtility.Request.builder().url("https://useless-facts.sameerkumar.website/api").build()).getAsJsonObject(); Main.getInstance().getCommandManager().sendMessage(js.get("data").getAsString(), commandEvent.getChannel(), commandEvent.getInteractionHook()); } diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/FunnyCryptocurrencies.java b/src/main/java/de/presti/ree6/commands/impl/fun/FunnyCryptocurrencies.java index a1b390957..22b587e20 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/FunnyCryptocurrencies.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/FunnyCryptocurrencies.java @@ -18,15 +18,15 @@ public class FunnyCryptocurrencies implements ICommand { @Override public void onPerform(CommandEvent commandEvent) { - JsonObject js = RequestUtility.request(new RequestUtility.Request("https://data.messari.io/api/v1/assets/doge/metrics")).getAsJsonObject(); + JsonObject js = RequestUtility.request(RequestUtility.Request.builder().url("https://data.messari.io/api/v1/assets/doge/metrics").build()).getAsJsonObject(); float dogeCoin = js.get("data").getAsJsonObject().get("market_data").getAsJsonObject().get("price_usd").getAsFloat(); - js = RequestUtility.request(new RequestUtility.Request("https://data.messari.io/api/v1/assets/btc/metrics")).getAsJsonObject(); + js = RequestUtility.request(RequestUtility.Request.builder().url("https://data.messari.io/api/v1/assets/btc/metrics").build()).getAsJsonObject(); float bitcoin = js.get("data").getAsJsonObject().get("market_data").getAsJsonObject().get("price_usd").getAsFloat(); - js = RequestUtility.request(new RequestUtility.Request("https://data.messari.io/api/v1/assets/ltc/metrics")).getAsJsonObject(); + js = RequestUtility.request(RequestUtility.Request.builder().url("https://data.messari.io/api/v1/assets/ltc/metrics").build()).getAsJsonObject(); float liteCoin = js.get("data").getAsJsonObject().get("market_data").getAsJsonObject().get("price_usd").getAsFloat(); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java b/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java new file mode 100644 index 000000000..599cb758f --- /dev/null +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Manga.java @@ -0,0 +1,216 @@ +package de.presti.ree6.commands.impl.fun; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import de.presti.ree6.commands.Category; +import de.presti.ree6.commands.CommandEvent; +import de.presti.ree6.commands.interfaces.Command; +import de.presti.ree6.commands.interfaces.ICommand; +import de.presti.ree6.main.Data; +import de.presti.ree6.main.Main; +import de.presti.ree6.utils.external.RequestUtility; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.Message; +import net.dv8tion.jda.api.interactions.commands.OptionMapping; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.CommandData; +import net.dv8tion.jda.internal.interactions.CommandDataImpl; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +/** + * A command used to search for mangas! + */ +@Command(name = "manga", description = "Search for mangas on kitsu.io!", category = Category.FUN) +public class Manga implements ICommand { + + /** + * @inheritDoc + */ + @Override + public void onPerform(CommandEvent commandEvent) { + Message message = commandEvent.isSlashCommand() ? + commandEvent.getInteractionHook().sendMessage("Searching for the Manga...").complete() : + commandEvent.getChannel().sendMessage("Searching for the Manga...").complete(); + + String[] args = commandEvent.getArguments(); + + if (commandEvent.isSlashCommand()) { + OptionMapping searchQueryMapping = commandEvent.getSlashCommandInteractionEvent().getOption("search"); + if (searchQueryMapping != null) + args = searchQueryMapping.getAsString().split(" "); + } + + StringBuilder builder = new StringBuilder(); + + for (final String string : args) + builder.append(string).append(' '); + + if (builder.toString().endsWith(" ")) + builder = new StringBuilder(builder.substring(0, builder.length() - 1)); + + if (args.length > 0) { + sendAnime(commandEvent, message, builder.toString()); + } else { + message.editMessage("Please provide a query!").queue(); + } + } + + /** + * Send the anime to the channel. + * @param commandEvent the CommandEvent. + * @param message the Message. + * @param query the query. + */ + public void sendAnime(CommandEvent commandEvent, Message message, String query) { + RequestUtility.Request request = RequestUtility.Request.builder() + .url("https://kitsu.io/api/edge/manga?filter[text]=" + URLEncoder.encode(query, StandardCharsets.UTF_8)) + .build(); + JsonElement jsonElement = RequestUtility.request(request); + + if (jsonElement != null && + jsonElement.isJsonObject() && + jsonElement.getAsJsonObject().has("data") && + jsonElement.getAsJsonObject().get("data").isJsonArray()) { + JsonArray dataArray = jsonElement.getAsJsonObject().getAsJsonArray("data"); + + JsonObject data = !dataArray.isEmpty() && dataArray.get(0).isJsonObject() ? + dataArray.get(0).getAsJsonObject() : new JsonObject(); + + JsonObject attributes = data.has("attributes") && data.get("attributes").isJsonObject() + ? data.getAsJsonObject("attributes") : new JsonObject(); + + String url = data.has("links") && + data.get("links").isJsonObject() && data.getAsJsonObject("links").has("self") ? + data.getAsJsonObject("links").get("self").getAsString() : null; + + String name = attributes.has("canonicalTitle") ? + attributes.get("canonicalTitle").getAsString() : "Error while resolving the Name!"; + + String thumbnailUrl = attributes.has("posterImage") && + attributes.get("posterImage").isJsonObject() && + attributes.getAsJsonObject("posterImage").has("large") ? + attributes.getAsJsonObject("posterImage").get("large").getAsString() : null; + + String description = attributes.has("synopsis") ? + attributes.get("synopsis").getAsString() : "?"; + + String status = attributes.has("status") ? + attributes.get("status").getAsString() : "?"; + + String type = attributes.has("mangaType") ? + attributes.get("mangaType").getAsString() : "?"; + + String genres = attributes.has("genres") && + attributes.get("genres").isJsonArray() ? + attributes.getAsJsonArray("genres").toString() : tryResolvingGenres(data); + + String startDate = attributes.has("startDate") ? + attributes.get("startDate").getAsString() : "?"; + + String endDate = attributes.has("endDate") ? + attributes.get("endDate").getAsString() : "?"; + + String chapters = attributes.has("chapterCount") ? + attributes.get("chapterCount").getAsString() : "?"; + + String volumes = attributes.has("volumeCount") ? + attributes.get("volumeCount").getAsString() : "?"; + + String rating = attributes.has("averageRating") ? + attributes.get("averageRating").getAsString() : "?"; + + String rank = attributes.has("ratingRank") ? + attributes.get("ratingRank").getAsString() : "?"; + + EmbedBuilder em = new EmbedBuilder(); + + em.setTitle(name, url); + em.setThumbnail(thumbnailUrl); + em.setDescription(description); + em.addField(":hourglass_flowing_sand: **Status**", status, true); + em.addField(":dividers: **Type**", type, true); + em.addField(":arrow_right: **Genres**", genres, false); + em.addField(":calendar: **Published**", "from **" + startDate + "** to **" + endDate + "**", false); + em.addField(":newspaper: **Chapters**", chapters, true); + em.addField(":books: **Volumes**", volumes + "", true); + em.addField(":star: **Average Rating**", " **" + rating + "/100**", true); + em.addField(":trophy: **Rank**", "**TOP " + rank + "**", true); + em.setFooter(commandEvent.getMember().getUser().getAsTag() + " - " + Data.ADVERTISEMENT, commandEvent.getMember().getUser().getAvatarUrl()); + + if (commandEvent.isSlashCommand()) { + message.editMessage("Manga found!").queue(); + Main.getInstance().getCommandManager().sendMessage(em, commandEvent.getChannel(), null); + } else { + message.editMessageEmbeds(em.build()).queue(message1 -> message1.editMessage("Manga found!").queue()); + } + } else { + message.editMessage("There was an error while trying to get the Anime!").queue(); + } + } + + /** + * Try to resolve the genres. + * @param data the data. + * @return the genres. + */ + public String tryResolvingGenres(JsonObject data) { + if (data.has("relationships") && + data.get("relationships").isJsonObject() && + data.getAsJsonObject("relationships").has("genres")) { + JsonObject genres = data.getAsJsonObject("relationships").getAsJsonObject("genres"); + + if (genres.has("links") && + genres.get("links").isJsonObject() && + genres.getAsJsonObject("links").has("related")) { + String url = genres.getAsJsonObject("links").get("related").getAsString(); + + RequestUtility.Request request = RequestUtility.Request.builder() + .url(url) + .build(); + + JsonElement jsonElement = RequestUtility.request(request); + + if (jsonElement != null && + jsonElement.isJsonObject() && + jsonElement.getAsJsonObject().has("data") && + jsonElement.getAsJsonObject().get("data").isJsonArray()) { + StringBuilder builder = new StringBuilder(); + for (JsonElement jsonElement1 : jsonElement.getAsJsonObject().get("data").getAsJsonArray()) { + if (jsonElement1.isJsonObject()) { + JsonObject jsonObject = jsonElement1.getAsJsonObject(); + if (jsonObject.has("attributes") && jsonObject.get("attributes").isJsonObject()) { + JsonObject attributes = jsonObject.getAsJsonObject("attributes"); + if (attributes.has("name")) { + builder.append(attributes.get("name").getAsString()).append(", "); + } + } + } + } + if (builder.length() > 0) + return builder.substring(0, builder.length() - 2); + } + } + } + return "?"; + } + + /** + * @inheritDoc + */ + @Override + public CommandData getCommandData() { + return new CommandDataImpl("manga", "Search for mangas on kitsu.io!") + .addOption(OptionType.STRING, "search", "The search query to search for.", true); + } + + /** + * @inheritDoc + */ + @Override + public String[] getAlias() { + return new String[0]; + } +} diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/MemeImage.java b/src/main/java/de/presti/ree6/commands/impl/fun/MemeImage.java index 8d2001f05..d177d6746 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/MemeImage.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/MemeImage.java @@ -18,7 +18,7 @@ public class MemeImage implements ICommand { @Override public void onPerform(CommandEvent commandEvent) { - JsonObject js = RequestUtility.request(new RequestUtility.Request("https://meme-api.herokuapp.com/gimme")).getAsJsonObject(); + JsonObject js = RequestUtility.request(RequestUtility.Request.builder().url("https://meme-api.herokuapp.com/gimme").build()).getAsJsonObject(); EmbedBuilder em = new EmbedBuilder(); diff --git a/src/main/java/de/presti/ree6/commands/impl/fun/Waifu.java b/src/main/java/de/presti/ree6/commands/impl/fun/Waifu.java index e74217452..f8653fbd7 100644 --- a/src/main/java/de/presti/ree6/commands/impl/fun/Waifu.java +++ b/src/main/java/de/presti/ree6/commands/impl/fun/Waifu.java @@ -18,7 +18,7 @@ public class Waifu implements ICommand { @Override public void onPerform(CommandEvent commandEvent) { - JsonObject jsonObject = RequestUtility.request(new RequestUtility.Request("https://api.dagpi.xyz/data/waifu", Main.getInstance().getConfig().getConfiguration().getString("dagpi.apitoken"))).getAsJsonObject(); + JsonObject jsonObject = RequestUtility.request(RequestUtility.Request.builder().url("https://api.dagpi.xyz/data/waifu").bearerAuth(Main.getInstance().getConfig().getConfiguration().getString("dagpi.apitoken")).build()).getAsJsonObject(); EmbedBuilder em = new EmbedBuilder(); diff --git a/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java b/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java index eb15540e9..4f21b8e3a 100644 --- a/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java +++ b/src/main/java/de/presti/ree6/commands/impl/nsfw/NSFW.java @@ -27,7 +27,6 @@ public class NSFW implements ICommand { @Override public void onPerform(CommandEvent commandEvent) { if (commandEvent.getChannel().getType() == ChannelType.TEXT && commandEvent.getChannel().asTextChannel().isNSFW()) { - sendImage(commandEvent); } else { Main.getInstance().getCommandManager().sendMessage("Only available in NSFW Channels!", 5, commandEvent.getChannel(), commandEvent.getInteractionHook()); @@ -44,7 +43,7 @@ public void sendImage(CommandEvent commandEvent) { commandEvent.getInteractionHook().sendMessage("Searching for Image...").complete() : commandEvent.getChannel().sendMessage("Searching for Image...").complete(); - JsonElement jsonElement = RequestUtility.request(new RequestUtility.Request("https://www.reddit.com/r/hentai/new.json?sort=hot&limit=50")); + JsonElement jsonElement = RequestUtility.request(RequestUtility.Request.builder().url("https://www.reddit.com/r/hentai/new.json?sort=hot&limit=50").build()); if (jsonElement.isJsonObject() && jsonElement.getAsJsonObject().has("data") && diff --git a/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java b/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java index 18b88e005..8e52bb65d 100644 --- a/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java +++ b/src/main/java/de/presti/ree6/commands/impl/nsfw/Rule34.java @@ -31,8 +31,7 @@ public class Rule34 implements ICommand { */ @Override public void onPerform(CommandEvent commandEvent) { - if (commandEvent.getChannel() != null && - commandEvent.getChannel().getType() == ChannelType.TEXT && + if (commandEvent.getChannel().getType() == ChannelType.TEXT && commandEvent.getChannel().asTextChannel().isNSFW()) { sendMessage(commandEvent); @@ -69,7 +68,7 @@ public void sendMessage(CommandEvent commandEvent) { if (builder.toString().endsWith(" ")) builder = new StringBuilder(builder.substring(0, builder.length() - 1)); - if (args.length > 1) + if (args.length > 0) tags = "&tags=" + URLEncoder.encode(builder.toString(), StandardCharsets.UTF_8).toLowerCase(); if (tags.contains("loli") || tags.contains("l0li") || tags.contains("lol1") || tags.contains("l0l1")) { @@ -88,7 +87,8 @@ public void sendMessage(CommandEvent commandEvent) { * @param tags the Tags. */ public void sendImage(CommandEvent commandEvent, Message message, String tags) { - final JsonElement jsonElement = RequestUtility.request(new RequestUtility.Request("https://api.rule34.xxx/index.php?page=dapi&s=post&q=index&json=1&limit=50" + tags)); + final JsonElement jsonElement = + RequestUtility.request(RequestUtility.Request.builder().url("https://api.rule34.xxx/index.php?page=dapi&s=post&q=index&json=1&limit=50" + tags).build()); if (jsonElement != null && jsonElement.isJsonArray()) { final JsonArray array = jsonElement.getAsJsonArray(); diff --git a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java index 0b9f42b06..0d843aec6 100644 --- a/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java +++ b/src/main/java/de/presti/ree6/commands/interfaces/ICommand.java @@ -18,7 +18,11 @@ public interface ICommand { * @param commandEvent the Event, with every needed data. */ default void onASyncPerform(CommandEvent commandEvent) { - CompletableFuture.runAsync(() -> onPerform(commandEvent)); + CompletableFuture.runAsync(() -> onPerform(commandEvent)).exceptionally(throwable -> { + Main.getInstance().getCommandManager().sendMessage("An Error occurred while performing the Command!", 5, commandEvent.getChannel(), commandEvent.getInteractionHook()); + Main.getInstance().getLogger().error("An error occurred while executing the command!", throwable); + return null; + }); // Update Stats. Main.getInstance().getSqlConnector().getSqlWorker().addStats(commandEvent.getGuild().getId(), this.getClass().getAnnotation(Command.class).name()); } diff --git a/src/main/java/de/presti/ree6/utils/external/RequestUtility.java b/src/main/java/de/presti/ree6/utils/external/RequestUtility.java index 183113505..238a4dd74 100644 --- a/src/main/java/de/presti/ree6/utils/external/RequestUtility.java +++ b/src/main/java/de/presti/ree6/utils/external/RequestUtility.java @@ -10,6 +10,8 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.util.ArrayList; +import java.util.List; // TODO rework. @@ -34,8 +36,17 @@ public static JsonElement request(Request request) { HttpRequest.Builder httpRequestBuilder = HttpRequest.newBuilder() .uri(request.getUri()) - .header("User-Agent", USER_AGENT) - .header("Content-Type", "application/json-rpc"); + .header("User-Agent", USER_AGENT); + + if (request.getHeaders().isEmpty()) { + httpRequestBuilder = httpRequestBuilder.header("Content-Type", "application/json-rpc"); + } else { + for (String[] header : request.getHeaders()) { + if (header.length == 2) { + httpRequestBuilder = httpRequestBuilder.header(header[0], header[1]); + } + } + } if (request.bearerAuth != null) { httpRequestBuilder = httpRequestBuilder.header("Authorization", request.getBearerAuth()); @@ -85,73 +96,20 @@ public static class Request { String url, bearerAuth; // The Request Method. - Method method; + Method method = Method.GET; // The Body Publisher used for PUT and POST Requests. HttpRequest.BodyPublisher bodyPublisher; - /** - * Create a simple HTTP GET Requests. - * - * @param url the Request URL. - */ - public Request(String url) { - this.url = url; - method = Method.GET; - } - - /** - * Create a simple HTTP GET Requests with a AuthToken. - * - * @param url the Request URL. - * @param bearerAuth the AuthToken. - */ - public Request(String url, String bearerAuth) { - this.url = url; - this.bearerAuth = bearerAuth; - method = Method.GET; - } - - /** - * Create a simple HTTP Requests with a AuthToken. - * - * @param url the Request URL. - * @param bearerAuth the AuthToken. - * @param method the wanted Method. - */ - public Request(String url, String bearerAuth, Method method) { - this.url = url; - this.bearerAuth = bearerAuth; - this.method = method; - } - - /** - * Create a simple HTTP Requests. - * - * @param url the Request URL. - * @param method the wanted Method. - * @param bodyPublisher the Body Publisher used for PUT and POST Requests. - */ - public Request(String url, Method method, HttpRequest.BodyPublisher bodyPublisher) { - this.url = url; - this.method = method; - this.bodyPublisher = bodyPublisher; - } - + // Custom Headers. + List headers = new ArrayList<>(); /** - * Create a simple HTTP Requests with a AuthToken. - * - * @param url the Request URL. - * @param bearerAuth the AuthToken. - * @param method the wanted Method. - * @param bodyPublisher the Body Publisher used for PUT and POST Requests. + * Create a new Request builder. + * @return a new Request builder. */ - public Request(String url, String bearerAuth, Method method, HttpRequest.BodyPublisher bodyPublisher) { - this.url = url; - this.bearerAuth = bearerAuth; - this.method = method; - this.bodyPublisher = bodyPublisher; + public static RequestBuilder builder() { + return new RequestBuilder(); } /** @@ -198,6 +156,91 @@ public Method getMethod() { public HttpRequest.BodyPublisher getBodyPublisher() { return bodyPublisher; } + + /** + * Get the Headers. + * @return the Headers. + */ + public List getHeaders() { + return headers; + } + + /** + * Builder class for a Request class. + */ + public static class RequestBuilder { + // The URL and Auth Token for the Request. + String url, bearerAuth; + + // The Request Method. + Method method = Method.GET; + + // The Body Publisher used for PUT and POST Requests. + HttpRequest.BodyPublisher bodyPublisher; + + // Custom Headers. + List headers = new ArrayList<>(); + + /** + * Change the Url of the Request. + * @param url the new Url. + * @return the Request. + */ + public RequestBuilder url(String url) { + this.url = url; + return this; + } + + /** + * Change the Bearer Auth Token. + * @param bearerAuth the new Auth Token. + * @return the Request. + */ + public RequestBuilder bearerAuth(String bearerAuth) { + this.bearerAuth = bearerAuth; + return this; + } + + /** + * Change the Request method. + * @param method the new Method. + * @return the Request. + */ + public RequestBuilder method(Method method) { + this.method = method; + return this; + } + + /** + * Change the Body publisher used. + * @param bodyPublisher the Body Publisher used for PUT and POST Requests. + * @return the Request. + */ + public RequestBuilder bodyPublisher(HttpRequest.BodyPublisher bodyPublisher) { + this.bodyPublisher = bodyPublisher; + return this; + } + + /** + * Change the Headers. + * @param header the new Header. + * @return the Request. + */ + public RequestBuilder header(String[] header) { + this.headers.add(header); + return this; + } + + public Request build() { + Request request = new Request(); + request.url = this.url; + request.method = this.method; + request.bodyPublisher = this.bodyPublisher; + request.headers = this.headers; + request.bearerAuth = this.bearerAuth; + return request; + } + } } /**