Skip to content

Commit

Permalink
Merge pull request #59 from pitzzahh/patches
Browse files Browse the repository at this point in the history
Update for /joke command
request from issue: #55
  • Loading branch information
pitzzahh authored Feb 24, 2023
2 parents 21f9aa7 + 46cb016 commit 61f40ea
Show file tree
Hide file tree
Showing 7 changed files with 146 additions and 60 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,18 @@

package tech.araopj.springpitzzahhbot.commands.slash_command;

import tech.araopj.springpitzzahhbot.commands.slash_command.commands.confessions.Confession;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.game.service.GameService;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.confessions.service.ConfessionService;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.getJoke.service.JokesService;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.game.service.GameService;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.confessions.Confession;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.getJoke.GetJoke;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.game.Game;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.service.JokesService;
import tech.araopj.springpitzzahhbot.exceptions.CommandAlreadyExistException;
import tech.araopj.springpitzzahhbot.config.channels.service.ChannelService;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.Joke;
import tech.araopj.springpitzzahhbot.commands.service.CommandsService;
import tech.araopj.springpitzzahhbot.utilities.MessageUtil;
import tech.araopj.springpitzzahhbot.config.HttpConfig;
import org.springframework.stereotype.Component;
import org.jetbrains.annotations.NotNull;
import java.util.function.Consumer;
Expand All @@ -56,12 +57,13 @@ public SlashCommandManager(
ChannelService channelService,
JokesService jokesService,
GameService gameService,
MessageUtil messageUtil
) {
MessageUtil messageUtil,
HttpConfig httpConfig
) {
addCommands(
new Confession(confessionService, commandsService, channelService, messageUtil),
new Game(gameService, messageUtil),
new Joke(messageUtil, jokesService)
new GetJoke(messageUtil, jokesService, httpConfig)
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,34 +22,41 @@
* SOFTWARE.
*/

package tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke;
package tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.getJoke;


import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.getJoke.service.JokesService;
import tech.araopj.springpitzzahhbot.commands.slash_command.CommandContext;
import tech.araopj.springpitzzahhbot.commands.slash_command.SlashCommand;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.internal.interactions.CommandDataImpl;
import org.springframework.stereotype.Component;
import tech.araopj.springpitzzahhbot.commands.slash_command.CommandContext;
import tech.araopj.springpitzzahhbot.commands.slash_command.SlashCommand;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.service.JokesService;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import tech.araopj.springpitzzahhbot.utilities.MessageUtil;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import tech.araopj.springpitzzahhbot.config.HttpConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import static java.awt.Color.YELLOW;
import static java.time.LocalDateTime.now;
import static java.lang.String.format;

import java.time.ZoneId;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.net.http.HttpResponse;
import static java.awt.Color.CYAN;
import static java.lang.String.format;
import static java.time.LocalDateTime.now;
import static java.time.ZoneId.of;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.URI;

@Slf4j
@Component
public record Joke(MessageUtil messageUtil, JokesService jokesService) implements SlashCommand {
public record GetJoke(
MessageUtil messageUtil,
JokesService jokesService,
HttpConfig httpConfig
) implements SlashCommand {

/**
* Executes a {@code SlashCommand}
Expand All @@ -66,43 +73,75 @@ public Consumer<CommandContext> execute() {
* Contains the process to be executed.
* @param context the command context containing the information about the command.
*/
private void process(CommandContext context) {
final var CLIENT = HttpClient.newHttpClient();
private void process(CommandContext context){

final var category = context.getEvent().getOption("category");
log.info("Category: {}", category);

final var REQUEST = HttpRequest.newBuilder()
.uri(URI.create("https://v2.jokeapi.dev/joke/Any?blacklistFlags=nsfw,religious,political,racist,sexist,explicit&format=txt"))
final var language = context.getEvent().getOption("language");
log.info("Language: {}", language);
String url = jokesService.createJokeRequestUrl(category, language);
log.info("Url: {}", url);
final var REQUEST = httpConfig.httpBuilder() // TODO: create a uri builder
.uri(URI.create(url))
.GET()
.build();

final HttpResponse<String> RESPONSE;

try {
RESPONSE = CLIENT.send(REQUEST, HttpResponse.BodyHandlers.ofString());
RESPONSE = httpConfig.httpClient().send(REQUEST, HttpResponse.BodyHandlers.ofString());
log.info("Response from joke api: {}", RESPONSE.body());
} catch (IOException | InterruptedException e) {
log.error("Error while sending request to joke api", e);
throw new RuntimeException(e);
}

var joke = RESPONSE.body();
messageUtil.getEmbedBuilder()
.clear()
.clearFields()
.setColor(CYAN)
.setTitle("Joke of the day")
.setDescription(joke)
.setTimestamp(now(of("UTC")))
.setFooter(
format("Created by %s", context.getGuild().getJDA().getSelfUser().getAsTag()),
context.getGuild().getJDA().getSelfUser().getAvatarUrl()
);
if (RESPONSE.statusCode() == 200) {

var apiResponse = RESPONSE.body();

String joke;

try {
joke = new ObjectMapper().readTree(apiResponse).get("joke").asText();
} catch (JsonProcessingException e) {
log.error("Error while parsing joke api response", e);
throw new RuntimeException(e);
}

messageUtil.getEmbedBuilder()
.clear()
.clearFields()
.setColor(CYAN)
.setTitle("GetJoke of the day")
.setDescription(joke != null ? joke : "No joke found")
.setTimestamp(now(ZoneId.systemDefault()))
.setFooter(
format("Created by %s", context.getGuild().getJDA().getSelfUser().getAsTag()),
context.getGuild().getJDA().getSelfUser().getAvatarUrl()
);
context.getEvent()
.getInteraction()
.replyEmbeds(messageUtil.getEmbedBuilder().build())
.queue();
} else {
messageUtil.getEmbedBuilder()
.clear()
.clearFields()
.setColor(YELLOW)
.setTitle("No joke found")
.setDescription("I couldn't find a joke for you 😢.")
.setTimestamp(now(ZoneId.systemDefault()))
.setFooter(
format("Created by %s", context.getGuild().getJDA().getSelfUser().getAsTag()),
context.getGuild().getJDA().getSelfUser().getAvatarUrl()
);
context.getEvent()
.getInteraction()
.replyEmbeds(messageUtil.getEmbedBuilder().build())
.queue();
}

}

/**
Expand All @@ -127,10 +166,10 @@ public Supplier<CommandData> getCommandData() {
name().get(),
description().get())
.addOptions(
new OptionData(OptionType.STRING, "category", "Category of the joke", true)
new OptionData(OptionType.STRING, "category", "Category of the joke", false)
.setDescription("Select your desired joke category")
.addChoices(jokesService.getCategories()),
new OptionData(OptionType.STRING, "language", "Language of the joke", true)
new OptionData(OptionType.STRING, "language", "Language of the joke", false)
.setDescription("Select your desired joke language")
.addChoices(jokesService.getLanguages())
);
Expand All @@ -144,6 +183,6 @@ public Supplier<CommandData> getCommandData() {
*/
@Override
public Supplier<String> description() {
return () -> "Sends a random Joke";
return () -> "Sends a random GetJoke";
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.entity;
package tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.getJoke.entity;

import net.dv8tion.jda.api.interactions.commands.Command;
import org.jetbrains.annotations.NotNull;

public class Category extends Command.Choice {
public Category(@NotNull String name, long value) {
public Category(@NotNull String name, @NotNull String value) {
super(name, value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@
* SOFTWARE.
*/

package tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.entity;
package tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.getJoke.entity;

import net.dv8tion.jda.api.interactions.commands.Command;
import org.jetbrains.annotations.NotNull;

public class Language extends Command.Choice {
public Language(@NotNull String name, long value) {
public Language(@NotNull String name, @NotNull String value) {
super(name, value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,22 @@
* SOFTWARE.
*/

package tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.service;
package tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.getJoke.service;

import tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.entity.Category;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.entity.Language;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.getJoke.entity.*;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import tech.araopj.springpitzzahhbot.config.HttpConfig;
import java.util.concurrent.ExecutionException;
import org.springframework.stereotype.Service;
import com.google.gson.reflect.TypeToken;
import java.util.stream.Collectors;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import java.util.Collection;
import com.google.gson.Gson;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.net.URI;

@Slf4j
Expand All @@ -57,7 +59,14 @@ public Collection<Category> getCategories() {
log.error("Error while getting categories", e);
throw new RuntimeException(e);
}
return new Gson().fromJson(stringHttpResponse.body(), new TypeToken<List<Category>>(){}.getType());

var categories = (String[]) new Gson().fromJson(stringHttpResponse.body(), new TypeToken<String[]>() {}.getType());

// Now the categories array should contain the parsed values
log.info("Categories: {}", Arrays.toString(categories));
return Arrays.stream(categories)
.map(category -> new Category(category, category))
.collect(Collectors.toCollection(ArrayList::new));
}

public Collection<Language> getLanguages() {
Expand All @@ -73,7 +82,28 @@ public Collection<Language> getLanguages() {
log.error("Error while getting languages", e);
throw new RuntimeException(e);
}
return new Gson().fromJson(stringHttpResponse.body(), new TypeToken<List<Language>>(){}.getType());

var languages = (String[]) new Gson().fromJson(stringHttpResponse.body(), new TypeToken<String[]>() {}.getType());

// Now the categories array should contain the parsed values
log.info("Languages: {}", Arrays.toString(languages));

return Arrays.stream(languages)
.map(language -> new Language(language, language))
.collect(Collectors.toCollection(ArrayList::new));
}

public String createJokeRequestUrl(OptionMapping category, OptionMapping language) {
var url = httpConfig.getJokeApiUrl();
if (category != null && language != null) url += "random?category=" + category.getAsString() + "&language=" + language.getAsString();
else if (category != null) url += "random?category=" + category.getAsString();
else if (language != null) url += "random?language=" + language.getAsString();
else url += "random";
return url;
}

public String createJokeSubmitUrl() {
return httpConfig.getJokeApiUrl().concat("submit");
}

}
16 changes: 14 additions & 2 deletions src/main/java/tech/araopj/springpitzzahhbot/config/HttpConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,29 @@
package tech.araopj.springpitzzahhbot.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;

import org.springframework.context.annotation.Bean;
import java.net.http.HttpRequest;
import java.net.http.HttpClient;
import lombok.Getter;

@Getter
@Configuration
public class HttpConfig {

@Value("${joke-api.url}")
private String jokeApiUrl;

@Bean
@Async
public HttpClient httpClient() {
return HttpClient.newHttpClient();
}

@Bean
@Async
public HttpRequest.Builder httpBuilder() {
return HttpRequest.newBuilder();
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package tech.araopj.springpitzzahhbot.service;

import tech.araopj.springpitzzahhbot.commands.slash_command.commands.confessions.service.ConfessionService;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.service.JokesService;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.joke.getJoke.service.JokesService;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.game.service.GameService;
import tech.araopj.springpitzzahhbot.commands.slash_command.commands.confessions.Confession;
import tech.araopj.springpitzzahhbot.config.moderation.service.MessageCheckerService;
Expand All @@ -19,6 +19,7 @@
import net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder;
import tech.araopj.springpitzzahhbot.listeners.MemberLogger;
import tech.araopj.springpitzzahhbot.utilities.MessageUtil;
import tech.araopj.springpitzzahhbot.config.HttpConfig;
import org.springframework.context.annotation.Bean;
import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.sharding.ShardManager;
Expand All @@ -43,7 +44,8 @@ public record BotService(
JokesService jokesService,
GameService gameService,
MessageUtil messageUtil,
Confession confession
Confession confession,
HttpConfig httpConfig
) {

@Bean
Expand Down Expand Up @@ -84,7 +86,8 @@ public ShardManager shardManager() {
channelService,
jokesService,
gameService,
messageUtil
messageUtil,
httpConfig
)
),
new MemberLogger(
Expand Down

0 comments on commit 61f40ea

Please sign in to comment.