From 0c0cf23bd4c1abb65e21fb17b4d56e9d68d58e74 Mon Sep 17 00:00:00 2001
From: Suraj Kumar <76599223+surajkumar@users.noreply.github.com>
Date: Fri, 14 Oct 2022 14:20:19 +0100
Subject: [PATCH 01/11] Added POC for /google command
---
.../togetherjava/tjbot/commands/Features.java | 6 +-
.../tjbot/commands/search/GoogleCommand.java | 95 +++++++++++++++++++
.../commands/search/GoogleSearchStrategy.java | 28 ++++++
.../tjbot/commands/search/SearchStrategy.java | 8 ++
.../search/StackOverflowSearchStrategy.java | 14 +++
.../commands/search/StackoverflowCommand.java | 21 ++++
6 files changed, 170 insertions(+), 2 deletions(-)
create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java
create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/search/StackOverflowSearchStrategy.java
create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/search/StackoverflowCommand.java
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java
index 581296a77d..ffbbabaf81 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java
@@ -19,6 +19,7 @@
import org.togetherjava.tjbot.commands.moderation.temp.TemporaryModerationRoutine;
import org.togetherjava.tjbot.commands.reminder.RemindCommand;
import org.togetherjava.tjbot.commands.reminder.RemindRoutine;
+import org.togetherjava.tjbot.commands.search.GoogleCommand;
import org.togetherjava.tjbot.commands.system.BotCore;
import org.togetherjava.tjbot.commands.system.LogLevelCommand;
import org.togetherjava.tjbot.commands.tags.TagCommand;
@@ -82,7 +83,7 @@ public static Collection createFeatures(JDA jda, Database database, Con
features.add(new HelpThreadMetadataPurger(database));
features.add(new HelpThreadActivityUpdater(helpSystemHelper));
features
- .add(new AutoPruneHelperRoutine(config, helpSystemHelper, modAuditLogWriter, database));
+ .add(new AutoPruneHelperRoutine(config, helpSystemHelper, modAuditLogWriter, database));
features.add(new HelpThreadAutoArchiver(helpSystemHelper));
// Message receivers
@@ -127,10 +128,11 @@ public static Collection createFeatures(JDA jda, Database database, Con
features.add(new WolframAlphaCommand(config));
features.add(new AskCommand(config, helpSystemHelper));
features.add(new HelpThreadCommand(config, helpSystemHelper));
+ features.add(new GoogleCommand());
// Mixtures
features.add(new HelpThreadOverviewUpdater(config, helpSystemHelper));
return features;
}
-}
+}
\ No newline at end of file
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
new file mode 100644
index 0000000000..226bb7bc2a
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
@@ -0,0 +1,95 @@
+package org.togetherjava.tjbot.commands.search;
+
+import net.dv8tion.jda.api.EmbedBuilder;
+import net.dv8tion.jda.api.entities.MessageEmbed;
+import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
+import net.dv8tion.jda.api.interactions.commands.OptionType;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.togetherjava.tjbot.commands.CommandVisibility;
+import org.togetherjava.tjbot.commands.SlashCommandAdapter;
+
+import java.awt.*;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+public class GoogleCommand extends SlashCommandAdapter {
+ private static final String COMMAND_OPTION = "query";
+ private static final int MAX_RESULTS_TO_SHOW = 5;
+ private final SearchStrategy searchStrategy = new GoogleSearchStrategy();
+
+ public GoogleCommand() {
+ super("google", "Searches Google for your search query", CommandVisibility.GUILD);
+ this.getData()
+ .addOption(OptionType.STRING, COMMAND_OPTION, "the query to send to Google", true);
+ }
+
+ @Override
+ public void onSlashCommand(SlashCommandInteractionEvent event) {
+ event.deferReply().queue();
+ searchStrategy.search(Objects.requireNonNull(event.getOption(COMMAND_OPTION)).getAsString())
+ .thenAccept(response -> {
+ JSONObject json = new JSONObject(response.body());
+ if (json.has("related_questions")) {
+ StringBuilder sb = new StringBuilder();
+ JSONArray relatedQuestions = json.getJSONArray("related_questions");
+ for (int i = 0; i < relatedQuestions.length(); i++) {
+ JSONObject result = relatedQuestions.getJSONObject(i);
+ String question = result.getString("question");
+ String snippetOfAnswer = "";
+ if (result.has("snippet")) {
+ snippetOfAnswer = result.getString("snippet");
+ } else if (result.has("list")) {
+ StringBuilder list = new StringBuilder();
+ result.getJSONArray("list")
+ .toList()
+ .forEach(line -> list.append(line).append("\n"));
+ snippetOfAnswer = list.toString();
+ }
+ String link = result.getString("link");
+ sb.append("\n**")
+ .append(question)
+ .append("**")
+ .append("\n")
+ .append(snippetOfAnswer)
+ .append("\n")
+ .append(link)
+ .append("\n");
+ }
+ EmbedBuilder eb = new EmbedBuilder();
+ eb.setAuthor("Here are some answers that I have found", null, null);
+ eb.setDescription(sb);
+ eb.setColor(Color.RED);
+ event.getHook().editOriginalEmbeds().setEmbeds(eb.build()).queue();
+ }
+ if (json.has("organic_results")) {
+ List embeds = new ArrayList<>();
+ JSONArray searchResults = json.getJSONArray("organic_results");
+ for (int i = 0; i < Math.min(searchResults.length(),
+ MAX_RESULTS_TO_SHOW); i++) {
+ JSONObject result = searchResults.getJSONObject(i);
+ String title = result.getString("title");
+ String link = result.getString("link");
+ String snippet = result.getString("snippet");
+ EmbedBuilder eb = new EmbedBuilder();
+ eb.setAuthor(title, link, null);
+ eb.setDescription(snippet);
+ eb.setColor(Color.RED);
+ embeds.add(eb.build());
+ }
+ if (embeds.size() > 0) {
+ event.getHook()
+ .sendMessage("Here are some results that I have found:")
+ .queue();
+ event.getHook().editOriginalEmbeds().setEmbeds(embeds).queue();
+ } else {
+ event.getHook()
+ .sendMessage(
+ "I could not find any results for your search term. Try rephrasing your search.")
+ .queue();
+ }
+ }
+ });
+ }
+}
\ No newline at end of file
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
new file mode 100644
index 0000000000..3b0d42a5c3
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
@@ -0,0 +1,28 @@
+package org.togetherjava.tjbot.commands.search;
+
+import io.mikael.urlbuilder.UrlBuilder;
+
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.util.concurrent.CompletableFuture;
+
+public class GoogleSearchStrategy extends SearchStrategy {
+ private static final String API_KEY =
+ "1d84500b082341aad66de5cf02f7c83d8608411b01b7ffcbb2d40042eea250df";
+ private static final String API_ENDPOINT = "https://serpapi.com/search";
+ private final HttpClient httpClient = HttpClient.newHttpClient();
+
+ @Override
+ public CompletableFuture> search(String searchTerm) {
+ return httpClient.sendAsync(
+ HttpRequest
+ .newBuilder(UrlBuilder.fromString(API_ENDPOINT)
+ .addParameter("q", searchTerm)
+ .addParameter("api_key", API_KEY)
+ .toUri())
+ .GET()
+ .build(),
+ HttpResponse.BodyHandlers.ofString());
+ }
+}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java
new file mode 100644
index 0000000000..25a81f8d1f
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java
@@ -0,0 +1,8 @@
+package org.togetherjava.tjbot.commands.search;
+
+import java.net.http.HttpResponse;
+import java.util.concurrent.CompletableFuture;
+
+public abstract class SearchStrategy {
+ public abstract CompletableFuture> search(String searchTerm);
+}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/StackOverflowSearchStrategy.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/StackOverflowSearchStrategy.java
new file mode 100644
index 0000000000..60fbdc13ea
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/StackOverflowSearchStrategy.java
@@ -0,0 +1,14 @@
+package org.togetherjava.tjbot.commands.search;
+
+import java.net.http.HttpResponse;
+import java.util.concurrent.CompletableFuture;
+
+public class StackOverflowSearchStrategy extends SearchStrategy {
+ private static final String API_URL =
+ "https://api.stackexchange.com/2.3/questions?order=desc&sort=activity&site=stackoverflow&intitle=";
+
+ @Override
+ public CompletableFuture> search(String searchTerm) {
+ return null;
+ }
+}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/StackoverflowCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/StackoverflowCommand.java
new file mode 100644
index 0000000000..e839ac7656
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/StackoverflowCommand.java
@@ -0,0 +1,21 @@
+package org.togetherjava.tjbot.commands.search;
+
+import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
+import org.togetherjava.tjbot.commands.CommandVisibility;
+import org.togetherjava.tjbot.commands.SlashCommandAdapter;
+
+public class StackoverflowCommand extends SlashCommandAdapter {
+ private final SearchStrategy searchStrategy = new StackOverflowSearchStrategy();
+
+ protected StackoverflowCommand() {
+ super("stackoverflow", "Searches Stackoverflow for your search term",
+ CommandVisibility.GUILD);
+ }
+
+ @Override
+ public void onSlashCommand(SlashCommandInteractionEvent event) {
+
+
+
+ }
+}
\ No newline at end of file
From f7615f73ceb99d4d29807e15be4a10658ce197a6 Mon Sep 17 00:00:00 2001
From: Suraj Kumar <76599223+surajkumar@users.noreply.github.com>
Date: Fri, 14 Oct 2022 17:58:38 +0100
Subject: [PATCH 02/11] Cleaned up code
---
.../tjbot/commands/search/GoogleCommand.java | 174 +++++++++++++-----
.../commands/search/GoogleSearchStrategy.java | 30 ++-
.../tjbot/commands/search/SearchStrategy.java | 21 ++-
.../search/StackOverflowSearchStrategy.java | 14 --
.../commands/search/StackoverflowCommand.java | 21 ---
5 files changed, 173 insertions(+), 87 deletions(-)
delete mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/search/StackOverflowSearchStrategy.java
delete mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/search/StackoverflowCommand.java
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
index 226bb7bc2a..04be973c1a 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
@@ -6,90 +6,164 @@
import net.dv8tion.jda.api.interactions.commands.OptionType;
import org.json.JSONArray;
import org.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.togetherjava.tjbot.commands.CommandVisibility;
import org.togetherjava.tjbot.commands.SlashCommandAdapter;
import java.awt.*;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
import java.util.Objects;
+/**
+ * This class contains the logic required for the '/google' slash command.
+ * The syntax of the command is as followed:
+ * /google query [search term]
+ *
+ * Results are sent to the user as embeds. The result contains the questions and answers
+ * of the search results under "People also asked" alongside the first 5 organic search results.
+ *
+ * @author Suraj Kumar
+ */
public class GoogleCommand extends SlashCommandAdapter {
+ private static final Logger logger = LoggerFactory.getLogger(GoogleCommand.class);
+ /**
+ * The option that contains the search term within the /google command.
+ */
private static final String COMMAND_OPTION = "query";
+ /**
+ * The maximum number of organic search results to show.
+ * When there are less than 5 results available in the search results,
+ * the amount returned is the number of available results. This flag does not affect the
+ * "People also asked" results.
+ */
private static final int MAX_RESULTS_TO_SHOW = 5;
+ /**
+ * The search strategy that is going to return the results to us.
+ */
private final SearchStrategy searchStrategy = new GoogleSearchStrategy();
+ /**
+ * Constructs a new {@code GoogleCommand} object and sets up the metadata for this command including the name,
+ * description and command options.
+ */
public GoogleCommand() {
super("google", "Searches Google for your search query", CommandVisibility.GUILD);
this.getData()
- .addOption(OptionType.STRING, COMMAND_OPTION, "the query to send to Google", true);
+ .addOption(OptionType.STRING, COMMAND_OPTION, "the query to send to Google", true);
}
+ /**
+ * The main logic for the /google command.
+ * When we receive the event from discord, the reply is deferred for a later period of time. This is because
+ * calling the {@link org.togetherjava.tjbot.commands.search.SearchStrategy} is considered a blocking operation.
+ *
+ * Related questions are sent as 1 long text block to the user as a response.
+ * Organic Google search results are collated and send as separate embeds to the user as a response.
+ *
+ * @param event the event provided by Discord to ack the initialization of the slash command.
+ */
@Override
public void onSlashCommand(SlashCommandInteractionEvent event) {
+ logger.info("Received /google slash command");
+
event.deferReply().queue();
- searchStrategy.search(Objects.requireNonNull(event.getOption(COMMAND_OPTION)).getAsString())
+ String searchTerm = Objects.requireNonNull(event.getOption(COMMAND_OPTION)).getAsString();
+ logger.info("{} entered search term {}", Objects.requireNonNull(event.getMember()).getEffectiveName(), searchTerm);
+
+ searchStrategy.search(searchTerm)
.thenAccept(response -> {
+ MessageEmbed relatedQuestionsMessageEmbed = null;
JSONObject json = new JSONObject(response.body());
if (json.has("related_questions")) {
- StringBuilder sb = new StringBuilder();
- JSONArray relatedQuestions = json.getJSONArray("related_questions");
- for (int i = 0; i < relatedQuestions.length(); i++) {
- JSONObject result = relatedQuestions.getJSONObject(i);
- String question = result.getString("question");
- String snippetOfAnswer = "";
- if (result.has("snippet")) {
- snippetOfAnswer = result.getString("snippet");
- } else if (result.has("list")) {
- StringBuilder list = new StringBuilder();
- result.getJSONArray("list")
- .toList()
- .forEach(line -> list.append(line).append("\n"));
- snippetOfAnswer = list.toString();
- }
- String link = result.getString("link");
- sb.append("\n**")
- .append(question)
- .append("**")
- .append("\n")
- .append(snippetOfAnswer)
- .append("\n")
- .append(link)
- .append("\n");
- }
- EmbedBuilder eb = new EmbedBuilder();
- eb.setAuthor("Here are some answers that I have found", null, null);
- eb.setDescription(sb);
- eb.setColor(Color.RED);
- event.getHook().editOriginalEmbeds().setEmbeds(eb.build()).queue();
+ logger.info("related_questions present within response from Google, adding results to response");
+ relatedQuestionsMessageEmbed = createMessageEmbedForRelatedQuestions(json.getJSONArray("related_questions"), searchTerm);
}
if (json.has("organic_results")) {
- List embeds = new ArrayList<>();
- JSONArray searchResults = json.getJSONArray("organic_results");
- for (int i = 0; i < Math.min(searchResults.length(),
- MAX_RESULTS_TO_SHOW); i++) {
- JSONObject result = searchResults.getJSONObject(i);
- String title = result.getString("title");
- String link = result.getString("link");
- String snippet = result.getString("snippet");
- EmbedBuilder eb = new EmbedBuilder();
- eb.setAuthor(title, link, null);
- eb.setDescription(snippet);
- eb.setColor(Color.RED);
- embeds.add(eb.build());
+ logger.info("organic_results present within response from Google, adding results to response");
+ List embeds = createMessageEmbedForOrganicResults(json.getJSONArray("organic_results"));
+ if(relatedQuestionsMessageEmbed != null) {
+ Collections.reverse(embeds);
+ embeds.add(relatedQuestionsMessageEmbed);
+ Collections.reverse(embeds);
}
if (embeds.size() > 0) {
- event.getHook()
- .sendMessage("Here are some results that I have found:")
- .queue();
event.getHook().editOriginalEmbeds().setEmbeds(embeds).queue();
} else {
event.getHook()
- .sendMessage(
- "I could not find any results for your search term. Try rephrasing your search.")
+ .sendMessage("I could not find any results for your search term. Try rephrasing your search.")
.queue();
}
+ } else if(relatedQuestionsMessageEmbed != null) {
+ event.getHook().editOriginalEmbeds().setEmbeds(relatedQuestionsMessageEmbed).queue();
}
+ logger.info("Finished handling /google slash command.");
});
}
+
+ /**
+ * Creates a ready to send response containing the information for an organic search result.
+ * The response is set to be a separate message for each result.
+ *
+ * @param searchResults An array of organic search results to build the MessageEmbeds.
+ * @return A List of MessageEmbeds for dispatch.
+ */
+ private List createMessageEmbedForOrganicResults(JSONArray searchResults) {
+ logger.info("Creating a list of MessageEmbed for a total of {} results", searchResults.length());
+ List embeds = new ArrayList<>();
+ for (int i = 0; i < Math.min(searchResults.length(), MAX_RESULTS_TO_SHOW); i++) {
+ JSONObject result = searchResults.getJSONObject(i);
+ String title = result.getString("title");
+ String link = result.getString("link");
+ String snippet = result.getString("snippet");
+ EmbedBuilder eb = new EmbedBuilder();
+ eb.setAuthor(title, link, null);
+ eb.setDescription(snippet);
+ eb.setColor(Color.BLACK);
+ embeds.add(eb.build());
+ }
+ return embeds;
+ }
+
+ /**
+ * Creates a ready to send response containing the information for related questions search result.
+ * The response is set to be 1 single message containing all the information.
+ *
+ * @param relatedQuestions An array of related questions search results to build the MessageEmbeds.
+ * @return A List of MessageEmbeds for dispatch.
+ */
+ private MessageEmbed createMessageEmbedForRelatedQuestions(JSONArray relatedQuestions, String searchTerm) {
+ logger.info("Creating a MessageEmbed for a total of {} results", relatedQuestions.length());
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < relatedQuestions.length(); i++) {
+ JSONObject result = relatedQuestions.getJSONObject(i);
+ String question = result.getString("question");
+ String snippetOfAnswer = "";
+ if (result.has("snippet")) {
+ snippetOfAnswer = result.getString("snippet");
+ } else if (result.has("list")) {
+ StringBuilder list = new StringBuilder();
+ result.getJSONArray("list")
+ .toList()
+ .forEach(line -> list.append(line).append("\n"));
+ snippetOfAnswer = list.toString();
+ }
+ String link = result.getString("link");
+ sb.append("\n**")
+ .append(question)
+ .append("**")
+ .append("\n")
+ .append(snippetOfAnswer.trim())
+ .append("\n\n")
+ .append(link)
+ .append("\n");
+ }
+ return new EmbedBuilder()
+ .setAuthor("Here are some answers that I have found for " + searchTerm, null, null)
+ .setDescription(sb)
+ .setColor(Color.BLACK)
+ .build();
+ }
}
\ No newline at end of file
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
index 3b0d42a5c3..0d2ef1d078 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
@@ -7,12 +7,40 @@
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
+/**
+ * {@code GoogleSearchStrategy} contains the logic for searching on Google.
+ *
+ * The service is provided by Serpapi is a wrapper over the Google API. This has
+ * been used because it provides us with much easier access to the Google API without having to go through the complicated
+ * process of setting up the application and auth on Google's side.
+ *
+ * @author Suraj Kumar
+ */
public class GoogleSearchStrategy extends SearchStrategy {
+ /** The API key to provide authentication into Serpapi */
private static final String API_KEY =
"1d84500b082341aad66de5cf02f7c83d8608411b01b7ffcbb2d40042eea250df";
+
+ /** The Serpapi REST service URL used for fetching Google search results. */
private static final String API_ENDPOINT = "https://serpapi.com/search";
+
+ /** The HttpClient object used for sending the REST API calls. */
private final HttpClient httpClient = HttpClient.newHttpClient();
+ /**
+ * Called the Serpapi API with the provided search term async. The result of the API is a JSON body that can be
+ * used to grab all the information we need regarding the search and search contents.
+ *
+ * The Serpapi takes 2 parameters:
+ * 1. q: The search query
+ * 2. api_key: The authentication key created via the Serpapi dashboard.
+ *
+ * For additional parameters see: Serpapi API docs
+ *
+ * @param searchTerm The search term to query against. This would be in the exact format a user would be searching
+ * on Google.
+ * @return A CompletableFuture as this action is blocking.
+ */
@Override
public CompletableFuture> search(String searchTerm) {
return httpClient.sendAsync(
@@ -25,4 +53,4 @@ public CompletableFuture> search(String searchTerm) {
.build(),
HttpResponse.BodyHandlers.ofString());
}
-}
+}
\ No newline at end of file
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java
index 25a81f8d1f..b2ef3f813f 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java
@@ -3,6 +3,25 @@
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
+/**
+ * A base class for a search Strategy. This allows us to implement multiple variations of a search functionality
+ * without having to rewrite any of the main logic (except parsing) used for getting search results. For
+ * example in the {@link GoogleSearchStrategy} the Serpapi API is used for fetching results from Google. If we were to
+ * change this, we can do by creating a new SearchStrategy and replace the existing call with the new strategy
+ * without further code changes.
+ *
+ * Additionally, we now have flexibility to implement searching in other platforms such as Stackoverflow, Yahoo, Bing
+ * etc.
+ *
+ * @author Suraj Kumar
+ */
public abstract class SearchStrategy {
+
+ /**
+ * A common search function that should asynchronously handle a search function for a given term.
+ *
+ * @param searchTerm The search term to look for.
+ * @return A CompletableFuture for retrieval of the response when ready.
+ */
public abstract CompletableFuture> search(String searchTerm);
-}
+}
\ No newline at end of file
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/StackOverflowSearchStrategy.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/StackOverflowSearchStrategy.java
deleted file mode 100644
index 60fbdc13ea..0000000000
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/StackOverflowSearchStrategy.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package org.togetherjava.tjbot.commands.search;
-
-import java.net.http.HttpResponse;
-import java.util.concurrent.CompletableFuture;
-
-public class StackOverflowSearchStrategy extends SearchStrategy {
- private static final String API_URL =
- "https://api.stackexchange.com/2.3/questions?order=desc&sort=activity&site=stackoverflow&intitle=";
-
- @Override
- public CompletableFuture> search(String searchTerm) {
- return null;
- }
-}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/StackoverflowCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/StackoverflowCommand.java
deleted file mode 100644
index e839ac7656..0000000000
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/StackoverflowCommand.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package org.togetherjava.tjbot.commands.search;
-
-import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
-import org.togetherjava.tjbot.commands.CommandVisibility;
-import org.togetherjava.tjbot.commands.SlashCommandAdapter;
-
-public class StackoverflowCommand extends SlashCommandAdapter {
- private final SearchStrategy searchStrategy = new StackOverflowSearchStrategy();
-
- protected StackoverflowCommand() {
- super("stackoverflow", "Searches Stackoverflow for your search term",
- CommandVisibility.GUILD);
- }
-
- @Override
- public void onSlashCommand(SlashCommandInteractionEvent event) {
-
-
-
- }
-}
\ No newline at end of file
From 6464f560129b0c295c6fe5099e1caee75aa2713d Mon Sep 17 00:00:00 2001
From: Suraj Kumar <76599223+surajkumar@users.noreply.github.com>
Date: Fri, 14 Oct 2022 18:36:28 +0100
Subject: [PATCH 03/11] Refactoring, docs and the Googleit command. Added the
new Google message to the helper.
---
.../togetherjava/tjbot/commands/Features.java | 2 +
.../tjbot/commands/help/HelpSystemHelper.java | 8 +-
.../tjbot/commands/search/GoogleCommand.java | 133 ++---------------
.../commands/search/GoogleItCommand.java | 45 ++++++
.../search/GoogleResponseComposer.java | 137 ++++++++++++++++++
.../commands/search/GoogleSearchStrategy.java | 32 ++--
.../tjbot/commands/search/SearchStrategy.java | 11 +-
7 files changed, 221 insertions(+), 147 deletions(-)
create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java
create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java
index ffbbabaf81..5055f5259c 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java
@@ -20,6 +20,7 @@
import org.togetherjava.tjbot.commands.reminder.RemindCommand;
import org.togetherjava.tjbot.commands.reminder.RemindRoutine;
import org.togetherjava.tjbot.commands.search.GoogleCommand;
+import org.togetherjava.tjbot.commands.search.GoogleItCommand;
import org.togetherjava.tjbot.commands.system.BotCore;
import org.togetherjava.tjbot.commands.system.LogLevelCommand;
import org.togetherjava.tjbot.commands.tags.TagCommand;
@@ -129,6 +130,7 @@ public static Collection createFeatures(JDA jda, Database database, Con
features.add(new AskCommand(config, helpSystemHelper));
features.add(new HelpThreadCommand(config, helpSystemHelper));
features.add(new GoogleCommand());
+ features.add(new GoogleItCommand());
// Mixtures
features.add(new HelpThreadOverviewUpdater(config, helpSystemHelper));
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java b/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java
index 4dce9512e0..4abe4ed2fc 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java
@@ -129,7 +129,11 @@ private RestAction sendExplanationMessage(GuildMessageChannel threadCha
With enough info, someone knows the answer for sure."""),
HelpSystemHelper.embedWith(
"Don't forget to close your thread using the command %s when your question has been answered, thanks."
- .formatted(closeCommandMention)));
+ .formatted(closeCommandMention)),
+
+ HelpSystemHelper.embedWith(
+ "You can now search your question on Google using the `/google` slash command! If you want me to search your question for you, just enter the slash command `/googleit`")
+ );
MessageCreateAction action = threadChannel.sendMessage(message);
if (useCodeSyntaxExampleImage) {
@@ -383,4 +387,4 @@ static ThreadActivity ofSymbol(String symbol) {
"Unknown thread activity symbol: " + symbol));
}
}
-}
+}
\ No newline at end of file
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
index 04be973c1a..e39fc30248 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
@@ -1,29 +1,18 @@
package org.togetherjava.tjbot.commands.search;
-import net.dv8tion.jda.api.EmbedBuilder;
-import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType;
-import org.json.JSONArray;
-import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.togetherjava.tjbot.commands.CommandVisibility;
import org.togetherjava.tjbot.commands.SlashCommandAdapter;
-import java.awt.*;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
import java.util.Objects;
-
/**
- * This class contains the logic required for the '/google' slash command.
- * The syntax of the command is as followed:
- * /google query [search term]
- *
- * Results are sent to the user as embeds. The result contains the questions and answers
- * of the search results under "People also asked" alongside the first 5 organic search results.
+ * This class contains the logic required for the '/google' slash command.
+ * The syntax of the command is as followed: /google query [search term].
+ * Results are sent to the user as embeds. The result contains the questions and answers of the search results under
+ * "People also asked" alongside the first 5 organic search results.
*
* @author Suraj Kumar
*/
@@ -33,35 +22,24 @@ public class GoogleCommand extends SlashCommandAdapter {
* The option that contains the search term within the /google command.
*/
private static final String COMMAND_OPTION = "query";
- /**
- * The maximum number of organic search results to show.
- * When there are less than 5 results available in the search results,
- * the amount returned is the number of available results. This flag does not affect the
- * "People also asked" results.
- */
- private static final int MAX_RESULTS_TO_SHOW = 5;
/**
* The search strategy that is going to return the results to us.
*/
private final SearchStrategy searchStrategy = new GoogleSearchStrategy();
/**
- * Constructs a new {@code GoogleCommand} object and sets up the metadata for this command including the name,
- * description and command options.
+ * Constructs a new {@code GoogleCommand} object and sets up the metadata for this command including the name,
+ * description and command options.
*/
public GoogleCommand() {
super("google", "Searches Google for your search query", CommandVisibility.GUILD);
this.getData()
.addOption(OptionType.STRING, COMMAND_OPTION, "the query to send to Google", true);
}
-
/**
- * The main logic for the /google command.
- * When we receive the event from discord, the reply is deferred for a later period of time. This is because
- * calling the {@link org.togetherjava.tjbot.commands.search.SearchStrategy} is considered a blocking operation.
- *
- * Related questions are sent as 1 long text block to the user as a response.
- * Organic Google search results are collated and send as separate embeds to the user as a response.
+ * The main logic for the /google command.
+ * When we receive the event from discord, the reply is deferred for a later period of time. This is because calling
+ * the {@link org.togetherjava.tjbot.commands.search.SearchStrategy} is considered a blocking operation.
*
* @param event the event provided by Discord to ack the initialization of the slash command.
*/
@@ -73,97 +51,6 @@ public void onSlashCommand(SlashCommandInteractionEvent event) {
String searchTerm = Objects.requireNonNull(event.getOption(COMMAND_OPTION)).getAsString();
logger.info("{} entered search term {}", Objects.requireNonNull(event.getMember()).getEffectiveName(), searchTerm);
- searchStrategy.search(searchTerm)
- .thenAccept(response -> {
- MessageEmbed relatedQuestionsMessageEmbed = null;
- JSONObject json = new JSONObject(response.body());
- if (json.has("related_questions")) {
- logger.info("related_questions present within response from Google, adding results to response");
- relatedQuestionsMessageEmbed = createMessageEmbedForRelatedQuestions(json.getJSONArray("related_questions"), searchTerm);
- }
- if (json.has("organic_results")) {
- logger.info("organic_results present within response from Google, adding results to response");
- List embeds = createMessageEmbedForOrganicResults(json.getJSONArray("organic_results"));
- if(relatedQuestionsMessageEmbed != null) {
- Collections.reverse(embeds);
- embeds.add(relatedQuestionsMessageEmbed);
- Collections.reverse(embeds);
- }
- if (embeds.size() > 0) {
- event.getHook().editOriginalEmbeds().setEmbeds(embeds).queue();
- } else {
- event.getHook()
- .sendMessage("I could not find any results for your search term. Try rephrasing your search.")
- .queue();
- }
- } else if(relatedQuestionsMessageEmbed != null) {
- event.getHook().editOriginalEmbeds().setEmbeds(relatedQuestionsMessageEmbed).queue();
- }
- logger.info("Finished handling /google slash command.");
- });
- }
-
- /**
- * Creates a ready to send response containing the information for an organic search result.
- * The response is set to be a separate message for each result.
- *
- * @param searchResults An array of organic search results to build the MessageEmbeds.
- * @return A List of MessageEmbeds for dispatch.
- */
- private List createMessageEmbedForOrganicResults(JSONArray searchResults) {
- logger.info("Creating a list of MessageEmbed for a total of {} results", searchResults.length());
- List embeds = new ArrayList<>();
- for (int i = 0; i < Math.min(searchResults.length(), MAX_RESULTS_TO_SHOW); i++) {
- JSONObject result = searchResults.getJSONObject(i);
- String title = result.getString("title");
- String link = result.getString("link");
- String snippet = result.getString("snippet");
- EmbedBuilder eb = new EmbedBuilder();
- eb.setAuthor(title, link, null);
- eb.setDescription(snippet);
- eb.setColor(Color.BLACK);
- embeds.add(eb.build());
- }
- return embeds;
- }
-
- /**
- * Creates a ready to send response containing the information for related questions search result.
- * The response is set to be 1 single message containing all the information.
- *
- * @param relatedQuestions An array of related questions search results to build the MessageEmbeds.
- * @return A List of MessageEmbeds for dispatch.
- */
- private MessageEmbed createMessageEmbedForRelatedQuestions(JSONArray relatedQuestions, String searchTerm) {
- logger.info("Creating a MessageEmbed for a total of {} results", relatedQuestions.length());
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < relatedQuestions.length(); i++) {
- JSONObject result = relatedQuestions.getJSONObject(i);
- String question = result.getString("question");
- String snippetOfAnswer = "";
- if (result.has("snippet")) {
- snippetOfAnswer = result.getString("snippet");
- } else if (result.has("list")) {
- StringBuilder list = new StringBuilder();
- result.getJSONArray("list")
- .toList()
- .forEach(line -> list.append(line).append("\n"));
- snippetOfAnswer = list.toString();
- }
- String link = result.getString("link");
- sb.append("\n**")
- .append(question)
- .append("**")
- .append("\n")
- .append(snippetOfAnswer.trim())
- .append("\n\n")
- .append(link)
- .append("\n");
- }
- return new EmbedBuilder()
- .setAuthor("Here are some answers that I have found for " + searchTerm, null, null)
- .setDescription(sb)
- .setColor(Color.BLACK)
- .build();
+ new GoogleResponseComposer().doSearchAndSendResponse(searchStrategy, searchTerm, event);
}
}
\ No newline at end of file
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java
new file mode 100644
index 0000000000..c73cda5e09
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java
@@ -0,0 +1,45 @@
+package org.togetherjava.tjbot.commands.search;
+
+import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.togetherjava.tjbot.commands.CommandVisibility;
+import org.togetherjava.tjbot.commands.SlashCommandAdapter;
+
+/**
+ * This class is designed for specific use in the #active_questions channel within the Together Java Discord server.
+ * As such, it is a convenience command that allows users to search their questions (thread title) on Google.
+ *
+ * @author Suraj Kumar
+ */
+public class GoogleItCommand extends SlashCommandAdapter {
+ private static final Logger logger = LoggerFactory.getLogger(GoogleItCommand.class);
+ /**
+ * The search strategy that is going to return the results to us.
+ */
+ private final SearchStrategy searchStrategy = new GoogleSearchStrategy();
+
+ /**
+ * Constructs a new {@code GoogleItCommand} object and sets up the metadata for this command including the name,
+ * description
+ */
+ public GoogleItCommand() {
+ super("googleit", "Searches the channel title on Google", CommandVisibility.GUILD);
+ }
+
+ @Override
+ public void onSlashCommand(SlashCommandInteractionEvent event) {
+ logger.info("Received /googleit slash command");
+ if(event.getChannel().getName().equals("active_questions")) {
+ try {
+ String searchTerm = event.getChannel().asThreadChannel().getName();
+ event.deferReply().queue();
+ new GoogleResponseComposer().doSearchAndSendResponse(searchStrategy, searchTerm, event);
+ } catch (IllegalStateException ex) {
+ event.reply("You must be within a thread in #active_questions to run this command.").queue();
+ }
+ } else {
+ event.reply("You must be within #active_questions to run this command.").queue();
+ }
+ }
+}
\ No newline at end of file
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java
new file mode 100644
index 0000000000..851d2ffabf
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java
@@ -0,0 +1,137 @@
+package org.togetherjava.tjbot.commands.search;
+
+import net.dv8tion.jda.api.EmbedBuilder;
+import net.dv8tion.jda.api.entities.MessageEmbed;
+import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.awt.*;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * A common class that is used for sending responses to Discord for a Google search request. This class contains
+ * functionality that allows you to get pre-constructed {@code MessageEmbed}s for dispatch to the user. Additionally,
+ * you can allow this composer class to do that for you.
+ *
+ * @author Suraj Kumar
+ */
+public class GoogleResponseComposer {
+ private static final Logger logger = LoggerFactory.getLogger(GoogleResponseComposer.class);
+ /**
+ * The maximum number of organic search results to show.
+ * When there are less than 5 results available in the search results,
+ * the amount returned is the number of available results. This flag does not affect the
+ * "People also asked" results.
+ */
+ private static final int MAX_RESULTS_TO_SHOW = 5;
+
+ public GoogleResponseComposer() { }
+
+ /**
+ * The main logic for the Google searching functionality. This method runs the Google search API, constructs
+ * a response and sends it to the user who invoked this request.
+ *
+ * @param searchStrategy The strategy to perform the search against.
+ * @param searchTerm The query to search on Google.
+ * @param event The Discord event so that a response can be sent.
+ */
+ public void doSearchAndSendResponse(SearchStrategy searchStrategy, String searchTerm, SlashCommandInteractionEvent event) {
+ searchStrategy.search(searchTerm)
+ .thenAccept(response -> {
+ MessageEmbed relatedQuestionsMessageEmbed = null;
+ JSONObject json = new JSONObject(response.body());
+ if (json.has("related_questions")) {
+ logger.info("related_questions present within response from Google, adding results to response");
+ relatedQuestionsMessageEmbed = createMessageEmbedForRelatedQuestions(json.getJSONArray("related_questions"), searchTerm);
+ }
+ if (json.has("organic_results")) {
+ logger.info("organic_results present within response from Google, adding results to response");
+ List embeds = createMessageEmbedForOrganicResults(json.getJSONArray("organic_results"));
+ if(relatedQuestionsMessageEmbed != null) {
+ Collections.reverse(embeds);
+ embeds.add(relatedQuestionsMessageEmbed);
+ Collections.reverse(embeds);
+ }
+ if (embeds.size() > 0) {
+ event.getHook().editOriginalEmbeds().setEmbeds(embeds).queue();
+ } else {
+ event.getHook()
+ .sendMessage("I could not find any results for your search term. Try rephrasing your search.")
+ .queue();
+ }
+ } else if(relatedQuestionsMessageEmbed != null) {
+ event.getHook().editOriginalEmbeds().setEmbeds(relatedQuestionsMessageEmbed).queue();
+ }
+ logger.info("Finished handling /google slash command.");
+ });
+ }
+
+ /**
+ * Creates a ready to send response containing the information for an organic search result.
+ * The response is set to be a separate message for each result.
+ *
+ * @param searchResults An array of organic search results to build the MessageEmbeds.
+ * @return A List of MessageEmbeds for dispatch.
+ */
+ public List createMessageEmbedForOrganicResults(JSONArray searchResults) {
+ logger.info("Creating a list of MessageEmbed for a total of {} results", searchResults.length());
+ List embeds = new ArrayList<>();
+ for (int i = 0; i < Math.min(searchResults.length(), MAX_RESULTS_TO_SHOW); i++) {
+ JSONObject result = searchResults.getJSONObject(i);
+ String title = result.getString("title");
+ String link = result.getString("link");
+ String snippet = result.getString("snippet");
+ EmbedBuilder eb = new EmbedBuilder();
+ eb.setAuthor(title, link, null);
+ eb.setDescription(snippet);
+ eb.setColor(Color.BLACK);
+ embeds.add(eb.build());
+ }
+ return embeds;
+ }
+
+ /**
+ * Creates a ready to send response containing the information for related questions search result.
+ * The response is set to be 1 single message containing all the information.
+ *
+ * @param relatedQuestions An array of related questions search results to build the MessageEmbeds.
+ * @return A List of MessageEmbeds for dispatch.
+ */
+ public MessageEmbed createMessageEmbedForRelatedQuestions(JSONArray relatedQuestions, String searchTerm) {
+ logger.info("Creating a MessageEmbed for a total of {} results", relatedQuestions.length());
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < relatedQuestions.length(); i++) {
+ JSONObject result = relatedQuestions.getJSONObject(i);
+ String question = result.getString("question");
+ String snippetOfAnswer = "";
+ if (result.has("snippet")) {
+ snippetOfAnswer = result.getString("snippet");
+ } else if (result.has("list")) {
+ StringBuilder list = new StringBuilder();
+ result.getJSONArray("list")
+ .toList()
+ .forEach(line -> list.append(line).append("\n"));
+ snippetOfAnswer = list.toString();
+ }
+ String link = result.getString("link");
+ sb.append("\n**")
+ .append(question)
+ .append("**")
+ .append("\n")
+ .append(snippetOfAnswer.trim())
+ .append("\n\n")
+ .append(link)
+ .append("\n");
+ }
+ return new EmbedBuilder()
+ .setAuthor("Here are some answers that I have found for " + searchTerm, null, null)
+ .setDescription(sb)
+ .setColor(Color.BLACK)
+ .build();
+ }
+}
\ No newline at end of file
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
index 0d2ef1d078..620ce50e80 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
@@ -8,16 +8,14 @@
import java.util.concurrent.CompletableFuture;
/**
- * {@code GoogleSearchStrategy} contains the logic for searching on Google.
- *
- * The service is provided by Serpapi is a wrapper over the Google API. This has
- * been used because it provides us with much easier access to the Google API without having to go through the complicated
- * process of setting up the application and auth on Google's side.
- *
+ * {@code GoogleSearchStrategy} contains the logic for searching on Google.
+ * The service is provided by Serpapi is a wrapper over the Google API. This has
+ * been used because it provides us with much easier access to the Google API without having to go through the complicated
+ * process of setting up the application and auth on Google's side.
* @author Suraj Kumar
*/
public class GoogleSearchStrategy extends SearchStrategy {
- /** The API key to provide authentication into Serpapi */
+ /** The API key to provide authentication into Serpapi. */
private static final String API_KEY =
"1d84500b082341aad66de5cf02f7c83d8608411b01b7ffcbb2d40042eea250df";
@@ -27,16 +25,18 @@ public class GoogleSearchStrategy extends SearchStrategy {
/** The HttpClient object used for sending the REST API calls. */
private final HttpClient httpClient = HttpClient.newHttpClient();
+ public GoogleSearchStrategy() {}
+
/**
- * Called the Serpapi API with the provided search term async. The result of the API is a JSON body that can be
- * used to grab all the information we need regarding the search and search contents.
- *
- * The Serpapi takes 2 parameters:
- * 1. q: The search query
- * 2. api_key: The authentication key created via the Serpapi dashboard.
- *
- * For additional parameters see: Serpapi API docs
- *
+ * Called the Serpapi API with the provided search term async.
+ * The result of the API is a JSON body that can be used to grab all the information we need regarding the search and
+ * search contents.
+ * The Serpapi takes 2 parameters:
+ *
+ * - q: The search query
+ * - api_key: The authentication key created via the Serpapi dashboard.
+ *
+ * For additional parameters see: Serpapi API docs
* @param searchTerm The search term to query against. This would be in the exact format a user would be searching
* on Google.
* @return A CompletableFuture as this action is blocking.
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java
index b2ef3f813f..b4163b04f8 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java
@@ -4,15 +4,14 @@
import java.util.concurrent.CompletableFuture;
/**
- * A base class for a search Strategy. This allows us to implement multiple variations of a search functionality
+ *
+ * A base class for a search Strategy. This allows us to implement multiple variations of a search functionality
* without having to rewrite any of the main logic (except parsing) used for getting search results. For
* example in the {@link GoogleSearchStrategy} the Serpapi API is used for fetching results from Google. If we were to
* change this, we can do by creating a new SearchStrategy and replace the existing call with the new strategy
- * without further code changes.
- *
- * Additionally, we now have flexibility to implement searching in other platforms such as Stackoverflow, Yahoo, Bing
- * etc.
- *
+ * without further code changes.
+ * Additionally, we now have flexibility to implement searching in other platforms such as Stackoverflow, Yahoo, Bing
+ * etc.
* @author Suraj Kumar
*/
public abstract class SearchStrategy {
From 10b0d5e11b21cf93efbbd047ebd612d76c78b175 Mon Sep 17 00:00:00 2001
From: Suraj Kumar <76599223+surajkumar@users.noreply.github.com>
Date: Fri, 14 Oct 2022 18:46:41 +0100
Subject: [PATCH 04/11] Googleit fix
---
.../tjbot/commands/search/GoogleItCommand.java | 16 ++++++++++------
1 file changed, 10 insertions(+), 6 deletions(-)
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java
index c73cda5e09..ffedbb2ff6 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java
@@ -19,6 +19,9 @@ public class GoogleItCommand extends SlashCommandAdapter {
*/
private final SearchStrategy searchStrategy = new GoogleSearchStrategy();
+ /** The error message displayed to the user if they are not within a thread in #active_questions. */
+ private static final String WRONG_CHANNEL_ERROR = "You must be within a thread in #active_questions to run this command.";
+
/**
* Constructs a new {@code GoogleItCommand} object and sets up the metadata for this command including the name,
* description
@@ -30,16 +33,17 @@ public GoogleItCommand() {
@Override
public void onSlashCommand(SlashCommandInteractionEvent event) {
logger.info("Received /googleit slash command");
- if(event.getChannel().getName().equals("active_questions")) {
- try {
+ try {
+ String parent = event.getChannel().asThreadChannel().getParentChannel().getName();
+ if(parent.equals("active_questions")) {
String searchTerm = event.getChannel().asThreadChannel().getName();
event.deferReply().queue();
new GoogleResponseComposer().doSearchAndSendResponse(searchStrategy, searchTerm, event);
- } catch (IllegalStateException ex) {
- event.reply("You must be within a thread in #active_questions to run this command.").queue();
+ } else {
+ event.reply(WRONG_CHANNEL_ERROR).queue();
}
- } else {
- event.reply("You must be within #active_questions to run this command.").queue();
+ } catch (IllegalStateException ex) {
+ event.reply(WRONG_CHANNEL_ERROR).queue();
}
}
}
\ No newline at end of file
From baa082dbdcf97817b425018af80a04506b7a61ea Mon Sep 17 00:00:00 2001
From: Suraj Kumar <76599223+surajkumar@users.noreply.github.com>
Date: Fri, 14 Oct 2022 18:50:45 +0100
Subject: [PATCH 05/11] API key from env variable
---
.../tjbot/commands/search/GoogleSearchStrategy.java | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
index 620ce50e80..1a637b046e 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
@@ -16,8 +16,7 @@
*/
public class GoogleSearchStrategy extends SearchStrategy {
/** The API key to provide authentication into Serpapi. */
- private static final String API_KEY =
- "1d84500b082341aad66de5cf02f7c83d8608411b01b7ffcbb2d40042eea250df";
+ private static final String API_KEY = System.getenv("serpapi-api-key");
/** The Serpapi REST service URL used for fetching Google search results. */
private static final String API_ENDPOINT = "https://serpapi.com/search";
From e8e7543a88cdb2165d1503b6907612e7ee9252e8 Mon Sep 17 00:00:00 2001
From: Suraj Kumar <76599223+surajkumar@users.noreply.github.com>
Date: Fri, 14 Oct 2022 20:29:44 +0100
Subject: [PATCH 06/11] Serfat API key from config file.
---
application/config.json.template | 89 -------------------
.../togetherjava/tjbot/commands/Features.java | 4 +-
.../tjbot/commands/search/GoogleCommand.java | 6 +-
.../commands/search/GoogleItCommand.java | 6 +-
.../commands/search/GoogleSearchStrategy.java | 8 +-
.../org/togetherjava/tjbot/config/Config.java | 16 +++-
6 files changed, 29 insertions(+), 100 deletions(-)
delete mode 100644 application/config.json.template
diff --git a/application/config.json.template b/application/config.json.template
deleted file mode 100644
index d7a3563a38..0000000000
--- a/application/config.json.template
+++ /dev/null
@@ -1,89 +0,0 @@
-{
- "token": "",
- "gistApiKey": "",
- "databasePath": "local-database.db",
- "projectWebsite": "https://github.com/Together-Java/TJ-Bot",
- "discordGuildInvite": "https://discord.com/invite/XXFUXzK",
- "modAuditLogChannelPattern": "mod_audit_log",
- "mutedRolePattern": "Muted",
- "heavyModerationRolePattern": "Moderator",
- "softModerationRolePattern": "Moderator|Staff Assistant",
- "tagManageRolePattern": "Moderator|Staff Assistant|Top Helpers .+",
- "suggestions": {
- "channelPattern": "tj_suggestions",
- "upVoteEmoteName": "peepo_yes",
- "downVoteEmoteName": "peepo_no"
- },
- "quarantinedRolePattern": "Quarantined",
- "scamBlocker": {
- "mode": "AUTO_DELETE_BUT_APPROVE_QUARANTINE",
- "reportChannelPattern": "commands",
- "hostWhitelist": ["discord.com", "discord.gg", "discord.media", "discordapp.com", "discordapp.net", "discordstatus.com"],
- "hostBlacklist": ["bit.ly"],
- "suspiciousHostKeywords": ["discord", "nitro", "premium"],
- "isHostSimilarToKeywordDistanceThreshold": 2
- },
- "wolframAlphaAppId": "79J52T-6239TVXHR7",
- "helpSystem": {
- "stagingChannelPattern": "ask_here",
- "overviewChannelPattern": "active_questions",
- "categories": [
- "Java",
- "Frameworks",
- "JavaFX|Swing",
- "IDE",
- "Build Tools",
- "Database",
- "Android",
- "C|C++",
- "Algorithms",
- "Math",
- "Architecture",
- "Code Review",
- "Together Java Bot",
- "Other"
- ],
- "categoryRoleSuffix": " - Helper"
- },
- "mediaOnlyChannelPattern": "memes",
- "blacklistedFileExtension": [
- "application",
- "bat",
- "cmd",
- "com",
- "cpl",
- "exe",
- "gadget",
- "hta",
- "inf",
- "jse",
- "lnk",
- "msc",
- "msh",
- "msh1",
- "msh1xml",
- "msh2",
- "msh2xml",
- "mshxml",
- "msi",
- "msp",
- "pif",
- "ps1",
- "ps1xml",
- "ps2",
- "ps2xml",
- "psc1",
- "psc2",
- "scf",
- "scr",
- "vb",
- "vbe",
- "vbs",
- "ws",
- "wsc",
- "wsf",
- "wsh"
- ],
- "logInfoChannelWebhook": "",
- "logErrorChannelWebhook": ""
-}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java
index 5055f5259c..867f14e7d0 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java
@@ -129,8 +129,8 @@ public static Collection createFeatures(JDA jda, Database database, Con
features.add(new WolframAlphaCommand(config));
features.add(new AskCommand(config, helpSystemHelper));
features.add(new HelpThreadCommand(config, helpSystemHelper));
- features.add(new GoogleCommand());
- features.add(new GoogleItCommand());
+ features.add(new GoogleCommand(config));
+ features.add(new GoogleItCommand(config));
// Mixtures
features.add(new HelpThreadOverviewUpdater(config, helpSystemHelper));
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
index e39fc30248..0abf2b732d 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
@@ -6,6 +6,7 @@
import org.slf4j.LoggerFactory;
import org.togetherjava.tjbot.commands.CommandVisibility;
import org.togetherjava.tjbot.commands.SlashCommandAdapter;
+import org.togetherjava.tjbot.config.Config;
import java.util.Objects;
/**
@@ -25,16 +26,17 @@ public class GoogleCommand extends SlashCommandAdapter {
/**
* The search strategy that is going to return the results to us.
*/
- private final SearchStrategy searchStrategy = new GoogleSearchStrategy();
+ private final SearchStrategy searchStrategy;
/**
* Constructs a new {@code GoogleCommand} object and sets up the metadata for this command including the name,
* description and command options.
*/
- public GoogleCommand() {
+ public GoogleCommand(Config config) {
super("google", "Searches Google for your search query", CommandVisibility.GUILD);
this.getData()
.addOption(OptionType.STRING, COMMAND_OPTION, "the query to send to Google", true);
+ searchStrategy = new GoogleSearchStrategy(config.getSerpapiApiKey());
}
/**
* The main logic for the /google command.
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java
index ffedbb2ff6..1fe2f04eed 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java
@@ -5,6 +5,7 @@
import org.slf4j.LoggerFactory;
import org.togetherjava.tjbot.commands.CommandVisibility;
import org.togetherjava.tjbot.commands.SlashCommandAdapter;
+import org.togetherjava.tjbot.config.Config;
/**
*
This class is designed for specific use in the #active_questions channel within the Together Java Discord server.
@@ -17,7 +18,7 @@ public class GoogleItCommand extends SlashCommandAdapter {
/**
* The search strategy that is going to return the results to us.
*/
- private final SearchStrategy searchStrategy = new GoogleSearchStrategy();
+ private final SearchStrategy searchStrategy;
/** The error message displayed to the user if they are not within a thread in #active_questions. */
private static final String WRONG_CHANNEL_ERROR = "You must be within a thread in #active_questions to run this command.";
@@ -26,8 +27,9 @@ public class GoogleItCommand extends SlashCommandAdapter {
*
Constructs a new {@code GoogleItCommand} object and sets up the metadata for this command including the name,
* description
*/
- public GoogleItCommand() {
+ public GoogleItCommand(Config config) {
super("googleit", "Searches the channel title on Google", CommandVisibility.GUILD);
+ searchStrategy = new GoogleSearchStrategy(config.getSerpapiApiKey());
}
@Override
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
index 1a637b046e..1c495a78dd 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
@@ -16,7 +16,7 @@
*/
public class GoogleSearchStrategy extends SearchStrategy {
/** The API key to provide authentication into Serpapi. */
- private static final String API_KEY = System.getenv("serpapi-api-key");
+ private final String apiKey;
/** The Serpapi REST service URL used for fetching Google search results. */
private static final String API_ENDPOINT = "https://serpapi.com/search";
@@ -24,7 +24,9 @@ public class GoogleSearchStrategy extends SearchStrategy {
/** The HttpClient object used for sending the REST API calls. */
private final HttpClient httpClient = HttpClient.newHttpClient();
- public GoogleSearchStrategy() {}
+ public GoogleSearchStrategy(String apiKey) {
+ this.apiKey = apiKey;
+ }
/**
* Called the Serpapi API with the provided search term async.
@@ -46,7 +48,7 @@ public CompletableFuture> search(String searchTerm) {
HttpRequest
.newBuilder(UrlBuilder.fromString(API_ENDPOINT)
.addParameter("q", searchTerm)
- .addParameter("api_key", API_KEY)
+ .addParameter("api_key", apiKey)
.toUri())
.GET()
.build(),
diff --git a/application/src/main/java/org/togetherjava/tjbot/config/Config.java b/application/src/main/java/org/togetherjava/tjbot/config/Config.java
index d9b9d8a88f..47ae0fb2d3 100644
--- a/application/src/main/java/org/togetherjava/tjbot/config/Config.java
+++ b/application/src/main/java/org/togetherjava/tjbot/config/Config.java
@@ -34,6 +34,7 @@ public final class Config {
private final String mediaOnlyChannelPattern;
private final String logInfoChannelWebhook;
private final String logErrorChannelWebhook;
+ private final String serpapiApiKey;
@SuppressWarnings("ConstructorWithTooManyParameters")
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
@@ -64,7 +65,9 @@ private Config(@JsonProperty(value = "token", required = true) String token,
@JsonProperty(value = "logInfoChannelWebhook",
required = true) String logInfoChannelWebhook,
@JsonProperty(value = "logErrorChannelWebhook",
- required = true) String logErrorChannelWebhook) {
+ required = true) String logErrorChannelWebhook,
+ @JsonProperty(value = "serpapiApiKey",
+ required = true) String serpapiApiKey) {
this.token = Objects.requireNonNull(token);
this.gistApiKey = Objects.requireNonNull(gistApiKey);
this.databasePath = Objects.requireNonNull(databasePath);
@@ -84,6 +87,7 @@ private Config(@JsonProperty(value = "token", required = true) String token,
this.blacklistedFileExtension = Objects.requireNonNull(blacklistedFileExtension);
this.logInfoChannelWebhook = Objects.requireNonNull(logInfoChannelWebhook);
this.logErrorChannelWebhook = Objects.requireNonNull(logErrorChannelWebhook);
+ this.serpapiApiKey = serpapiApiKey;
}
/**
@@ -275,4 +279,12 @@ public String getLogInfoChannelWebhook() {
public String getLogErrorChannelWebhook() {
return logErrorChannelWebhook;
}
-}
+
+ /**
+ * The Serpapi API key to pass to the service call.
+ * @return The API key
+ */
+ public String getSerpapiApiKey() {
+ return serpapiApiKey;
+ }
+}
\ No newline at end of file
From 3bb4cc6db29b90f85ab4749c980ea364167924b1 Mon Sep 17 00:00:00 2001
From: Suraj Kumar <76599223+surajkumar@users.noreply.github.com>
Date: Fri, 14 Oct 2022 20:46:27 +0100
Subject: [PATCH 07/11] Object.requireNonNull on serpapi api key
---
.../src/main/java/org/togetherjava/tjbot/config/Config.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/application/src/main/java/org/togetherjava/tjbot/config/Config.java b/application/src/main/java/org/togetherjava/tjbot/config/Config.java
index 47ae0fb2d3..2fa90db55f 100644
--- a/application/src/main/java/org/togetherjava/tjbot/config/Config.java
+++ b/application/src/main/java/org/togetherjava/tjbot/config/Config.java
@@ -87,7 +87,7 @@ private Config(@JsonProperty(value = "token", required = true) String token,
this.blacklistedFileExtension = Objects.requireNonNull(blacklistedFileExtension);
this.logInfoChannelWebhook = Objects.requireNonNull(logInfoChannelWebhook);
this.logErrorChannelWebhook = Objects.requireNonNull(logErrorChannelWebhook);
- this.serpapiApiKey = serpapiApiKey;
+ this.serpapiApiKey = Objects.requireNonNull(serpapiApiKey);
}
/**
From 5d7868dc6d0bd092a60fcf6bea33a1f19328f077 Mon Sep 17 00:00:00 2001
From: Suraj Kumar <76599223+surajkumar@users.noreply.github.com>
Date: Fri, 14 Oct 2022 20:51:37 +0100
Subject: [PATCH 08/11] Added generics to SearchStrategy
---
.../tjbot/commands/search/GoogleResponseComposer.java | 4 +++-
.../tjbot/commands/search/GoogleSearchStrategy.java | 2 +-
.../togetherjava/tjbot/commands/search/SearchStrategy.java | 5 ++---
3 files changed, 6 insertions(+), 5 deletions(-)
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java
index 851d2ffabf..1c99d86f1d 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java
@@ -9,6 +9,7 @@
import org.slf4j.LoggerFactory;
import java.awt.*;
+import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -43,8 +44,9 @@ public GoogleResponseComposer() { }
public void doSearchAndSendResponse(SearchStrategy searchStrategy, String searchTerm, SlashCommandInteractionEvent event) {
searchStrategy.search(searchTerm)
.thenAccept(response -> {
+ HttpResponse httpResponse = (HttpResponse) response;
+ JSONObject json = new JSONObject(httpResponse.body());
MessageEmbed relatedQuestionsMessageEmbed = null;
- JSONObject json = new JSONObject(response.body());
if (json.has("related_questions")) {
logger.info("related_questions present within response from Google, adding results to response");
relatedQuestionsMessageEmbed = createMessageEmbedForRelatedQuestions(json.getJSONArray("related_questions"), searchTerm);
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
index 1c495a78dd..3850f5a3b1 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
@@ -14,7 +14,7 @@
* process of setting up the application and auth on Google's side.
* @author Suraj Kumar
*/
-public class GoogleSearchStrategy extends SearchStrategy {
+public class GoogleSearchStrategy extends SearchStrategy> {
/** The API key to provide authentication into Serpapi. */
private final String apiKey;
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java
index b4163b04f8..5f6659d677 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java
@@ -1,6 +1,5 @@
package org.togetherjava.tjbot.commands.search;
-import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
/**
@@ -14,7 +13,7 @@
* etc.
* @author Suraj Kumar
*/
-public abstract class SearchStrategy {
+public abstract class SearchStrategy {
/**
* A common search function that should asynchronously handle a search function for a given term.
@@ -22,5 +21,5 @@ public abstract class SearchStrategy {
* @param searchTerm The search term to look for.
* @return A CompletableFuture for retrieval of the response when ready.
*/
- public abstract CompletableFuture> search(String searchTerm);
+ public abstract CompletableFuture search(String searchTerm);
}
\ No newline at end of file
From ac89c6b8896e05a7b98509ac68535057c3ab65d5 Mon Sep 17 00:00:00 2001
From: Suraj Kumar <76599223+surajkumar@users.noreply.github.com>
Date: Fri, 14 Oct 2022 20:53:50 +0100
Subject: [PATCH 09/11] Fixed raw use warning
---
.../togetherjava/tjbot/commands/search/GoogleCommand.java | 3 ++-
.../togetherjava/tjbot/commands/search/GoogleItCommand.java | 4 +++-
.../tjbot/commands/search/GoogleResponseComposer.java | 5 ++---
3 files changed, 7 insertions(+), 5 deletions(-)
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
index 0abf2b732d..6c30034d8e 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
@@ -8,6 +8,7 @@
import org.togetherjava.tjbot.commands.SlashCommandAdapter;
import org.togetherjava.tjbot.config.Config;
+import java.net.http.HttpResponse;
import java.util.Objects;
/**
* This class contains the logic required for the '/google' slash command.
@@ -26,7 +27,7 @@ public class GoogleCommand extends SlashCommandAdapter {
/**
* The search strategy that is going to return the results to us.
*/
- private final SearchStrategy searchStrategy;
+ private final SearchStrategy> searchStrategy;
/**
* Constructs a new {@code GoogleCommand} object and sets up the metadata for this command including the name,
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java
index 1fe2f04eed..586803ce89 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java
@@ -7,6 +7,8 @@
import org.togetherjava.tjbot.commands.SlashCommandAdapter;
import org.togetherjava.tjbot.config.Config;
+import java.net.http.HttpResponse;
+
/**
*
This class is designed for specific use in the #active_questions channel within the Together Java Discord server.
* As such, it is a convenience command that allows users to search their questions (thread title) on Google.
@@ -18,7 +20,7 @@ public class GoogleItCommand extends SlashCommandAdapter {
/**
* The search strategy that is going to return the results to us.
*/
- private final SearchStrategy searchStrategy;
+ private final SearchStrategy> searchStrategy;
/** The error message displayed to the user if they are not within a thread in #active_questions. */
private static final String WRONG_CHANNEL_ERROR = "You must be within a thread in #active_questions to run this command.";
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java
index 1c99d86f1d..48b4cf9fe4 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java
@@ -41,11 +41,10 @@ public GoogleResponseComposer() { }
* @param searchTerm The query to search on Google.
* @param event The Discord event so that a response can be sent.
*/
- public void doSearchAndSendResponse(SearchStrategy searchStrategy, String searchTerm, SlashCommandInteractionEvent event) {
+ public void doSearchAndSendResponse(SearchStrategy> searchStrategy, String searchTerm, SlashCommandInteractionEvent event) {
searchStrategy.search(searchTerm)
.thenAccept(response -> {
- HttpResponse httpResponse = (HttpResponse) response;
- JSONObject json = new JSONObject(httpResponse.body());
+ JSONObject json = new JSONObject(response.body());
MessageEmbed relatedQuestionsMessageEmbed = null;
if (json.has("related_questions")) {
logger.info("related_questions present within response from Google, adding results to response");
From 200f280c7f402454a42590e80fc95da501243c28 Mon Sep 17 00:00:00 2001
From: Suraj Kumar <76599223+surajkumar@users.noreply.github.com>
Date: Fri, 14 Oct 2022 20:57:26 +0100
Subject: [PATCH 10/11] Log levels
---
.../tjbot/commands/search/GoogleCommand.java | 2 +-
.../tjbot/commands/search/GoogleResponseComposer.java | 10 +++++-----
2 files changed, 6 insertions(+), 6 deletions(-)
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
index 6c30034d8e..6b1da123e3 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
@@ -52,7 +52,7 @@ public void onSlashCommand(SlashCommandInteractionEvent event) {
event.deferReply().queue();
String searchTerm = Objects.requireNonNull(event.getOption(COMMAND_OPTION)).getAsString();
- logger.info("{} entered search term {}", Objects.requireNonNull(event.getMember()).getEffectiveName(), searchTerm);
+ logger.debug("{} entered search term {}", Objects.requireNonNull(event.getMember()).getEffectiveName(), searchTerm);
new GoogleResponseComposer().doSearchAndSendResponse(searchStrategy, searchTerm, event);
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java
index 48b4cf9fe4..603a68d756 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java
@@ -47,11 +47,11 @@ public void doSearchAndSendResponse(SearchStrategy> searchS
JSONObject json = new JSONObject(response.body());
MessageEmbed relatedQuestionsMessageEmbed = null;
if (json.has("related_questions")) {
- logger.info("related_questions present within response from Google, adding results to response");
+ logger.trace("related_questions present within response from Google, adding results to response");
relatedQuestionsMessageEmbed = createMessageEmbedForRelatedQuestions(json.getJSONArray("related_questions"), searchTerm);
}
if (json.has("organic_results")) {
- logger.info("organic_results present within response from Google, adding results to response");
+ logger.trace("organic_results present within response from Google, adding results to response");
List embeds = createMessageEmbedForOrganicResults(json.getJSONArray("organic_results"));
if(relatedQuestionsMessageEmbed != null) {
Collections.reverse(embeds);
@@ -80,7 +80,7 @@ public void doSearchAndSendResponse(SearchStrategy> searchS
* @return A List of MessageEmbeds for dispatch.
*/
public List createMessageEmbedForOrganicResults(JSONArray searchResults) {
- logger.info("Creating a list of MessageEmbed for a total of {} results", searchResults.length());
+ logger.trace("Creating a list of MessageEmbed for a total of {} results", searchResults.length());
List embeds = new ArrayList<>();
for (int i = 0; i < Math.min(searchResults.length(), MAX_RESULTS_TO_SHOW); i++) {
JSONObject result = searchResults.getJSONObject(i);
@@ -90,7 +90,7 @@ public List createMessageEmbedForOrganicResults(JSONArray searchRe
EmbedBuilder eb = new EmbedBuilder();
eb.setAuthor(title, link, null);
eb.setDescription(snippet);
- eb.setColor(Color.BLACK);
+ eb.setColor(Color.RED);
embeds.add(eb.build());
}
return embeds;
@@ -104,7 +104,7 @@ public List createMessageEmbedForOrganicResults(JSONArray searchRe
* @return A List of MessageEmbeds for dispatch.
*/
public MessageEmbed createMessageEmbedForRelatedQuestions(JSONArray relatedQuestions, String searchTerm) {
- logger.info("Creating a MessageEmbed for a total of {} results", relatedQuestions.length());
+ logger.trace("Creating a MessageEmbed for a total of {} results", relatedQuestions.length());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < relatedQuestions.length(); i++) {
JSONObject result = relatedQuestions.getJSONObject(i);
From dae024835dcd6853dd75bd1e82568a60dbcb88f1 Mon Sep 17 00:00:00 2001
From: Suraj Kumar <76599223+surajkumar@users.noreply.github.com>
Date: Sat, 15 Oct 2022 11:01:52 +0100
Subject: [PATCH 11/11] Solarlint changes
---
.../togetherjava/tjbot/commands/Features.java | 4 +-
.../tjbot/commands/help/HelpSystemHelper.java | 5 +-
.../tjbot/commands/search/GoogleCommand.java | 39 +++--
.../commands/search/GoogleItCommand.java | 28 ++-
.../search/GoogleResponseComposer.java | 160 ++++++++++--------
.../commands/search/GoogleSearchStrategy.java | 39 +++--
.../tjbot/commands/search/SearchStrategy.java | 27 +--
.../org/togetherjava/tjbot/config/Config.java | 6 +-
8 files changed, 186 insertions(+), 122 deletions(-)
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java
index 867f14e7d0..97780e30fb 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java
@@ -84,7 +84,7 @@ public static Collection createFeatures(JDA jda, Database database, Con
features.add(new HelpThreadMetadataPurger(database));
features.add(new HelpThreadActivityUpdater(helpSystemHelper));
features
- .add(new AutoPruneHelperRoutine(config, helpSystemHelper, modAuditLogWriter, database));
+ .add(new AutoPruneHelperRoutine(config, helpSystemHelper, modAuditLogWriter, database));
features.add(new HelpThreadAutoArchiver(helpSystemHelper));
// Message receivers
@@ -137,4 +137,4 @@ public static Collection createFeatures(JDA jda, Database database, Con
return features;
}
-}
\ No newline at end of file
+}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java b/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java
index 4abe4ed2fc..9c01515883 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java
@@ -132,8 +132,7 @@ private RestAction sendExplanationMessage(GuildMessageChannel threadCha
.formatted(closeCommandMention)),
HelpSystemHelper.embedWith(
- "You can now search your question on Google using the `/google` slash command! If you want me to search your question for you, just enter the slash command `/googleit`")
- );
+ "You can now search your question on Google using the `/google` slash command! If you want me to search your question for you, just enter the slash command `/googleit`"));
MessageCreateAction action = threadChannel.sendMessage(message);
if (useCodeSyntaxExampleImage) {
@@ -387,4 +386,4 @@ static ThreadActivity ofSymbol(String symbol) {
"Unknown thread activity symbol: " + symbol));
}
}
-}
\ No newline at end of file
+}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
index 6b1da123e3..e8010e11b0 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java
@@ -4,17 +4,25 @@
import net.dv8tion.jda.api.interactions.commands.OptionType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
import org.togetherjava.tjbot.commands.CommandVisibility;
import org.togetherjava.tjbot.commands.SlashCommandAdapter;
import org.togetherjava.tjbot.config.Config;
import java.net.http.HttpResponse;
import java.util.Objects;
+
/**
- * This class contains the logic required for the '/google' slash command.
- * The syntax of the command is as followed: /google query [search term].
- * Results are sent to the user as embeds. The result contains the questions and answers of the search results under
- * "People also asked" alongside the first 5 organic search results.
+ *
+ * This class contains the logic required for the '/google' slash command.
+ *
+ *
+ * The syntax of the command is as followed: /google query [search term].
+ *
+ *
+ * Results are sent to the user as embeds. The result contains the questions and answers of the
+ * search results under "People also asked" alongside the first 5 organic search results.
+ *
*
* @author Suraj Kumar
*/
@@ -30,19 +38,25 @@ public class GoogleCommand extends SlashCommandAdapter {
private final SearchStrategy> searchStrategy;
/**
- * Constructs a new {@code GoogleCommand} object and sets up the metadata for this command including the name,
- * description and command options.
+ *
+ * Constructs a new {@code GoogleCommand} object and sets up the metadata for this command
+ * including the name, description and command options.
+ *
*/
public GoogleCommand(Config config) {
super("google", "Searches Google for your search query", CommandVisibility.GUILD);
this.getData()
- .addOption(OptionType.STRING, COMMAND_OPTION, "the query to send to Google", true);
+ .addOption(OptionType.STRING, COMMAND_OPTION, "the query to send to Google", true);
searchStrategy = new GoogleSearchStrategy(config.getSerpapiApiKey());
}
+
/**
- * The main logic for the /google command.
- * When we receive the event from discord, the reply is deferred for a later period of time. This is because calling
- * the {@link org.togetherjava.tjbot.commands.search.SearchStrategy} is considered a blocking operation.
+ *
+ * The main logic for the /google command. When we receive the event from discord, the reply is
+ * deferred for a later period of time. This is because calling the
+ * {@link org.togetherjava.tjbot.commands.search.SearchStrategy} is considered a blocking
+ * operation.
+ *
*
* @param event the event provided by Discord to ack the initialization of the slash command.
*/
@@ -52,8 +66,9 @@ public void onSlashCommand(SlashCommandInteractionEvent event) {
event.deferReply().queue();
String searchTerm = Objects.requireNonNull(event.getOption(COMMAND_OPTION)).getAsString();
- logger.debug("{} entered search term {}", Objects.requireNonNull(event.getMember()).getEffectiveName(), searchTerm);
+ logger.debug("{} entered search term {}",
+ Objects.requireNonNull(event.getMember()).getEffectiveName(), searchTerm);
new GoogleResponseComposer().doSearchAndSendResponse(searchStrategy, searchTerm, event);
}
-}
\ No newline at end of file
+}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java
index 586803ce89..464636a73a 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java
@@ -3,6 +3,7 @@
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
import org.togetherjava.tjbot.commands.CommandVisibility;
import org.togetherjava.tjbot.commands.SlashCommandAdapter;
import org.togetherjava.tjbot.config.Config;
@@ -10,8 +11,11 @@
import java.net.http.HttpResponse;
/**
- * This class is designed for specific use in the #active_questions channel within the Together Java Discord server.
- * As such, it is a convenience command that allows users to search their questions (thread title) on Google.
+ *
+ * This class is designed for specific use in the #active_questions channel within the Together Java
+ * Discord server. As such, it is a convenience command that allows users to search their questions
+ * (thread title) on Google.
+ *
*
* @author Suraj Kumar
*/
@@ -22,12 +26,17 @@ public class GoogleItCommand extends SlashCommandAdapter {
*/
private final SearchStrategy> searchStrategy;
- /** The error message displayed to the user if they are not within a thread in #active_questions. */
- private static final String WRONG_CHANNEL_ERROR = "You must be within a thread in #active_questions to run this command.";
+ /**
+ * The error message displayed to the user if they are not within a thread in #active_questions.
+ */
+ private static final String WRONG_CHANNEL_ERROR =
+ "You must be within a thread in #active_questions to run this command.";
/**
- * Constructs a new {@code GoogleItCommand} object and sets up the metadata for this command including the name,
- * description
+ *
+ * Constructs a new {@code GoogleItCommand} object and sets up the metadata for this command
+ * including the name, description
+ *
*/
public GoogleItCommand(Config config) {
super("googleit", "Searches the channel title on Google", CommandVisibility.GUILD);
@@ -39,10 +48,11 @@ public void onSlashCommand(SlashCommandInteractionEvent event) {
logger.info("Received /googleit slash command");
try {
String parent = event.getChannel().asThreadChannel().getParentChannel().getName();
- if(parent.equals("active_questions")) {
+ if (parent.equals("active_questions")) {
String searchTerm = event.getChannel().asThreadChannel().getName();
event.deferReply().queue();
- new GoogleResponseComposer().doSearchAndSendResponse(searchStrategy, searchTerm, event);
+ new GoogleResponseComposer().doSearchAndSendResponse(searchStrategy, searchTerm,
+ event);
} else {
event.reply(WRONG_CHANNEL_ERROR).queue();
}
@@ -50,4 +60,4 @@ public void onSlashCommand(SlashCommandInteractionEvent event) {
event.reply(WRONG_CHANNEL_ERROR).queue();
}
}
-}
\ No newline at end of file
+}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java
index 603a68d756..fb5332fe3c 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java
@@ -15,78 +15,97 @@
import java.util.List;
/**
- * A common class that is used for sending responses to Discord for a Google search request. This class contains
- * functionality that allows you to get pre-constructed {@code MessageEmbed}s for dispatch to the user. Additionally,
- * you can allow this composer class to do that for you.
+ *
+ * A common class that is used for sending responses to Discord for a Google search request. This
+ * class contains functionality that allows you to get pre-constructed {@code MessageEmbed}s for
+ * dispatch to the user. Additionally, you can allow this composer class to do that for you.
+ *
*
* @author Suraj Kumar
*/
public class GoogleResponseComposer {
private static final Logger logger = LoggerFactory.getLogger(GoogleResponseComposer.class);
/**
- * The maximum number of organic search results to show.
- * When there are less than 5 results available in the search results,
- * the amount returned is the number of available results. This flag does not affect the
- * "People also asked" results.
+ * The maximum number of organic search results to show. When there are less than 5 results
+ * available in the search results, the amount returned is the number of available results. This
+ * flag does not affect the "People also asked" results.
*/
private static final int MAX_RESULTS_TO_SHOW = 5;
- public GoogleResponseComposer() { }
+ /** These are the JSON fields that contain the data needed for the response messages. */
+ private static final String RELATED_QUESTIONS_KEY = "related_questions";
+ private static final String ORGANIC_KEY = "organic_results";
+ private static final String TITLE_KEY = "title";
+ private static final String LINK_KEY = "link";
+ private static final String SNIPPET_KEY = "snippet";
+ private static final String LIST_KEY = "list";
+ private static final String QUESTION_KEY = "question";
/**
- * The main logic for the Google searching functionality. This method runs the Google search API, constructs
- * a response and sends it to the user who invoked this request.
+ *
+ * The main logic for the Google searching functionality. This method runs the Google search
+ * API, constructs a response and sends it to the user who invoked this request.
+ *
*
* @param searchStrategy The strategy to perform the search against.
* @param searchTerm The query to search on Google.
* @param event The Discord event so that a response can be sent.
*/
- public void doSearchAndSendResponse(SearchStrategy> searchStrategy, String searchTerm, SlashCommandInteractionEvent event) {
- searchStrategy.search(searchTerm)
- .thenAccept(response -> {
- JSONObject json = new JSONObject(response.body());
- MessageEmbed relatedQuestionsMessageEmbed = null;
- if (json.has("related_questions")) {
- logger.trace("related_questions present within response from Google, adding results to response");
- relatedQuestionsMessageEmbed = createMessageEmbedForRelatedQuestions(json.getJSONArray("related_questions"), searchTerm);
- }
- if (json.has("organic_results")) {
- logger.trace("organic_results present within response from Google, adding results to response");
- List embeds = createMessageEmbedForOrganicResults(json.getJSONArray("organic_results"));
- if(relatedQuestionsMessageEmbed != null) {
- Collections.reverse(embeds);
- embeds.add(relatedQuestionsMessageEmbed);
- Collections.reverse(embeds);
- }
- if (embeds.size() > 0) {
- event.getHook().editOriginalEmbeds().setEmbeds(embeds).queue();
- } else {
- event.getHook()
- .sendMessage("I could not find any results for your search term. Try rephrasing your search.")
- .queue();
- }
- } else if(relatedQuestionsMessageEmbed != null) {
- event.getHook().editOriginalEmbeds().setEmbeds(relatedQuestionsMessageEmbed).queue();
- }
- logger.info("Finished handling /google slash command.");
- });
+ public void doSearchAndSendResponse(SearchStrategy> searchStrategy,
+ String searchTerm, SlashCommandInteractionEvent event) {
+ searchStrategy.search(searchTerm).thenAccept(response -> {
+ JSONObject json = new JSONObject(response.body());
+ MessageEmbed relatedQuestionsMessageEmbed = null;
+ if (json.has(RELATED_QUESTIONS_KEY)) {
+ logger.trace(
+ "related_questions present within response from Google, adding results to response");
+ relatedQuestionsMessageEmbed = createMessageEmbedForRelatedQuestions(
+ json.getJSONArray(RELATED_QUESTIONS_KEY), searchTerm);
+ }
+ if (json.has(ORGANIC_KEY)) {
+ logger.trace(
+ "organic_results present within response from Google, adding results to response");
+ List embeds =
+ createMessageEmbedForOrganicResults(json.getJSONArray(ORGANIC_KEY));
+ if (relatedQuestionsMessageEmbed != null) {
+ Collections.reverse(embeds);
+ embeds.add(relatedQuestionsMessageEmbed);
+ Collections.reverse(embeds);
+ }
+ if (!embeds.isEmpty()) {
+ event.getHook().editOriginalEmbeds().setEmbeds(embeds).queue();
+ } else {
+ event.getHook()
+ .sendMessage(
+ "I could not find any results for your search term. Try rephrasing your search.")
+ .queue();
+ }
+ } else if (relatedQuestionsMessageEmbed != null) {
+ event.getHook()
+ .editOriginalEmbeds()
+ .setEmbeds(relatedQuestionsMessageEmbed)
+ .queue();
+ }
+ logger.info("Finished handling /google slash command.");
+ });
}
/**
- * Creates a ready to send response containing the information for an organic search result.
- * The response is set to be a separate message for each result.
+ * Creates a ready to send response containing the information for an organic search result. The
+ * response is set to be a separate message for each result.
*
* @param searchResults An array of organic search results to build the MessageEmbeds.
* @return A List of MessageEmbeds for dispatch.
*/
public List createMessageEmbedForOrganicResults(JSONArray searchResults) {
- logger.trace("Creating a list of MessageEmbed for a total of {} results", searchResults.length());
+ logger.trace("Creating a list of MessageEmbed for a total of {} results",
+ searchResults.length());
List embeds = new ArrayList<>();
for (int i = 0; i < Math.min(searchResults.length(), MAX_RESULTS_TO_SHOW); i++) {
JSONObject result = searchResults.getJSONObject(i);
- String title = result.getString("title");
- String link = result.getString("link");
- String snippet = result.getString("snippet");
+ String title = result.getString(TITLE_KEY);
+ String link = result.getString(LINK_KEY);
+ String snippet = result.getString(SNIPPET_KEY);
EmbedBuilder eb = new EmbedBuilder();
eb.setAuthor(title, link, null);
eb.setDescription(snippet);
@@ -97,42 +116,45 @@ public List createMessageEmbedForOrganicResults(JSONArray searchRe
}
/**
- * Creates a ready to send response containing the information for related questions search result.
- * The response is set to be 1 single message containing all the information.
+ * Creates a ready to send response containing the information for related questions search
+ * result. The response is set to be 1 single message containing all the information.
*
- * @param relatedQuestions An array of related questions search results to build the MessageEmbeds.
+ * @param relatedQuestions An array of related questions search results to build the
+ * MessageEmbeds.
* @return A List of MessageEmbeds for dispatch.
*/
- public MessageEmbed createMessageEmbedForRelatedQuestions(JSONArray relatedQuestions, String searchTerm) {
- logger.trace("Creating a MessageEmbed for a total of {} results", relatedQuestions.length());
+ public MessageEmbed createMessageEmbedForRelatedQuestions(JSONArray relatedQuestions,
+ String searchTerm) {
+ logger.trace("Creating a MessageEmbed for a total of {} results",
+ relatedQuestions.length());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < relatedQuestions.length(); i++) {
JSONObject result = relatedQuestions.getJSONObject(i);
- String question = result.getString("question");
+ String question = result.getString(QUESTION_KEY);
String snippetOfAnswer = "";
- if (result.has("snippet")) {
- snippetOfAnswer = result.getString("snippet");
- } else if (result.has("list")) {
+ if (result.has(SNIPPET_KEY)) {
+ snippetOfAnswer = result.getString(SNIPPET_KEY);
+ } else if (result.has(LIST_KEY)) {
StringBuilder list = new StringBuilder();
- result.getJSONArray("list")
- .toList()
- .forEach(line -> list.append(line).append("\n"));
+ result.getJSONArray(LIST_KEY)
+ .toList()
+ .forEach(line -> list.append(line).append("\n"));
snippetOfAnswer = list.toString();
}
- String link = result.getString("link");
+ String link = result.getString(LINK_KEY);
sb.append("\n**")
- .append(question)
- .append("**")
- .append("\n")
- .append(snippetOfAnswer.trim())
- .append("\n\n")
- .append(link)
- .append("\n");
+ .append(question)
+ .append("**")
+ .append("\n")
+ .append(snippetOfAnswer.trim())
+ .append("\n\n")
+ .append(link)
+ .append("\n");
}
return new EmbedBuilder()
- .setAuthor("Here are some answers that I have found for " + searchTerm, null, null)
- .setDescription(sb)
- .setColor(Color.BLACK)
- .build();
+ .setAuthor("Here are some answers that I have found for " + searchTerm, null, null)
+ .setDescription(sb)
+ .setColor(Color.BLACK)
+ .build();
}
}
\ No newline at end of file
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
index 3850f5a3b1..5d7dd2192f 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java
@@ -8,13 +8,19 @@
import java.util.concurrent.CompletableFuture;
/**
- * {@code GoogleSearchStrategy} contains the logic for searching on Google.
- * The service is provided by Serpapi is a wrapper over the Google API. This has
- * been used because it provides us with much easier access to the Google API without having to go through the complicated
- * process of setting up the application and auth on Google's side.
+ *
+ * {@code GoogleSearchStrategy} contains the logic for searching on Google.
+ *
+ *
+ * The service is provided by Serpapi is a wrapper over the
+ * Google API. This has been used because it provides us with much easier access to the Google API
+ * without having to go through the complicated process of setting up the application and auth on
+ * Google's side.
+ *
+ *
* @author Suraj Kumar
*/
-public class GoogleSearchStrategy extends SearchStrategy> {
+public class GoogleSearchStrategy implements SearchStrategy> {
/** The API key to provide authentication into Serpapi. */
private final String apiKey;
@@ -29,18 +35,25 @@ public GoogleSearchStrategy(String apiKey) {
}
/**
- * Called the Serpapi API with the provided search term async.
- * The result of the API is a JSON body that can be used to grab all the information we need regarding the search and
- * search contents.
- * The Serpapi takes 2 parameters:
+ *
+ * Called the Serpapi API with the provided search term async.
+ *
+ *
+ * The result of the API is a JSON body that can be used to grab all the information we need
+ * regarding the search and search contents.
+ *
+ *
+ * The Serpapi takes 2 parameters:
*
* - q: The search query
* - api_key: The authentication key created via the Serpapi dashboard.
- *
+ *
+ *
* For additional parameters see: Serpapi API docs
- * @param searchTerm The search term to query against. This would be in the exact format a user would be searching
- * on Google.
- * @return A CompletableFuture as this action is blocking.
+ *
+ * @param searchTerm The search term to query against. This would be in the exact format a user
+ * would be searching on Google.
+ * @return A CompletableFuture as this action is blocking.
*/
@Override
public CompletableFuture> search(String searchTerm) {
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java
index 5f6659d677..37c70edbc9 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java
@@ -4,22 +4,27 @@
/**
*
- * A base class for a search Strategy. This allows us to implement multiple variations of a search functionality
- * without having to rewrite any of the main logic (except parsing) used for getting search results. For
- * example in the {@link GoogleSearchStrategy} the Serpapi API is used for fetching results from Google. If we were to
- * change this, we can do by creating a new SearchStrategy and replace the existing call with the new strategy
- * without further code changes.
- * Additionally, we now have flexibility to implement searching in other platforms such as Stackoverflow, Yahoo, Bing
- * etc.
+ * A base class for a search Strategy. This allows us to implement multiple variations of a search
+ * functionality without having to rewrite any of the main logic (except parsing) used for getting
+ * search results. For example in the {@link GoogleSearchStrategy} the Serpapi API is used for
+ * fetching results from Google. If we were to change this, we can do by creating a new
+ * SearchStrategy and replace the existing call with the new strategy without further code changes.
+ *
+ *
+ * Additionally, we now have flexibility to implement searching in other platforms such as
+ * Stackoverflow, Yahoo, Bing etc.
+ *
+ *
* @author Suraj Kumar
*/
-public abstract class SearchStrategy {
+public interface SearchStrategy {
/**
- * A common search function that should asynchronously handle a search function for a given term.
+ * A common search function that should asynchronously handle a search function for a given
+ * term.
*
* @param searchTerm The search term to look for.
- * @return A CompletableFuture for retrieval of the response when ready.
+ * @return A CompletableFuture for retrieval of the response when ready.
*/
- public abstract CompletableFuture search(String searchTerm);
+ CompletableFuture search(String searchTerm);
}
\ No newline at end of file
diff --git a/application/src/main/java/org/togetherjava/tjbot/config/Config.java b/application/src/main/java/org/togetherjava/tjbot/config/Config.java
index 2fa90db55f..0e2488c7b1 100644
--- a/application/src/main/java/org/togetherjava/tjbot/config/Config.java
+++ b/application/src/main/java/org/togetherjava/tjbot/config/Config.java
@@ -66,8 +66,7 @@ private Config(@JsonProperty(value = "token", required = true) String token,
required = true) String logInfoChannelWebhook,
@JsonProperty(value = "logErrorChannelWebhook",
required = true) String logErrorChannelWebhook,
- @JsonProperty(value = "serpapiApiKey",
- required = true) String serpapiApiKey) {
+ @JsonProperty(value = "serpapiApiKey", required = true) String serpapiApiKey) {
this.token = Objects.requireNonNull(token);
this.gistApiKey = Objects.requireNonNull(gistApiKey);
this.databasePath = Objects.requireNonNull(databasePath);
@@ -282,9 +281,10 @@ public String getLogErrorChannelWebhook() {
/**
* The Serpapi API key to pass to the service call.
+ *
* @return The API key
*/
public String getSerpapiApiKey() {
return serpapiApiKey;
}
-}
\ No newline at end of file
+}