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 581296a77d..97780e30fb 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,8 @@ 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.search.GoogleItCommand; import org.togetherjava.tjbot.commands.system.BotCore; import org.togetherjava.tjbot.commands.system.LogLevelCommand; import org.togetherjava.tjbot.commands.tags.TagCommand; @@ -127,6 +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(config)); + features.add(new GoogleItCommand(config)); // 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..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 @@ -129,7 +129,10 @@ 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) { 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..e8010e11b0 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleCommand.java @@ -0,0 +1,74 @@ +package org.togetherjava.tjbot.commands.search; + +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +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. + *

+ * + * @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 search strategy that is going to return the results to us. + */ + 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(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. 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. + */ + @Override + public void onSlashCommand(SlashCommandInteractionEvent event) { + logger.info("Received /google slash command"); + + event.deferReply().queue(); + String searchTerm = Objects.requireNonNull(event.getOption(COMMAND_OPTION)).getAsString(); + 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/GoogleItCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java new file mode 100644 index 0000000000..464636a73a --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleItCommand.java @@ -0,0 +1,63 @@ +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; +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. + *

+ * + * @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; + + /** + * 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 + *

+ */ + public GoogleItCommand(Config config) { + super("googleit", "Searches the channel title on Google", CommandVisibility.GUILD); + searchStrategy = new GoogleSearchStrategy(config.getSerpapiApiKey()); + } + + @Override + public void onSlashCommand(SlashCommandInteractionEvent event) { + logger.info("Received /googleit slash command"); + 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); + } else { + event.reply(WRONG_CHANNEL_ERROR).queue(); + } + } catch (IllegalStateException ex) { + event.reply(WRONG_CHANNEL_ERROR).queue(); + } + } +} 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..fb5332fe3c --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleResponseComposer.java @@ -0,0 +1,160 @@ +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.net.http.HttpResponse; +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; + + /** 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. + *

+ * + * @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_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. + * + * @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()); + 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_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); + eb.setColor(Color.RED); + 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.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_KEY); + String snippetOfAnswer = ""; + if (result.has(SNIPPET_KEY)) { + snippetOfAnswer = result.getString(SNIPPET_KEY); + } else if (result.has(LIST_KEY)) { + StringBuilder list = new StringBuilder(); + result.getJSONArray(LIST_KEY) + .toList() + .forEach(line -> list.append(line).append("\n")); + snippetOfAnswer = list.toString(); + } + String link = result.getString(LINK_KEY); + 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 new file mode 100644 index 0000000000..5d7dd2192f --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/GoogleSearchStrategy.java @@ -0,0 +1,70 @@ +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; + +/** + *

+ * {@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 implements SearchStrategy> { + /** The API key to provide authentication into Serpapi. */ + 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"; + + /** The HttpClient object used for sending the REST API calls. */ + private final HttpClient httpClient = HttpClient.newHttpClient(); + + public GoogleSearchStrategy(String apiKey) { + this.apiKey = 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:
+ *

    + *
  1. q: The search query
  2. + *
  3. api_key: The authentication key created via the Serpapi dashboard.
  4. + *
+ *

+ * 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( + HttpRequest + .newBuilder(UrlBuilder.fromString(API_ENDPOINT) + .addParameter("q", searchTerm) + .addParameter("api_key", apiKey) + .toUri()) + .GET() + .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 new file mode 100644 index 0000000000..37c70edbc9 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/search/SearchStrategy.java @@ -0,0 +1,30 @@ +package org.togetherjava.tjbot.commands.search; + +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 interface 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. + */ + 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 d9b9d8a88f..0e2488c7b1 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,8 @@ 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 +86,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 = Objects.requireNonNull(serpapiApiKey); } /** @@ -275,4 +278,13 @@ 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; + } }