├── .gitignore ├── .travis.yml ├── README.md ├── bot-context.xml ├── discord.properties ├── logging.properties ├── pom.xml └── src ├── main ├── java │ └── oakbot │ │ ├── BotProperties.java │ │ ├── CliArguments.java │ │ ├── Database.java │ │ ├── JsonDatabase.java │ │ ├── Main.java │ │ ├── MemoryDatabase.java │ │ ├── Rooms.java │ │ ├── Statistics.java │ │ ├── ai │ │ ├── openai │ │ │ ├── ChatCompletionRequest.java │ │ │ ├── ChatCompletionResponse.java │ │ │ ├── CreateImageResponse.java │ │ │ ├── CreateSpeechRequest.java │ │ │ ├── ModerationResponse.java │ │ │ ├── OpenAIClient.java │ │ │ ├── OpenAIException.java │ │ │ ├── OpenAIModel.java │ │ │ └── OpenAIModerationException.java │ │ └── stabilityai │ │ │ ├── PromptBuilder.java │ │ │ ├── RemoveBackgroundRequest.java │ │ │ ├── StabilityAIClient.java │ │ │ ├── StabilityAIException.java │ │ │ ├── StableImageCoreRequest.java │ │ │ ├── StableImageDiffusionRequest.java │ │ │ ├── StableImageResponse.java │ │ │ ├── UpscaleRequest.java │ │ │ └── VideoRequest.java │ │ ├── bot │ │ ├── Bot.java │ │ ├── ChatAction.java │ │ ├── ChatActions.java │ │ ├── ChatCommand.java │ │ ├── DeleteMessage.java │ │ ├── IBot.java │ │ ├── JoinRoom.java │ │ ├── LeaveRoom.java │ │ ├── PostMessage.java │ │ └── Shutdown.java │ │ ├── chat │ │ └── mock │ │ │ ├── FileChatClient.java │ │ │ └── FileChatRoom.java │ │ ├── command │ │ ├── AboutCommand.java │ │ ├── AfkCommand.java │ │ ├── CatCommand.java │ │ ├── CoffeeCommand.java │ │ ├── Command.java │ │ ├── DeleteCommand.java │ │ ├── DogCommand.java │ │ ├── EchoCommand.java │ │ ├── EightBallCommand.java │ │ ├── FacepalmCommand.java │ │ ├── FatCatCommand.java │ │ ├── FishCommand.java │ │ ├── GiphyClient.java │ │ ├── HelpCommand.java │ │ ├── HelpDoc.java │ │ ├── JuiceBoxCommand.java │ │ ├── PhishCommand.java │ │ ├── ReactCommand.java │ │ ├── ReactGiphyCommand.java │ │ ├── RemindCommand.java │ │ ├── RollCommand.java │ │ ├── ShrugCommand.java │ │ ├── ShutdownCommand.java │ │ ├── SummonCommand.java │ │ ├── TagCommand.java │ │ ├── TheCatDogApiClient.java │ │ ├── TimeoutCommand.java │ │ ├── UnsummonCommand.java │ │ ├── WikiCommand.java │ │ ├── aoc │ │ │ ├── AdventOfCode.java │ │ │ └── AdventOfCodeApi.java │ │ ├── define │ │ │ ├── DefineCommand.java │ │ │ └── Definition.java │ │ ├── effective │ │ │ ├── EffectiveDebuggingCommand.java │ │ │ └── EffectiveJavaCommand.java │ │ ├── http │ │ │ └── HttpCommand.java │ │ ├── javadoc │ │ │ ├── ClassInfo.java │ │ │ ├── ClassInfoXmlParser.java │ │ │ ├── ClassName.java │ │ │ ├── JavadocCommand.java │ │ │ ├── JavadocCommandArguments.java │ │ │ ├── JavadocDao.java │ │ │ ├── JavadocDaoCached.java │ │ │ ├── JavadocDaoUncached.java │ │ │ ├── JavadocZipFile.java │ │ │ ├── MethodInfo.java │ │ │ └── ParameterInfo.java │ │ ├── learn │ │ │ ├── LearnCommand.java │ │ │ ├── LearnedCommand.java │ │ │ ├── LearnedCommandsDao.java │ │ │ └── UnlearnCommand.java │ │ ├── shibe │ │ │ ├── BirdCommand.java │ │ │ ├── ShibaCommand.java │ │ │ └── ShibeOnlineClient.java │ │ ├── stands4 │ │ │ ├── AbbreviationCommand.java │ │ │ ├── ConvertCommand.java │ │ │ ├── ConvertException.java │ │ │ ├── ExplainCommand.java │ │ │ ├── Explanation.java │ │ │ ├── GrammarCommand.java │ │ │ ├── RhymeCommand.java │ │ │ └── Stands4Client.java │ │ └── urban │ │ │ ├── UrbanCommand.java │ │ │ ├── UrbanDefinition.java │ │ │ └── UrbanResponse.java │ │ ├── discord │ │ ├── AboutCommand.java │ │ ├── BotContext.java │ │ ├── CatCommand.java │ │ ├── ChatGPTListener.java │ │ ├── CoffeeCommand.java │ │ ├── CommandListener.java │ │ ├── DiscordBot.java │ │ ├── DiscordCommand.java │ │ ├── DiscordHelpDoc.java │ │ ├── DiscordListener.java │ │ ├── DiscordProperties.java │ │ ├── DiscordSlashCommand.java │ │ ├── DogCommand.java │ │ ├── HelpCommand.java │ │ ├── ImagineCommand.java │ │ ├── MainDiscord.java │ │ ├── ShutdownCommand.java │ │ └── WaveListener.java │ │ ├── filter │ │ ├── ChatResponseFilter.java │ │ ├── GrootFilter.java │ │ ├── ToggleableFilter.java │ │ ├── UpsidedownTextFilter.java │ │ └── WaduFilter.java │ │ ├── imgur │ │ ├── ImgurClient.java │ │ └── ImgurException.java │ │ ├── inactivity │ │ ├── FillTheSilenceTask.java │ │ ├── InactivityTask.java │ │ └── LeaveRoomTask.java │ │ ├── listener │ │ ├── BotlerListener.java │ │ ├── CatchAllMentionListener.java │ │ ├── CommandListener.java │ │ ├── DadJokeListener.java │ │ ├── Listener.java │ │ ├── MentionListener.java │ │ ├── MornListener.java │ │ ├── WaveListener.java │ │ ├── WelcomeListener.java │ │ └── chatgpt │ │ │ ├── ChatGPT.java │ │ │ ├── ImagineCommand.java │ │ │ ├── MoodCommand.java │ │ │ ├── PromptCommand.java │ │ │ ├── QuotaCommand.java │ │ │ ├── TtsCommand.java │ │ │ ├── UsageQuota.java │ │ │ └── VideoCommand.java │ │ ├── task │ │ ├── FOTD.java │ │ ├── HealthMonitor.java │ │ ├── LinuxHealthMonitor.java │ │ ├── QOTD.java │ │ ├── ScheduledTask.java │ │ └── XkcdExplained.java │ │ └── util │ │ ├── CharIterator.java │ │ ├── ChatBuilder.java │ │ ├── HttpFactory.java │ │ ├── HttpRequestLogger.java │ │ ├── ImageUtils.java │ │ ├── JsonUtils.java │ │ ├── Now.java │ │ ├── PropertiesWrapper.java │ │ ├── RelativeDateFormat.java │ │ ├── Rng.java │ │ └── StringUtils.java └── resources │ ├── info.properties │ └── oakbot │ └── command │ ├── effective │ └── effective-java.xml │ └── http │ └── http.xml ├── old └── java │ ├── RobustClient.java │ └── StackoverflowChat.java └── test ├── java └── oakbot │ ├── ai │ └── openai │ │ └── OpenAIClientTest.java │ ├── bot │ ├── BotTest.java │ ├── ChatActionsUtils.java │ ├── ChatCommandTest.java │ ├── CommandsWikiPage.java │ └── JsonDatabaseTest.java │ ├── command │ ├── AfkCommandTest.java │ ├── CommandTest.java │ ├── EchoCommandTest.java │ ├── FacepalmCommandTest.java │ ├── FishCommandTest.java │ ├── JuiceBoxCommandTest.java │ ├── WikiCommandTest.java │ ├── aoc │ │ ├── AdventOfCodeApiTest.java │ │ └── AdventOfCodeTest.java │ ├── define │ │ └── DefineCommandTest.java │ ├── effective │ │ ├── EffectiveDebuggingCommandTest.java │ │ └── EffectiveJavaXmlTest.java │ ├── http │ │ └── HttpCommandTest.java │ ├── javadoc │ │ ├── JavadocCommandArgumentsTest.java │ │ ├── JavadocDaoCachedTest.java │ │ ├── JavadocDaoUncachedTest.java │ │ └── JavadocZipFileTest.java │ ├── learn │ │ ├── LearnCommandTest.java │ │ ├── LearnedCommandTest.java │ │ └── LearnedCommandsDaoTest.java │ ├── stands4 │ │ ├── ResponseSamples.java │ │ └── Stands4ClientTest.java │ └── urban │ │ └── UrbanCommandTest.java │ ├── filter │ └── UpsidedownTextFilterTest.java │ ├── listener │ ├── CommandListenerTest.java │ ├── DadJokeListenerTest.java │ ├── MentionListenerTest.java │ ├── MornListenerTest.java │ ├── WaveListenerTest.java │ └── chatgpt │ │ ├── ChatGPTTest.java │ │ ├── ImagineCommandTest.java │ │ ├── ResponseSamples.java │ │ └── UsageQuotaTest.java │ ├── task │ ├── FOTDTest.java │ ├── QOTDTest.java │ └── XkcdExplainedTest.java │ └── util │ ├── ChatBuilderTest.java │ ├── ChatCommandBuilder.java │ ├── Gobble.java │ ├── GobbleTest.java │ ├── MockHttpClientBuilder.java │ ├── PropertiesWrapperTest.java │ ├── RelativeDateFormatTest.java │ └── StringUtilsTest.java └── resources ├── logging.properties └── oakbot ├── ai └── openai │ └── image.jpg ├── chat ├── rooms-1.html ├── rooms-15-protected.html ├── stackexchange-login-form.html ├── stackexchange-login-redirect-page.html └── users-login.html ├── command ├── aoc │ ├── advent-of-code-2017.json │ ├── advent-of-code-2018.json │ ├── advent-of-code-2019.json │ └── advent-of-code-2021.json ├── define │ └── cool.xml ├── javadoc │ ├── JavadocZipFileTest-javadocUrlPattern.zip │ ├── JavadocZipFileTest-no-attributes.zip │ ├── JavadocZipFileTest-no-info.zip │ └── JavadocZipFileTest.zip ├── juiceboxify-face.html ├── juiceboxify-no-face.html ├── tenor-response.json └── urban │ ├── urbandictionary.cool.json │ └── urbandictionary.snafu.json └── task ├── refdesk.html ├── slashdot.html ├── theysaidso.json ├── theysaidso_newline.json ├── xkcd-explained-2796-first-para-not-wrapped-in-p-element.html ├── xkcd-explained-2796-has-newlines.html ├── xkcd-explained-2796.html ├── xkcd-explained-3072-explanation-incomplete-wrapped-in-div.html ├── xkcd-explained-404-response.html └── xkcd-explained-no-explanation.html /.gitignore: -------------------------------------------------------------------------------- 1 | # Maven related 2 | target/ 3 | 4 | # Javadoc dir 5 | javadocs/ 6 | 7 | # IntelliJ Idea related 8 | .idea/ 9 | *.iml 10 | 11 | # Eclipse related 12 | .settings/ 13 | .classpath 14 | .project 15 | 16 | # Miscellenous 17 | statistics.properties 18 | *.log 19 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: openjdk8 3 | sudo: true 4 | script: "mvn cobertura:cobertura" 5 | after_success: 6 | - bash <(curl -s https://codecov.io/bash) 7 | -------------------------------------------------------------------------------- /discord.properties: -------------------------------------------------------------------------------- 1 | discord.token=TOKEN 2 | discord.status=Ready to not be useful. 3 | openai.key=KEY 4 | openai.messageHistoryCount=10 5 | openai.prompt=You are a groovy C# developer named 'OakBot'. You are in a Discord chat room with other C# developers. You love everything Microsoft. 6 | stabilityai.key=KEY 7 | admins= 8 | ignoredChannels= 9 | -------------------------------------------------------------------------------- /logging.properties: -------------------------------------------------------------------------------- 1 | #Global logging level 2 | .level=OFF 3 | 4 | #Package logging level 5 | oakbot.level=FINE 6 | 7 | #Handlers 8 | handlers=java.util.logging.ConsoleHandler,java.util.logging.FileHandler 9 | 10 | java.util.logging.ConsoleHandler.level=ALL 11 | java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter 12 | 13 | java.util.logging.FileHandler.level=INFO 14 | java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter 15 | java.util.logging.FileHandler.append=true 16 | java.util.logging.FileHandler.count=2 17 | java.util.logging.FileHandler.limit=1000000 18 | java.util.logging.FileHandler.pattern=oakbot-%u-%g.log -------------------------------------------------------------------------------- /src/main/java/oakbot/CliArguments.java: -------------------------------------------------------------------------------- 1 | package oakbot; 2 | 3 | import joptsimple.OptionParser; 4 | import joptsimple.OptionSet; 5 | 6 | /** 7 | * Parses the command-line arguments. 8 | * @author Michael Angstadt 9 | */ 10 | public class CliArguments { 11 | private final OptionSet options; 12 | 13 | public CliArguments(String[] args) { 14 | var parser = new OptionParser(); 15 | parser.accepts("context").withRequiredArg(); 16 | parser.accepts("mock"); 17 | parser.accepts("quiet"); 18 | parser.accepts("version"); 19 | parser.accepts("help"); 20 | 21 | options = parser.parse(args); 22 | } 23 | 24 | public String context() { 25 | return (String) options.valueOf("context"); 26 | } 27 | 28 | public boolean version() { 29 | return options.has("version"); 30 | } 31 | 32 | public boolean help() { 33 | return options.has("help"); 34 | } 35 | 36 | public boolean quiet() { 37 | return options.has("quiet"); 38 | } 39 | 40 | public boolean mock() { 41 | return options.has("mock"); 42 | } 43 | 44 | public String printHelp(String defaultContext) { 45 | return """ 46 | OakBot v%s 47 | by Michael Angstadt 48 | %s 49 | 50 | Arguments 51 | ================================================ 52 | --context=PATH 53 | The path to the Spring application context XML file that contains the bot's 54 | configuration settings and commands (defaults to "%s"). 55 | Note: Absolute paths must be prefixed with "file:". 56 | 57 | --mock 58 | Runs the bot using a mock chat connection for testing purposes. 59 | A text file will be created in the root of the project for each chat room the 60 | bot is configured to connect to. These files are used to "send" messages 61 | to the mock chat rooms. To send a message, type your message into the text 62 | file and save it. 63 | Messages are entered one per line. Multi-line messages can be entered by 64 | ending each line with a backslash until you reach the last line. You should 65 | only append onto the end of the file; do not delete anything. These files are 66 | re-created every time the program runs. 67 | All messages that are sent to the mock chat room are displayed in stdout (this 68 | includes your messages and the bot's responses). 69 | 70 | --quiet 71 | If specified, the bot will not output a greeting message when it starts up. 72 | 73 | --version 74 | Prints the version of this program. 75 | 76 | --help 77 | Prints this help message.""".formatted(Main.VERSION, Main.URL, defaultContext); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/oakbot/Database.java: -------------------------------------------------------------------------------- 1 | package oakbot; 2 | 3 | import java.time.LocalDateTime; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | /** 8 | * An interface to persistent storage. 9 | * @author Michael Angstadt 10 | */ 11 | public interface Database { 12 | /** 13 | * Retrieves a value from the database. 14 | * @param key the key 15 | * @return the value 16 | */ 17 | Object get(String key); 18 | 19 | /** 20 | * Retrieves a map value from the database. 21 | * @param key the key 22 | * @return the value 23 | */ 24 | @SuppressWarnings("unchecked") 25 | default Map getMap(String key) { 26 | return (Map) get(key); 27 | } 28 | 29 | /** 30 | * Retrieves a list value from the database. 31 | * @param key the key 32 | * @return the value 33 | */ 34 | @SuppressWarnings("unchecked") 35 | default List getList(String key) { 36 | return (List) get(key); 37 | } 38 | 39 | /** 40 | *

41 | * Stores a value in the database. 42 | *

43 | *

44 | * If the given key already exists in the database, it will be overwritten. 45 | *

46 | *

47 | * This method will properly serialize the following value objects so that 48 | * round-tripping is preserved: 49 | *

50 | *
    51 | *
  • {@code Map}
  • 52 | *
  • {@code List} 53 | *
  • {@link LocalDateTime}
  • 54 | *
  • {@link Integer}
  • 55 | *
  • {@link Long} (if within the range of a Java int, will be converted to 56 | * an int)
  • 57 | *
  • {@code null}
  • 58 | * 59 | *

    60 | * All other objects are converted to strings using their {@code toString} 61 | * method. 62 | *

    63 | * @param key the key 64 | * @param value the value 65 | */ 66 | void set(String key, Object value); 67 | 68 | /** 69 | * Saves all changes made to the database since the last commit (if any). 70 | */ 71 | void commit(); 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/oakbot/MemoryDatabase.java: -------------------------------------------------------------------------------- 1 | package oakbot; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * A database that only holds its values in memory. 8 | * @author Michael Angstadt 9 | */ 10 | public class MemoryDatabase implements Database { 11 | private final Map fields = new HashMap<>(); 12 | 13 | @Override 14 | public Object get(String key) { 15 | return fields.get(key); 16 | } 17 | 18 | @Override 19 | public void set(String key, Object value) { 20 | fields.put(key, value); 21 | } 22 | 23 | @Override 24 | public void commit() { 25 | //do nothing 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/oakbot/Statistics.java: -------------------------------------------------------------------------------- 1 | package oakbot; 2 | 3 | import java.time.LocalDateTime; 4 | import java.util.Map; 5 | 6 | /** 7 | * Records statistics on the bot. 8 | * @author Michael Angstadt 9 | */ 10 | public class Statistics { 11 | private final Database db; 12 | private final LocalDateTime since; 13 | private int responses; 14 | 15 | /** 16 | * @param db the database to save the stats to 17 | */ 18 | public Statistics(Database db) { 19 | this.db = db; 20 | 21 | var value = db.getMap("statistics"); 22 | if (value == null) { 23 | since = LocalDateTime.now(); 24 | responses = 0; 25 | save(); 26 | } else { 27 | since = (LocalDateTime) value.get("since"); 28 | responses = (Integer) value.get("responses"); 29 | } 30 | } 31 | 32 | public synchronized void incMessagesRespondedTo() { 33 | responses++; 34 | save(); 35 | } 36 | 37 | public synchronized int getMessagesRespondedTo() { 38 | return responses; 39 | } 40 | 41 | public LocalDateTime getSince() { 42 | return since; 43 | } 44 | 45 | private void save() { 46 | db.set("statistics", Map.of( 47 | "since", since, 48 | "responses", responses 49 | )); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/oakbot/ai/openai/CreateImageResponse.java: -------------------------------------------------------------------------------- 1 | package oakbot.ai.openai; 2 | 3 | import java.time.Instant; 4 | 5 | /** 6 | * @author Michael Angstadt 7 | * @see "https://platform.openai.com/docs/api-reference/images/object" 8 | */ 9 | public class CreateImageResponse { 10 | private final Instant created; 11 | private final String url; 12 | private final String revisedPrompt; 13 | 14 | /** 15 | * @param created the timestamp when the image was created 16 | * @param url the URL to the image 17 | * @param revisedPrompt the revised prompt or null if the user's prompt was 18 | * used 19 | */ 20 | public CreateImageResponse(Instant created, String url, String revisedPrompt) { 21 | this.created = created; 22 | this.url = url; 23 | this.revisedPrompt = revisedPrompt; 24 | } 25 | 26 | /** 27 | * Gets the timestamp that the image was created. 28 | * @return the timestamp 29 | */ 30 | public Instant getCreated() { 31 | return created; 32 | } 33 | 34 | /** 35 | * Gets the URL to the generated image. The URL is only valid for 1 hour. 36 | * @return the URL to the image 37 | */ 38 | public String getUrl() { 39 | return url; 40 | } 41 | 42 | /** 43 | * Gets the prompt that was used to generate the image, if there was any 44 | * revision to the prompt. 45 | * @return the revised prompt or null if the user's prompt was used 46 | */ 47 | public String getRevisedPrompt() { 48 | return revisedPrompt; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/oakbot/ai/openai/ModerationResponse.java: -------------------------------------------------------------------------------- 1 | package oakbot.ai.openai; 2 | 3 | import java.util.Map; 4 | import java.util.Set; 5 | 6 | /** 7 | * A moderation response. 8 | * @author Michael Angstadt 9 | * @see OpenAIClient#moderate 10 | * @see "https://platform.openai.com/docs/api-reference/moderations/object" 11 | */ 12 | public class ModerationResponse { 13 | private final String id; 14 | private final String model; 15 | private final Set flaggedCategories; 16 | private final Map categoryScores; 17 | 18 | private ModerationResponse(ModerationResponse.Builder builder) { 19 | id = builder.id; 20 | model = builder.model; 21 | flaggedCategories = (builder.flaggedCategories == null) ? Set.of() : Set.copyOf(builder.flaggedCategories); 22 | categoryScores = (builder.categoryScores == null) ? Map.of() : Map.copyOf(builder.categoryScores); 23 | } 24 | 25 | /** 26 | * Gets the unique identifier for the moderation request. 27 | * @return the ID 28 | */ 29 | public String getId() { 30 | return id; 31 | } 32 | 33 | /** 34 | * Gets the model used to generate the moderation results. 35 | * @return the model 36 | */ 37 | public String getModel() { 38 | return model; 39 | } 40 | 41 | /** 42 | * Gets the categories that were flagged by the system due to their score 43 | * being too high. If at least one category is flagged, then the entire 44 | * input message is rejected by the moderation system. 45 | * @return the flagged categories 46 | */ 47 | public Set getFlaggedCategories() { 48 | return flaggedCategories; 49 | } 50 | 51 | /** 52 | * Gets the score of each category. 53 | * @return the scores 54 | */ 55 | public Map getCategoryScores() { 56 | return categoryScores; 57 | } 58 | 59 | public static class Builder { 60 | private String id; 61 | private String model; 62 | private Set flaggedCategories; 63 | private Map categoryScores; 64 | 65 | public Builder id(String id) { 66 | this.id = id; 67 | return this; 68 | } 69 | 70 | public Builder model(String model) { 71 | this.model = model; 72 | return this; 73 | } 74 | 75 | public Builder flaggedCategories(Set flaggedCategories) { 76 | this.flaggedCategories = flaggedCategories; 77 | return this; 78 | } 79 | 80 | public Builder categoryScores(Map categoryScores) { 81 | this.categoryScores = categoryScores; 82 | return this; 83 | } 84 | 85 | public ModerationResponse build() { 86 | return new ModerationResponse(this); 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/oakbot/ai/openai/OpenAIException.java: -------------------------------------------------------------------------------- 1 | package oakbot.ai.openai; 2 | 3 | /** 4 | * @author Michael Angstadt 5 | */ 6 | public class OpenAIException extends RuntimeException { 7 | private static final long serialVersionUID = 1L; 8 | 9 | private final String type; 10 | private final String param; 11 | private final String code; 12 | 13 | public OpenAIException(String message, String type, String param, String code) { 14 | super(message); 15 | this.type = type; 16 | this.param = param; 17 | this.code = code; 18 | } 19 | 20 | public String getType() { 21 | return type; 22 | } 23 | 24 | public String getParam() { 25 | return param; 26 | } 27 | 28 | public String getCode() { 29 | return code; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/oakbot/ai/openai/OpenAIModel.java: -------------------------------------------------------------------------------- 1 | package oakbot.ai.openai; 2 | 3 | import java.time.Instant; 4 | 5 | /** 6 | * Represents an OpenAI model. 7 | * @author Michael Angstadt 8 | * @see OpenAIClient#listModels 9 | * @see "https://platform.openai.com/docs/api-reference/models/list" 10 | */ 11 | public record OpenAIModel(String id, Instant created, String owner) { 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/oakbot/ai/openai/OpenAIModerationException.java: -------------------------------------------------------------------------------- 1 | package oakbot.ai.openai; 2 | 3 | import java.util.Set; 4 | 5 | /** 6 | * @author Michael Angstadt 7 | */ 8 | public class OpenAIModerationException extends OpenAIException { 9 | private static final long serialVersionUID = 1L; 10 | 11 | private final Set flaggedCategories; 12 | 13 | public OpenAIModerationException(String message, String type, String param, String code, Set flaggedCategories) { 14 | super(message, type, param, code); 15 | this.flaggedCategories = flaggedCategories; 16 | } 17 | 18 | public Set getFlaggedCategories() { 19 | return flaggedCategories; 20 | } 21 | 22 | @Override 23 | public String getMessage() { 24 | if (flaggedCategories.isEmpty()) { 25 | return super.getMessage(); 26 | } 27 | 28 | return super.getMessage() + " Flagged categories: " + flaggedCategories; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/oakbot/ai/stabilityai/PromptBuilder.java: -------------------------------------------------------------------------------- 1 | package oakbot.ai.stabilityai; 2 | 3 | /** 4 | * Helper class for building Stability.ai prompts. 5 | * @author Michael Angstadt 6 | */ 7 | public class PromptBuilder implements CharSequence { 8 | private final StringBuilder sb; 9 | 10 | /** 11 | * Creates a new prompt builder. 12 | */ 13 | public PromptBuilder() { 14 | sb = new StringBuilder(); 15 | } 16 | 17 | /** 18 | * Creates a new prompt builder. 19 | * @param text the text to initialize the builder with 20 | */ 21 | public PromptBuilder(String text) { 22 | sb = new StringBuilder(text); 23 | } 24 | 25 | /** 26 | * Appends a raw string. 27 | * @param text the string to append 28 | * @return this 29 | */ 30 | public PromptBuilder append(CharSequence text) { 31 | sb.append(text); 32 | return this; 33 | } 34 | 35 | /** 36 | * Appends a weighted word. The higher the weight value, the more importance 37 | * the system will assign to that word. 38 | * @param word the word to append 39 | * @param weight the weight to assign to the word (between 0 and 1) 40 | * @return this 41 | * @throws IllegalArgumentException if the weight is not between 0 and 1 42 | */ 43 | public PromptBuilder append(CharSequence word, double weight) { 44 | if (weight < 0.0 || weight > 1.0) { 45 | throw new IllegalArgumentException("Weight must be between 0 and 1."); 46 | } 47 | 48 | sb.append('(').append(word).append(':').append(weight).append(')'); 49 | return this; 50 | } 51 | 52 | @Override 53 | public int length() { 54 | return sb.length(); 55 | } 56 | 57 | @Override 58 | public char charAt(int index) { 59 | return sb.charAt(index); 60 | } 61 | 62 | @Override 63 | public CharSequence subSequence(int start, int end) { 64 | return sb.subSequence(start, end); 65 | } 66 | 67 | @Override 68 | public String toString() { 69 | return sb.toString(); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/oakbot/ai/stabilityai/RemoveBackgroundRequest.java: -------------------------------------------------------------------------------- 1 | package oakbot.ai.stabilityai; 2 | 3 | import java.util.Objects; 4 | 5 | /** 6 | *

    7 | * The Remove Background service accurately segments the foreground from an 8 | * image and implements and removes the background. 9 | *

    10 | *

    11 | * Cost: 2 credits 12 | *

    13 | * @see "https://platform.stability.ai/docs/api-reference#tag/Edit/paths/~1v2beta~1stable-image~1edit~1remove-background/post" 14 | */ 15 | public class RemoveBackgroundRequest { 16 | private final byte[] image; 17 | private final String imageContentType; 18 | private final String outputFormat; 19 | 20 | private RemoveBackgroundRequest(RemoveBackgroundRequest.Builder builder) { 21 | image = Objects.requireNonNull(builder.image); 22 | imageContentType = Objects.requireNonNull(builder.imageContentType); 23 | outputFormat = builder.outputFormat; 24 | } 25 | 26 | public byte[] getImage() { 27 | return image; 28 | } 29 | 30 | public String getImageContentType() { 31 | return imageContentType; 32 | } 33 | 34 | public String getOutputFormat() { 35 | return outputFormat; 36 | } 37 | 38 | public static class Builder { 39 | private byte[] image; 40 | private String imageContentType; 41 | private String outputFormat; 42 | 43 | /** 44 | *

    45 | * Sets the image whose background you wish to remove. Please ensure 46 | * that the source image is in the correct format and dimensions. 47 | *

    48 | *

    49 | * Every side must be at least 64 pixels. The total pixel count cannot 50 | * exceed 4,194,304 pixels (e.g. 20482048, 40961024, etc.) 51 | *

    52 | *

    53 | * Supported formats: jpeg, png, webp 54 | *

    55 | * @param image the image 56 | * @param contentType the content type of the image (e.g. "image/jpeg") 57 | * @return this 58 | */ 59 | public Builder image(byte[] image, String contentType) { 60 | this.image = image; 61 | this.imageContentType = contentType; 62 | return this; 63 | } 64 | 65 | /** 66 | *

    67 | * Sets the format of the generated image. 68 | *

    69 | *

    70 | * Default value: png 71 | *

    72 | *

    73 | * Valid values: png, webp 74 | *

    75 | * @param outputFormat the output format 76 | * @return this 77 | */ 78 | public Builder outputFormat(String outputFormat) { 79 | this.outputFormat = outputFormat; 80 | return this; 81 | } 82 | 83 | public RemoveBackgroundRequest build() { 84 | return new RemoveBackgroundRequest(this); 85 | } 86 | } 87 | } -------------------------------------------------------------------------------- /src/main/java/oakbot/ai/stabilityai/StabilityAIException.java: -------------------------------------------------------------------------------- 1 | package oakbot.ai.stabilityai; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * @author Michael Angstadt 7 | */ 8 | public class StabilityAIException extends RuntimeException { 9 | private static final long serialVersionUID = 1L; 10 | 11 | private final int statusCode; 12 | private final String name; 13 | private final List errors; 14 | 15 | public StabilityAIException(int statusCode, String name, List errors) { 16 | super("HTTP " + statusCode + ": " + name + ": " + errors); 17 | this.statusCode = statusCode; 18 | this.name = name; 19 | this.errors = errors; 20 | } 21 | 22 | public int getStatusCode() { 23 | return statusCode; 24 | } 25 | 26 | public String getName() { 27 | return name; 28 | } 29 | 30 | public List getErrors() { 31 | return errors; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/oakbot/ai/stabilityai/StableImageResponse.java: -------------------------------------------------------------------------------- 1 | package oakbot.ai.stabilityai; 2 | 3 | /** 4 | * @author Michael Angstadt 5 | */ 6 | public class StableImageResponse { 7 | private final byte[] image; 8 | private final String contentType; 9 | private final String finishReason; 10 | private final int seed; 11 | 12 | public StableImageResponse(byte[] image, String contentType, String finishReason, int seed) { 13 | this.image = image; 14 | this.contentType = contentType; 15 | this.finishReason = finishReason; 16 | this.seed = seed; 17 | } 18 | 19 | public byte[] getImage() { 20 | return image; 21 | } 22 | 23 | public String getContentType() { 24 | return contentType; 25 | } 26 | 27 | public String getFinishReason() { 28 | return finishReason; 29 | } 30 | 31 | public int getSeed() { 32 | return seed; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/oakbot/bot/ChatAction.java: -------------------------------------------------------------------------------- 1 | package oakbot.bot; 2 | 3 | /** 4 | * Represents an action to perform in response to a chat message. 5 | * @author Michael Angstadt 6 | */ 7 | public interface ChatAction { 8 | //empty 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/oakbot/bot/DeleteMessage.java: -------------------------------------------------------------------------------- 1 | package oakbot.bot; 2 | 3 | import java.util.function.Function; 4 | import java.util.function.Supplier; 5 | 6 | /** 7 | * Instructs the bot to delete a message. It can only delete messages that it 8 | * has authored and that have been posted within the last 2 minutes. 9 | * @author Michael Angstadt 10 | */ 11 | public class DeleteMessage implements ChatAction { 12 | private long messageId; 13 | private Supplier onSuccess; 14 | private Function onError; 15 | 16 | /** 17 | * @param messageId the ID of the message to delete 18 | */ 19 | public DeleteMessage(long messageId) { 20 | this.messageId = messageId; 21 | onSuccess = ChatActions::doNothing; 22 | onError = e -> ChatActions.doNothing(); 23 | } 24 | 25 | /** 26 | * Gets the ID of the message to delete. 27 | * @return the message ID 28 | */ 29 | public long messageId() { 30 | return messageId; 31 | } 32 | 33 | /** 34 | * Sets the ID of the message to delete 35 | * @param messageId the message ID 36 | * @return this 37 | */ 38 | public DeleteMessage messageId(int messageId) { 39 | this.messageId = messageId; 40 | return this; 41 | } 42 | 43 | /** 44 | * Gets the action(s) to perform when the message is deleted successfully. 45 | * @return the actions 46 | */ 47 | public Supplier onSuccess() { 48 | return onSuccess; 49 | } 50 | 51 | /** 52 | * Sets the action(s) to perform when the message is deleted successfully. 53 | * @param actions the actions 54 | * @return this 55 | */ 56 | public DeleteMessage onSuccess(Supplier actions) { 57 | onSuccess = actions; 58 | return this; 59 | } 60 | 61 | /** 62 | * Sets the action(s) to perform if there is an error deleting the message. 63 | * @return the actions 64 | */ 65 | public Function onError() { 66 | return onError; 67 | } 68 | 69 | /** 70 | * Gets the action(s) to perform if there is an error deleting the message. 71 | * @param actions the actions 72 | * @return this 73 | */ 74 | public DeleteMessage onError(Function actions) { 75 | onError = actions; 76 | return this; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/oakbot/bot/LeaveRoom.java: -------------------------------------------------------------------------------- 1 | package oakbot.bot; 2 | 3 | /** 4 | * Instructs the bot to leave a room. 5 | * @author Michael Angstadt 6 | */ 7 | public class LeaveRoom implements ChatAction { 8 | private int roomId; 9 | 10 | /** 11 | * @param roomId the ID of the room to leave 12 | */ 13 | public LeaveRoom(int roomId) { 14 | this.roomId = roomId; 15 | } 16 | 17 | /** 18 | * Gets the ID of the room to leave. 19 | * @return the room ID 20 | */ 21 | public int roomId() { 22 | return roomId; 23 | } 24 | 25 | /** 26 | * Sets the ID of the room to leave. 27 | * @param roomId the room ID 28 | * @return this 29 | */ 30 | public LeaveRoom roomId(int roomId) { 31 | this.roomId = roomId; 32 | return this; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/oakbot/bot/Shutdown.java: -------------------------------------------------------------------------------- 1 | package oakbot.bot; 2 | 3 | /** 4 | * Instructs the bot to terminate. 5 | * @author Michael Angstadt 6 | */ 7 | public class Shutdown implements ChatAction { 8 | //empty 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/AboutCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.post; 4 | 5 | import java.time.LocalDateTime; 6 | import java.time.ZoneId; 7 | import java.time.format.DateTimeFormatter; 8 | 9 | import oakbot.Main; 10 | import oakbot.Statistics; 11 | import oakbot.bot.ChatActions; 12 | import oakbot.bot.ChatCommand; 13 | import oakbot.bot.IBot; 14 | import oakbot.util.ChatBuilder; 15 | import oakbot.util.RelativeDateFormat; 16 | 17 | /** 18 | * Displays meta information about the bot. 19 | * @author Michael Angstadt 20 | */ 21 | public class AboutCommand implements Command { 22 | private final LocalDateTime startedUp = LocalDateTime.now(); 23 | private final Statistics stats; 24 | private final String host; 25 | 26 | public AboutCommand(Statistics stats, String host) { 27 | this.stats = stats; 28 | this.host = host; 29 | } 30 | 31 | @Override 32 | public String name() { 33 | return "about"; 34 | } 35 | 36 | @Override 37 | public HelpDoc help() { 38 | //@formatter:off 39 | return new HelpDoc.Builder(this) 40 | .summary("Displays information about this bot.") 41 | .build(); 42 | //@formatter:on 43 | } 44 | 45 | @Override 46 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 47 | var relativeDf = new RelativeDateFormat(); 48 | var built = LocalDateTime.ofInstant(Main.BUILT, ZoneId.systemDefault()); 49 | 50 | //@formatter:off 51 | var cb = new ChatBuilder() 52 | .bold("OakBot").append(" by ").link("Michael", "https://stackoverflow.com/users/13379/michael").append(" | ") 53 | .link("source code", Main.URL).append(" | ") 54 | .append("JAR built on: ").append(relativeDf.format(built)).append(" | ") 55 | .append("started up: ").append(relativeDf.format(startedUp)); 56 | //@formatter:on 57 | 58 | if (host != null) { 59 | cb.append(" | ").append("hosted by: ").append(host); 60 | } 61 | 62 | if (stats != null) { 63 | cb.append(" | ").append("responded to ").append(stats.getMessagesRespondedTo()).append(" commands"); 64 | 65 | var since = stats.getSince(); 66 | if (since != null) { 67 | var formatter = DateTimeFormatter.ofPattern("MMM d, yyyy"); 68 | cb.append(" since ").append(since.format(formatter)); 69 | } 70 | } 71 | 72 | return post(cb); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/CatCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.error; 4 | 5 | import java.io.IOException; 6 | import java.util.List; 7 | 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | import oakbot.bot.ChatActions; 12 | import oakbot.bot.ChatCommand; 13 | import oakbot.bot.IBot; 14 | import oakbot.bot.PostMessage; 15 | 16 | /** 17 | * Displays a random cat picture. 18 | * @author Michael Angstadt 19 | * @see "https://thecatapi.com/" 20 | */ 21 | public class CatCommand implements Command { 22 | private static final Logger logger = LoggerFactory.getLogger(CatCommand.class); 23 | 24 | private final TheCatDogApiClient client; 25 | 26 | public CatCommand(TheCatDogApiClient client) { 27 | this.client = client; 28 | } 29 | 30 | @Override 31 | public String name() { 32 | return "cat"; 33 | } 34 | 35 | @Override 36 | public List aliases() { 37 | return List.of("meow"); 38 | } 39 | 40 | @Override 41 | public HelpDoc help() { 42 | //@formatter:off 43 | return new HelpDoc.Builder(this) 44 | .summary("Displays a cat GIF. :3") 45 | .detail("Images from thecatapi.com.") 46 | .build(); 47 | //@formatter:on 48 | } 49 | 50 | @Override 51 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 52 | String url; 53 | try { 54 | url = client.getRandomCatGif(); 55 | } catch (IOException e) { 56 | logger.atError().setCause(e).log(() -> "Problem getting cat."); 57 | return error("Error getting cat: ", e, chatCommand); 58 | } 59 | 60 | //@formatter:off 61 | return ChatActions.create( 62 | new PostMessage(url).bypassFilters(true) 63 | ); 64 | //@formatter:on 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/CoffeeCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.error; 4 | 5 | import java.io.IOException; 6 | import java.util.List; 7 | 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | import oakbot.bot.ChatActions; 12 | import oakbot.bot.ChatCommand; 13 | import oakbot.bot.IBot; 14 | import oakbot.bot.PostMessage; 15 | import oakbot.util.HttpFactory; 16 | 17 | /** 18 | * Displays a coffee-related picture. 19 | * @author Michael Angstadt 20 | * @see "https://coffee.alexflipnote.dev" 21 | */ 22 | public class CoffeeCommand implements Command { 23 | private static final Logger logger = LoggerFactory.getLogger(CoffeeCommand.class); 24 | 25 | private final String apiUrl = "https://coffee.alexflipnote.dev/random.json"; 26 | 27 | @Override 28 | public String name() { 29 | return "coffee"; 30 | } 31 | 32 | @Override 33 | public List aliases() { 34 | return List.of("KAFFEEZEIT"); 35 | } 36 | 37 | @Override 38 | public HelpDoc help() { 39 | //@formatter:off 40 | return new HelpDoc.Builder(this) 41 | .summary("Displays a coffee-related image.") 42 | .detail("Images from coffee.alexflipnote.dev.") 43 | .build(); 44 | //@formatter:on 45 | } 46 | 47 | @Override 48 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 49 | String url; 50 | try { 51 | url = getCoffee(); 52 | } catch (IOException e) { 53 | logger.atError().setCause(e).log(() -> "Problem getting coffee."); 54 | return error("Error getting coffee: ", e, chatCommand); 55 | } 56 | 57 | //@formatter:off 58 | return ChatActions.create( 59 | new PostMessage(url).bypassFilters(true) 60 | ); 61 | //@formatter:on 62 | } 63 | 64 | private String getCoffee() throws IOException { 65 | try (var http = HttpFactory.connect()) { 66 | var node = http.get(apiUrl).getBodyAsJson().get("file"); 67 | if (node == null) { 68 | throw new IOException("Unexpected JSON structure."); 69 | } 70 | return node.asText(); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/Command.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | import java.util.Collections; 6 | 7 | import com.github.mangstadt.sochat4j.ChatMessage; 8 | 9 | import oakbot.bot.ChatActions; 10 | import oakbot.bot.ChatCommand; 11 | import oakbot.bot.IBot; 12 | 13 | /** 14 | * A chat bot command. 15 | * @author Michael Angstadt 16 | */ 17 | public interface Command { 18 | /** 19 | * Gets the command's name. This is what is used to invoke the command. 20 | * @return the name 21 | */ 22 | String name(); 23 | 24 | /** 25 | * Gets other names that can be used to invoke the command. 26 | * @return the command name aliases 27 | */ 28 | default Collection aliases() { 29 | return Collections.emptyList(); 30 | } 31 | 32 | /** 33 | * Gets the command's help documentation. 34 | * @return the help documentation 35 | */ 36 | HelpDoc help(); 37 | 38 | /** 39 | * Called when a user invokes this command. 40 | * @param chatCommand the command that the user has sent 41 | * @param bot the bot instance 42 | * @return the action(s) to perform in response to the message 43 | */ 44 | ChatActions onMessage(ChatCommand chatCommand, IBot bot); 45 | 46 | /** 47 | * Determines if the given chat message is invoking this command. 48 | * @param message the message 49 | * @param trigger the bot's command trigger 50 | * @return true if the message is invoking this command, false if not 51 | */ 52 | default boolean isInvokingMe(ChatMessage message, String trigger) { 53 | var content = message.getContent().getContent(); 54 | 55 | var names = new ArrayList(); 56 | names.add(name()); 57 | names.addAll(aliases()); 58 | 59 | return names.stream().anyMatch(name -> { 60 | var invocation = trigger + name; 61 | return content.equals(invocation) || content.startsWith(invocation + " "); 62 | }); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/DogCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.error; 4 | 5 | import java.io.IOException; 6 | import java.util.List; 7 | 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | import oakbot.bot.ChatActions; 12 | import oakbot.bot.ChatCommand; 13 | import oakbot.bot.IBot; 14 | import oakbot.bot.PostMessage; 15 | 16 | /** 17 | * Displays a random cat picture. 18 | * @author Michael Angstadt 19 | * @see "https://thecatapi.com/" 20 | */ 21 | public class DogCommand implements Command { 22 | private static final Logger logger = LoggerFactory.getLogger(DogCommand.class); 23 | 24 | private final TheCatDogApiClient client; 25 | 26 | public DogCommand(TheCatDogApiClient client) { 27 | this.client = client; 28 | } 29 | 30 | @Override 31 | public String name() { 32 | return "dog"; 33 | } 34 | 35 | @Override 36 | public List aliases() { 37 | return List.of("woof"); 38 | } 39 | 40 | @Override 41 | public HelpDoc help() { 42 | //@formatter:off 43 | return new HelpDoc.Builder(this) 44 | .summary("Displays a dog GIF. :3") 45 | .detail("Images from thedogapi.com.") 46 | .build(); 47 | //@formatter:on 48 | } 49 | 50 | @Override 51 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 52 | String url; 53 | try { 54 | url = client.getRandomDogGif(); 55 | } catch (IOException e) { 56 | logger.atError().setCause(e).log(() -> "Problem getting dog."); 57 | return error("Error getting dog: ", e, chatCommand); 58 | } 59 | 60 | //@formatter:off 61 | return ChatActions.create( 62 | new PostMessage(url).bypassFilters(true) 63 | ); 64 | //@formatter:on 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/EchoCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.post; 4 | import static oakbot.bot.ChatActions.reply; 5 | 6 | import java.util.List; 7 | 8 | import oakbot.bot.ChatActions; 9 | import oakbot.bot.ChatCommand; 10 | import oakbot.bot.IBot; 11 | 12 | /** 13 | * Makes the bot say something. 14 | * @author Michael Angstadt 15 | */ 16 | public class EchoCommand implements Command { 17 | @Override 18 | public String name() { 19 | return "echo"; 20 | } 21 | 22 | @Override 23 | public List aliases() { 24 | return List.of("say"); 25 | } 26 | 27 | @Override 28 | public HelpDoc help() { 29 | //@formatter:off 30 | return new HelpDoc.Builder(this) 31 | .summary("Makes the bot say something.") 32 | .example("I love Java!", "Makes the bot post the message, \"I love Java!\".") 33 | .build(); 34 | //@formatter:on 35 | } 36 | 37 | @Override 38 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 39 | var content = chatCommand.getContentMarkdown().trim(); 40 | if (content.isEmpty()) { 41 | return reply("Tell me what to say.", chatCommand); 42 | } 43 | 44 | return post(content); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/EightBallCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.reply; 4 | 5 | import oakbot.bot.ChatActions; 6 | import oakbot.bot.ChatCommand; 7 | import oakbot.bot.IBot; 8 | import oakbot.util.Rng; 9 | 10 | /** 11 | * Simulates a magic 8-ball. 12 | * @author Michael Angstadt 13 | */ 14 | public class EightBallCommand implements Command { 15 | //@formatter:off 16 | private final String[] answers = { 17 | //positive 18 | "It is certain", 19 | "It is decidedly so", 20 | "Without a doubt", 21 | "Yes definitely", 22 | "You may rely on it", 23 | "As I see it, yes", 24 | "Most likely", 25 | "Outlook good", 26 | "Yes", 27 | "Signs point to yes", 28 | 29 | //neutral 30 | "Reply hazy try again", 31 | "Ask again later", 32 | "Better not tell you now", 33 | "Cannot predict now", 34 | "Concentrate and ask again", 35 | 36 | //negative 37 | "Don't count on it", 38 | "My reply is no", 39 | "My sources say no", 40 | "Outlook not so good", 41 | "Very doubtful", 42 | "That's impossible", 43 | "When pigs fly", 44 | "Chances are lower than skynet", 45 | "Are you kidding? No!", 46 | "No way" 47 | }; 48 | //@formatter:on 49 | 50 | @Override 51 | public String name() { 52 | return "8ball"; 53 | } 54 | 55 | @Override 56 | public HelpDoc help() { 57 | //@formatter:off 58 | return new HelpDoc.Builder(this) 59 | .summary("Simulates a magic 8-ball.") 60 | .example("Is Java the best?", "") 61 | .build(); 62 | //@formatter:on 63 | } 64 | 65 | @Override 66 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 67 | var answer = Rng.random(answers); 68 | return reply(answer, chatCommand); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/FacepalmCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.reply; 4 | 5 | import java.util.Objects; 6 | 7 | import org.apache.http.client.utils.URIBuilder; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | import com.github.mangstadt.sochat4j.util.Http; 12 | 13 | import oakbot.bot.ChatActions; 14 | import oakbot.bot.ChatCommand; 15 | import oakbot.bot.IBot; 16 | import oakbot.bot.PostMessage; 17 | import oakbot.util.ChatBuilder; 18 | import oakbot.util.HttpFactory; 19 | 20 | /** 21 | * Displays facepalm GIFs using the Tenor API. 22 | * @author Michael Angstadt 23 | * @see "https://tenor.com/gifapi/documentation" 24 | */ 25 | public class FacepalmCommand implements Command { 26 | private static final Logger logger = LoggerFactory.getLogger(FacepalmCommand.class); 27 | 28 | private final String uri; 29 | 30 | /** 31 | * @param key the tenor API key 32 | */ 33 | public FacepalmCommand(String key) { 34 | Objects.requireNonNull(key); 35 | 36 | //see: https://tenor.com/gifapi/documentation#endpoints-random 37 | //@formatter:off 38 | uri = new URIBuilder() 39 | .setScheme("https") 40 | .setHost("api.tenor.com") 41 | .setPath("/v1/random") 42 | .setParameter("key", key) 43 | .setParameter("q", "facepalm") 44 | .setParameter("media_filter", "minimal") 45 | .setParameter("safesearch", "moderate") 46 | .setParameter("limit", "1") 47 | .toString(); 48 | //@formatter:on 49 | } 50 | 51 | @Override 52 | public String name() { 53 | return "facepalm"; 54 | } 55 | 56 | @Override 57 | public HelpDoc help() { 58 | //@formatter:off 59 | return new HelpDoc.Builder(this) 60 | .summary("Displays a facepalm GIF.") 61 | .detail("Images from tenor.com.") 62 | .build(); 63 | //@formatter:on 64 | } 65 | 66 | @Override 67 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 68 | String imageUrl; 69 | Http.Response response = null; 70 | try (var http = HttpFactory.connect()) { 71 | response = http.get(uri); 72 | var node = response.getBodyAsJson(); 73 | imageUrl = node.get("results").get(0).get("media").get(0).get("tinygif").get("url").asText(); 74 | } catch (Exception e) { 75 | String body = (response == null) ? null : response.getBody(); 76 | logger.atError().setCause(e).log(() -> "Problem querying Tenor API.\nURI = " + uri + "\nResponse = " + body); 77 | return reply("Sorry, an error occurred. >.>", chatCommand); 78 | } 79 | 80 | /* 81 | * "All content retrieved from Tenor must be properly attributed." 82 | * 83 | * https://tenor.com/gifapi/documentation#attribution 84 | */ 85 | var condensed = new ChatBuilder().append(imageUrl).append(" (via ").link("Tenor", "https://tenor.com").append(")"); 86 | 87 | //@formatter:off 88 | return ChatActions.create( 89 | new PostMessage(imageUrl).bypassFilters(true).condensedMessage(condensed) 90 | ); 91 | //@formatter:on 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/GiphyClient.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import java.io.IOException; 4 | 5 | import org.apache.http.client.utils.URIBuilder; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import com.fasterxml.jackson.core.JsonProcessingException; 10 | import com.fasterxml.jackson.databind.JsonNode; 11 | import com.github.mangstadt.sochat4j.util.Http; 12 | 13 | import oakbot.util.HttpFactory; 14 | 15 | /** 16 | * Interfaces with the GIPHY API. 17 | * @author Michael Angstadt 18 | * @see "https://developers.giphy.com" 19 | */ 20 | public class GiphyClient { 21 | private static final Logger logger = LoggerFactory.getLogger(GiphyClient.class); 22 | 23 | private final String apiKey; 24 | 25 | /** 26 | * @param apiKey the API key 27 | */ 28 | public GiphyClient(String apiKey) { 29 | this.apiKey = apiKey; 30 | } 31 | 32 | /** 33 | * Retrieves a random GIF. 34 | * @param tag filters result by tag, can be null 35 | * @param rating filters result by content rating, can be null 36 | * @return the URL of the image or null if no images were found 37 | * @throws IOException if an unexpected response was returned or if there 38 | * was a network problem 39 | * @see "https://developers.giphy.com/docs/api/endpoint#random" 40 | */ 41 | public String random(String tag, Rating rating) throws IOException { 42 | var url = baseUrl("random"); 43 | if (tag != null) { 44 | url.addParameter("tag", tag); 45 | } 46 | if (rating != null) { 47 | url.addParameter("rating", rating.value); 48 | } 49 | 50 | var response = send(url.toString()); 51 | 52 | var data = response.path("data"); 53 | if (data.isArray() && data.size() == 0) { 54 | return null; 55 | } 56 | 57 | var node = data.path("images").path("original").path("url"); 58 | if (node.isMissingNode()) { 59 | throw new IOException("Unexpected JSON structure in response."); 60 | } 61 | 62 | return node.asText(); 63 | } 64 | 65 | private JsonNode send(String url) throws IOException { 66 | Http.Response response; 67 | try (var http = HttpFactory.connect()) { 68 | response = http.get(url); 69 | } catch (IOException e) { 70 | logger.atError().setCause(e).log(() -> "Problem sending Giphy API request: " + url); 71 | throw e; 72 | } 73 | 74 | try { 75 | return response.getBodyAsJson(); 76 | } catch (JsonProcessingException e) { 77 | logger.atError().setCause(e).log(() -> "Response could not be parsed as JSON: " + response.getBody()); 78 | throw e; 79 | } 80 | } 81 | 82 | private URIBuilder baseUrl(String endpoint) { 83 | //@formatter:off 84 | return new URIBuilder() 85 | .setScheme("https") 86 | .setHost("api.giphy.com") 87 | .setPathSegments("v1", "gifs", endpoint) 88 | .addParameter("api_key", apiKey); 89 | //@formatter:on 90 | } 91 | 92 | public enum Rating { 93 | G("g"), PG("pg"), PG_13("pg-13"), R("r"); 94 | 95 | private final String value; 96 | 97 | private Rating(String value) { 98 | this.value = value; 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/ReactCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.reply; 4 | 5 | import java.util.List; 6 | 7 | import org.apache.http.client.utils.URIBuilder; 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | import oakbot.bot.ChatActions; 12 | import oakbot.bot.ChatCommand; 13 | import oakbot.bot.IBot; 14 | import oakbot.bot.PostMessage; 15 | import oakbot.util.HttpFactory; 16 | import oakbot.util.Rng; 17 | 18 | /** 19 | * Displays reaction gifs of human emotions. 20 | * @author Michael Angstadt 21 | */ 22 | public class ReactCommand implements Command { 23 | private static final Logger logger = LoggerFactory.getLogger(ReactCommand.class); 24 | 25 | private final URIBuilder uriBuilder; 26 | 27 | public ReactCommand(String key) { 28 | //@formatter:off 29 | uriBuilder = new URIBuilder() 30 | .setScheme("http") 31 | .setHost("replygif.net") 32 | .setPath("/api/gifs") 33 | .setParameter("tag-operator", "and"); 34 | //@formatter:on 35 | 36 | if (key != null && !key.isEmpty()) { 37 | uriBuilder.setParameter("api-key", key); 38 | } 39 | } 40 | 41 | @Override 42 | public String name() { 43 | return "react"; 44 | } 45 | 46 | @Override 47 | public List aliases() { 48 | return List.of("reaction"); 49 | } 50 | 51 | @Override 52 | public HelpDoc help() { 53 | //@formatter:off 54 | return new HelpDoc.Builder(this) 55 | .summary("Displays a reaction GIF.") 56 | .detail("Images from replygif.net.") 57 | .example("happy", "Displays a \"happy\" GIF.") 58 | .build(); 59 | //@formatter:on 60 | } 61 | 62 | @Override 63 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 64 | var content = chatCommand.getContent().trim(); 65 | if (content.isEmpty()) { 66 | return reply("Please specify a human emotion.", chatCommand); 67 | } 68 | 69 | var url = url(content); 70 | 71 | try (var http = HttpFactory.connect()) { 72 | var node = http.get(url).getBodyAsJson(); 73 | if (node.isEmpty()) { 74 | return reply("Unknown human emotion. Please visit http://replygif.net/t for a list of emotions.", chatCommand); 75 | } 76 | 77 | var index = Rng.next(node.size()); 78 | var imageUrl = node.get(index).get("file").asText(); 79 | 80 | //@formatter:off 81 | return ChatActions.create( 82 | new PostMessage(imageUrl).bypassFilters(true) 83 | ); 84 | //@formatter:on 85 | } catch (Exception e) { 86 | logger.atError().setCause(e).log(() -> "Problem querying reaction API."); 87 | 88 | return reply("Sorry, an error occurred >.> : " + e.getMessage(), chatCommand); 89 | } 90 | } 91 | 92 | private String url(String content) { 93 | return uriBuilder.setParameter("tag", content).toString(); 94 | } 95 | } -------------------------------------------------------------------------------- /src/main/java/oakbot/command/ReactGiphyCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.error; 4 | import static oakbot.bot.ChatActions.reply; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import oakbot.bot.ChatActions; 10 | import oakbot.bot.ChatCommand; 11 | import oakbot.bot.IBot; 12 | import oakbot.bot.PostMessage; 13 | import oakbot.command.GiphyClient.Rating; 14 | import oakbot.util.ChatBuilder; 15 | 16 | /** 17 | * Displays reaction GIFs of human emotions. 18 | * @author Michael Angstadt 19 | */ 20 | public class ReactGiphyCommand implements Command { 21 | private static final Logger logger = LoggerFactory.getLogger(ReactGiphyCommand.class); 22 | 23 | private final GiphyClient giphyClient; 24 | 25 | /** 26 | * @param apiKey the GIPHY API key 27 | */ 28 | public ReactGiphyCommand(String apiKey) { 29 | giphyClient = new GiphyClient(apiKey); 30 | } 31 | 32 | @Override 33 | public String name() { 34 | return "react"; 35 | } 36 | 37 | @Override 38 | public HelpDoc help() { 39 | //@formatter:off 40 | return new HelpDoc.Builder(this) 41 | .summary("Displays a random GIF.") 42 | .detail("Images from giphy.com.") 43 | .example("happy", "Displays a \"happy\" GIF.") 44 | .build(); 45 | //@formatter:on 46 | } 47 | 48 | @Override 49 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 50 | var content = chatCommand.getContent().trim(); 51 | if (content.isEmpty()) { 52 | return reply("Please specify a human emotion.", chatCommand); 53 | } 54 | 55 | try { 56 | var imageUrl = giphyClient.random(content, Rating.G); 57 | if (imageUrl == null) { 58 | return reply("404 human emotion not found.", chatCommand); 59 | } 60 | 61 | /* 62 | * URL must end in a file extension in order for chat to display the 63 | * image. 64 | */ 65 | var imageUrlForChat = imageUrl + "&.gif"; 66 | 67 | //@formatter:off 68 | var condensedMessage = new ChatBuilder() 69 | .append("Reaction: ") 70 | .link(content, imageUrl) 71 | .append(" (powered by ").link("GIPHY", "https://giphy.com").append(")"); 72 | 73 | return ChatActions.create( 74 | new PostMessage(imageUrlForChat).bypassFilters(true).condensedMessage(condensedMessage) 75 | ); 76 | //@formatter:on 77 | } catch (Exception e) { 78 | logger.atError().setCause(e).log(() -> "Problem querying GIPHY API."); 79 | return error("Unable to process human emotion: ", e, chatCommand); 80 | } 81 | } 82 | } -------------------------------------------------------------------------------- /src/main/java/oakbot/command/RemindCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.reply; 4 | 5 | import java.time.Duration; 6 | import java.util.regex.Matcher; 7 | import java.util.regex.Pattern; 8 | 9 | import oakbot.bot.ChatActions; 10 | import oakbot.bot.ChatCommand; 11 | import oakbot.bot.IBot; 12 | import oakbot.bot.PostMessage; 13 | import oakbot.util.ChatBuilder; 14 | 15 | /** 16 | * Reminds the user about something. 17 | * @author Michael Angstadt 18 | */ 19 | public class RemindCommand implements Command { 20 | @Override 21 | public String name() { 22 | return "remind"; 23 | } 24 | 25 | @Override 26 | public HelpDoc help() { 27 | //@formatter:off 28 | return new HelpDoc.Builder(this) 29 | .summary("Reminds you about something.") 30 | .detail("Syntax: in [hour|minute]") 31 | .example("do the laundry in 2 hours", "Sends the user a reminder in 2 hours.") 32 | .build(); 33 | //@formatter:on 34 | } 35 | 36 | @Override 37 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 38 | var content = chatCommand.getContent(); 39 | if (content.isEmpty()) { 40 | return reply("Enter what you want to be reminded about, followed by a time period (e.g. " + bot.getTrigger() + name() + " do the laundry in 2 hours)", chatCommand); 41 | } 42 | 43 | var p = Pattern.compile("^(.*?) in (\\d+) (hour|minute)s?", Pattern.CASE_INSENSITIVE); 44 | var m = p.matcher(content); 45 | if (!m.find()) { 46 | return reply("Invalid format. Example: " + bot.getTrigger() + name() + " do the laundry in 2 hours", chatCommand); 47 | } 48 | 49 | var reminder = m.group(1); 50 | var duration = parseDuration(m); 51 | var mention = chatCommand.getMessage().getUsername().replace(" ", ""); 52 | 53 | //@formatter:off 54 | return ChatActions.create( 55 | new PostMessage(new ChatBuilder().reply(chatCommand).append("Created.")), 56 | new PostMessage(new ChatBuilder().mention(mention).append(" ").append(reminder)).delay(duration) 57 | ); 58 | //@formatter:on 59 | } 60 | 61 | private Duration parseDuration(Matcher m) { 62 | var num = Integer.parseInt(m.group(2)); 63 | var period = m.group(3).toLowerCase(); 64 | 65 | return "hour".equals(period) ? Duration.ofHours(num) : Duration.ofMinutes(num); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/ShrugCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.post; 4 | 5 | import oakbot.bot.ChatActions; 6 | import oakbot.bot.ChatCommand; 7 | import oakbot.bot.IBot; 8 | 9 | /** 10 | * Displays a "shrug" emoticon. 11 | * @author Michael Angstadt 12 | */ 13 | public class ShrugCommand implements Command { 14 | @Override 15 | public String name() { 16 | return "shrug"; 17 | } 18 | 19 | @Override 20 | public HelpDoc help() { 21 | //@formatter:off 22 | return new HelpDoc.Builder(this) 23 | .summary("lol idk") 24 | .detail("Displays a \"shrug\" emoticon.") 25 | .includeSummaryWithDetail(false) 26 | .build(); 27 | //@formatter:on 28 | } 29 | 30 | @Override 31 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 32 | return post("¯\\\\_(\u30C4)_/¯"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/ShutdownCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.reply; 4 | 5 | import oakbot.bot.ChatActions; 6 | import oakbot.bot.ChatCommand; 7 | import oakbot.bot.IBot; 8 | import oakbot.bot.PostMessage; 9 | import oakbot.bot.Shutdown; 10 | 11 | /** 12 | * Shuts down the bot. 13 | * @author Michael Angstadt 14 | */ 15 | public class ShutdownCommand implements Command { 16 | 17 | @Override 18 | public String name() { 19 | return "shutdown"; 20 | } 21 | 22 | @Override 23 | public HelpDoc help() { 24 | //@formatter:off 25 | return new HelpDoc.Builder(this) 26 | .summary("Terminates the bot (admins only).") 27 | .build(); 28 | //@formatter:on 29 | } 30 | 31 | @Override 32 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 33 | var userId = chatCommand.getMessage().getUserId(); 34 | if (!bot.isAdminUser(userId)) { 35 | return reply("Only admins can shut me down. :P", chatCommand); 36 | } 37 | 38 | var message = "Shutting down. See you later."; 39 | var broadcast = chatCommand.getContent().equalsIgnoreCase("broadcast"); 40 | 41 | //@formatter:off 42 | return ChatActions.create( 43 | new PostMessage(message).broadcast(broadcast), 44 | new Shutdown() 45 | ); 46 | //@formatter:on 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/SummonCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.error; 4 | import static oakbot.bot.ChatActions.reply; 5 | 6 | import java.io.IOException; 7 | import java.util.List; 8 | 9 | import oakbot.bot.ChatActions; 10 | import oakbot.bot.ChatCommand; 11 | import oakbot.bot.IBot; 12 | import oakbot.bot.JoinRoom; 13 | 14 | /** 15 | * Makes the bot join another room. 16 | * @author Michael Angstadt 17 | */ 18 | public class SummonCommand implements Command { 19 | @Override 20 | public String name() { 21 | return "summon"; 22 | } 23 | 24 | @Override 25 | public List aliases() { 26 | return List.of("join"); 27 | } 28 | 29 | @Override 30 | public HelpDoc help() { 31 | //@formatter:off 32 | return new HelpDoc.Builder(this) 33 | .summary("Makes the bot join another room.") 34 | .detail("Only room owners can make the bot join a room.") 35 | .example("139", "Makes the bot join the room with ID 139.") 36 | .build(); 37 | //@formatter:on 38 | } 39 | 40 | @Override 41 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 42 | var content = chatCommand.getContent().trim(); 43 | 44 | var maxRooms = bot.getMaxRooms(); 45 | if (maxRooms != null && bot.getRooms().size() >= maxRooms) { 46 | return reply("I can't join any more rooms, I've reached my limit (" + maxRooms + ").", chatCommand); 47 | } 48 | 49 | int roomToJoin; 50 | try { 51 | roomToJoin = Integer.parseInt(content); 52 | } catch (NumberFormatException e) { 53 | return reply("Please specify the room ID.", chatCommand); 54 | } 55 | 56 | if (roomToJoin < 1) { 57 | return reply("Invalid room ID.", chatCommand); 58 | } 59 | 60 | if (roomToJoin == chatCommand.getMessage().getRoomId()) { 61 | return reply("That's the ID for this room... -_-", chatCommand); 62 | } 63 | 64 | if (bot.getRooms().contains(roomToJoin)) { 65 | return reply("I'm already there... -_-", chatCommand); 66 | } 67 | 68 | var userId = chatCommand.getMessage().getUserId(); 69 | var authorIsAdmin = bot.isAdminUser(userId); 70 | if (!authorIsAdmin) { 71 | boolean authorIsOwnerOfRoomToJoin; 72 | try { 73 | authorIsOwnerOfRoomToJoin = bot.isRoomOwner(roomToJoin, userId); 74 | } catch (IOException e) { 75 | return error("Unable to join. Error determining whether you are a room owner: ", e, chatCommand); 76 | } 77 | 78 | if (!authorIsOwnerOfRoomToJoin) { 79 | return reply("Only room owners can invite me to rooms.", chatCommand); 80 | } 81 | } 82 | 83 | //@formatter:off 84 | return ChatActions.create( 85 | new JoinRoom(roomToJoin) 86 | .onSuccess(() -> reply("Joined.", chatCommand)) 87 | .ifRoomDoesNotExist(() -> reply("That room doesn't exist...", chatCommand)) 88 | .ifLackingPermissionToPost(() -> reply("I don't seem to have permission to post there.", chatCommand)) 89 | .onError(thrown -> reply("I can't seem to join that room: " + thrown.getMessage(), chatCommand)) 90 | ); 91 | //@formatter:on 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/TagCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.error; 4 | import static oakbot.bot.ChatActions.reply; 5 | 6 | import java.io.IOException; 7 | 8 | import org.apache.http.client.utils.URIBuilder; 9 | import org.jsoup.nodes.Document; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | import com.github.mangstadt.sochat4j.SplitStrategy; 14 | 15 | import oakbot.bot.ChatActions; 16 | import oakbot.bot.ChatCommand; 17 | import oakbot.bot.IBot; 18 | import oakbot.bot.PostMessage; 19 | import oakbot.util.ChatBuilder; 20 | import oakbot.util.HttpFactory; 21 | 22 | /** 23 | * Displays StackOverflow tag descriptions (can sort of act like a Computer 24 | * Science urban dictionary). 25 | * @author Michael Angstadt 26 | */ 27 | public class TagCommand implements Command { 28 | private static final Logger logger = LoggerFactory.getLogger(TagCommand.class); 29 | 30 | @Override 31 | public String name() { 32 | return "tag"; 33 | } 34 | 35 | @Override 36 | public HelpDoc help() { 37 | //@formatter:off 38 | return new HelpDoc.Builder(this) 39 | .summary("Displays the description of a StackOverflow tag.") 40 | .example("mvc", "Displays the description of the \"mvc\" tag.") 41 | .build(); 42 | //@formatter:on 43 | } 44 | 45 | @Override 46 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 47 | var content = chatCommand.getContent().trim(); 48 | if (content.isEmpty()) { 49 | return reply("Please specify the tag name (e.g. \"java\").", chatCommand); 50 | } 51 | 52 | var tag = content.toLowerCase().replace(' ', '-'); 53 | var url = url(tag); 54 | 55 | Document document; 56 | try (var http = HttpFactory.connect()) { 57 | document = http.get(url).getBodyAsHtml(); 58 | } catch (IOException e) { 59 | logger.atError().setCause(e).log(() -> "Error getting tag description."); 60 | return error("An error occurred retrieving the tag description: ", e, chatCommand); 61 | } 62 | 63 | var element = document.getElementById("wiki-excerpt"); 64 | if (element == null) { 65 | return reply("Tag not found. :(", chatCommand); 66 | } 67 | 68 | var definition = element.text(); 69 | 70 | //@formatter:off 71 | return ChatActions.create( 72 | new PostMessage(new ChatBuilder() 73 | .reply(chatCommand) 74 | .tag(tag) 75 | .append(' ').append(definition) 76 | ) 77 | .splitStrategy(SplitStrategy.WORD) 78 | ); 79 | //@formatter:on 80 | } 81 | 82 | private String url(String tag) { 83 | //@formatter:off 84 | return new URIBuilder() 85 | .setScheme("http") 86 | .setHost("stackoverflow.com") 87 | .setPathSegments("tags", tag, "info") 88 | .toString(); 89 | //@formatter:on 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/TheCatDogApiClient.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import java.io.IOException; 4 | 5 | import com.fasterxml.jackson.databind.JsonNode; 6 | 7 | import oakbot.util.HttpFactory; 8 | import oakbot.util.JsonUtils; 9 | import okhttp3.HttpUrl; 10 | import okhttp3.Request; 11 | 12 | /** 13 | * Client for interacting with The Cat API. 14 | * @author Michael Angstadt 15 | * @see "https://thecatapi.com/" 16 | */ 17 | public class TheCatDogApiClient { 18 | private final String apiKey; 19 | 20 | public TheCatDogApiClient() { 21 | this(null); 22 | } 23 | 24 | /** 25 | * @param apiKey the API key (can be null) 26 | */ 27 | public TheCatDogApiClient(String apiKey) { 28 | this.apiKey = apiKey; 29 | } 30 | 31 | /** 32 | * Gets a random cat GIF. 33 | * @return the URL to the image 34 | * @throws IOException if there's a network problem 35 | */ 36 | public String getRandomCatGif() throws IOException { 37 | return getRandomGif("cat"); 38 | } 39 | 40 | /** 41 | * Gets a random dog GIF. 42 | * @return the image URL 43 | * @throws IOException if there's a network problem 44 | */ 45 | public String getRandomDogGif() throws IOException { 46 | return getRandomGif("dog"); 47 | } 48 | 49 | /** 50 | * Gets a random GIF 51 | * @param animal the animal ("cat" or "dog") 52 | * @return the image URL 53 | * @throws IOException if there's a network problem 54 | */ 55 | private String getRandomGif(String animal) throws IOException { 56 | //@formatter:off 57 | var url = baseUrl(animal) 58 | .addPathSegments("/v1/images/search") 59 | .setQueryParameter("size", "small") 60 | .setQueryParameter("mime_types", "gif") 61 | .build(); 62 | //@formatter:on 63 | 64 | var request = requestWithApiKey().url(url).get().build(); 65 | 66 | var response = HttpFactory.okHttp().newCall(request).execute(); 67 | JsonNode body; 68 | try (var reader = response.body().charStream()) { 69 | body = JsonUtils.parse(reader); 70 | } 71 | 72 | var gifUrl = body.path(0).path("url").asText(); 73 | if (gifUrl.isEmpty()) { 74 | throw new IOException("Unexpected JSON structure."); 75 | } 76 | 77 | return gifUrl; 78 | } 79 | 80 | private HttpUrl.Builder baseUrl(String animal) { 81 | //@formatter:off 82 | return new HttpUrl.Builder() 83 | .scheme("https") 84 | .host("api.the" + animal + "api.com"); 85 | //@formatter:on 86 | } 87 | 88 | private Request.Builder requestWithApiKey() { 89 | var builder = new Request.Builder(); 90 | if (apiKey != null) { 91 | builder.addHeader("x-api-key", apiKey); 92 | } 93 | return builder; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/TimeoutCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.reply; 4 | 5 | import java.time.Duration; 6 | import java.util.List; 7 | 8 | import oakbot.bot.ChatActions; 9 | import oakbot.bot.ChatCommand; 10 | import oakbot.bot.IBot; 11 | 12 | /** 13 | * Stops the bot from responding to incoming messages. 14 | * @author Michael Angstadt 15 | */ 16 | public class TimeoutCommand implements Command { 17 | @Override 18 | public String name() { 19 | return "timeout"; 20 | } 21 | 22 | @Override 23 | public List aliases() { 24 | return List.of("shutup"); 25 | } 26 | 27 | @Override 28 | public HelpDoc help() { 29 | //@formatter:off 30 | return new HelpDoc.Builder(this) 31 | .summary("Stops the bot from responding to incoming messages (admins only).") 32 | .detail("Will still respond to messages from admin users.") 33 | .example("10", "Timeout for 10 minutes.") 34 | .example("cancel", "Ends the timeout early.") 35 | .build(); 36 | //@formatter:on 37 | } 38 | 39 | @Override 40 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 41 | var userId = chatCommand.getMessage().getUserId(); 42 | if (!bot.isAdminUser(userId)) { 43 | return reply("Only admins can run this command.", chatCommand); 44 | } 45 | 46 | var content = chatCommand.getContent(); 47 | if ("cancel".equalsIgnoreCase(content)) { 48 | bot.cancelTimeout(); 49 | return reply("Timeout canceled.", chatCommand); 50 | } 51 | 52 | int minutes; 53 | try { 54 | minutes = Integer.parseInt(content); 55 | } catch (NumberFormatException e) { 56 | return reply("Enter the number of minutes.", chatCommand); 57 | } 58 | 59 | if (minutes <= 0) { 60 | return reply("Enter a positive number.", chatCommand); 61 | } 62 | 63 | bot.timeout(Duration.ofMinutes(minutes)); 64 | 65 | return reply("Incoming messages will be ignored for " + minutes + " minutes.", chatCommand); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/UnsummonCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.reply; 4 | 5 | import java.util.List; 6 | 7 | import oakbot.bot.ChatActions; 8 | import oakbot.bot.ChatCommand; 9 | import oakbot.bot.IBot; 10 | import oakbot.bot.LeaveRoom; 11 | import oakbot.bot.PostMessage; 12 | import oakbot.util.ChatBuilder; 13 | import oakbot.util.Rng; 14 | 15 | /** 16 | * Makes the bot leave a room. 17 | * @author Michael Angstadt 18 | */ 19 | public class UnsummonCommand implements Command { 20 | @Override 21 | public String name() { 22 | return "unsummon"; 23 | } 24 | 25 | @Override 26 | public List aliases() { 27 | return List.of("leave"); 28 | } 29 | 30 | @Override 31 | public HelpDoc help() { 32 | //@formatter:off 33 | return new HelpDoc.Builder(this) 34 | .summary("Makes the bot leave a room.") 35 | .detail("Rooms which are designated as \"home\" rooms cannot be left.") 36 | .example("", "Makes the bot leave the current room.") 37 | .example("139", "Makes the bot leave the room with ID 139.") 38 | .build(); 39 | //@formatter:on 40 | } 41 | 42 | @Override 43 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 44 | var content = chatCommand.getContent().trim(); 45 | 46 | int roomToLeave; 47 | boolean inRoomToLeave; 48 | if (content.isEmpty()) { 49 | roomToLeave = chatCommand.getMessage().getRoomId(); 50 | inRoomToLeave = true; 51 | } else { 52 | try { 53 | roomToLeave = Integer.parseInt(content); 54 | } catch (NumberFormatException e) { 55 | return reply("Please specify the room ID.", chatCommand); 56 | } 57 | inRoomToLeave = (roomToLeave == chatCommand.getMessage().getRoomId()); 58 | } 59 | 60 | if (!bot.getRooms().contains(roomToLeave)) { 61 | return reply("I'm not in that room... -_-", chatCommand); 62 | } 63 | 64 | if (bot.getHomeRooms().contains(roomToLeave)) { 65 | if (inRoomToLeave) { 66 | return reply("This is one of my home rooms, I can't leave it.", chatCommand); 67 | } 68 | return reply("That's one of my home rooms, I can't leave it.", chatCommand); 69 | } 70 | 71 | String reply; 72 | if (inRoomToLeave) { 73 | reply = Rng.random("*poof*", "Hasta la vista, baby.", "Bye."); 74 | } else { 75 | reply = Rng.random("They smelled funny anyway.", "Less for me to worry about."); 76 | } 77 | 78 | //@formatter:off 79 | return ChatActions.create( 80 | new PostMessage(new ChatBuilder().reply(chatCommand).append(reply)), 81 | new LeaveRoom(roomToLeave) 82 | ); 83 | //@formatter:on 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/WikiCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActions.post; 4 | import static oakbot.bot.ChatActions.reply; 5 | 6 | import org.apache.http.client.utils.URIBuilder; 7 | 8 | import oakbot.bot.ChatActions; 9 | import oakbot.bot.ChatCommand; 10 | import oakbot.bot.IBot; 11 | 12 | /** 13 | * Displays on-boxed Wikipedia pages. 14 | * @author Michael Angstadt 15 | */ 16 | public class WikiCommand implements Command { 17 | @Override 18 | public String name() { 19 | return "wiki"; 20 | } 21 | 22 | @Override 23 | public HelpDoc help() { 24 | //@formatter:off 25 | return new HelpDoc.Builder(this) 26 | .summary("Displays a one-box for a Wikipedia page.") 27 | .example("James Gosling", "Displays a one-box for the \"James Gosling\" Wikipedia page.") 28 | .build(); 29 | //@formatter:on 30 | } 31 | 32 | @Override 33 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 34 | var content = chatCommand.getContent().trim(); 35 | if (content.isEmpty()) { 36 | return reply("Please specify the term you'd like to display.", chatCommand); 37 | } 38 | 39 | var keyword = content.replace(' ', '_'); 40 | 41 | //@formatter:off 42 | var url = new URIBuilder() 43 | .setScheme("https") 44 | .setHost("en.wikipedia.org") 45 | .setPathSegments("wiki", keyword) 46 | .toString(); 47 | //@formatter:on 48 | 49 | return post(url); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/define/Definition.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.define; 2 | 3 | /** 4 | * A dictionary definition for a word. 5 | * @author Michael Angstadt 6 | */ 7 | public class Definition { 8 | private String wordType; 9 | private String definition; 10 | private String example; 11 | 12 | public String getWordType() { 13 | return wordType; 14 | } 15 | 16 | public void setWordType(String wordType) { 17 | this.wordType = wordType; 18 | } 19 | 20 | public String getDefinition() { 21 | return definition; 22 | } 23 | 24 | public void setDefinition(String definition) { 25 | this.definition = definition; 26 | } 27 | 28 | public String getExample() { 29 | return example; 30 | } 31 | 32 | public void setExample(String example) { 33 | this.example = example; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/javadoc/ClassName.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.javadoc; 2 | 3 | import java.util.Collections; 4 | import java.util.List; 5 | 6 | /** 7 | * Represents the name of a class. 8 | * @author Michael Angstadt 9 | */ 10 | public class ClassName { 11 | /* 12 | * Note: The parts of the fully-qualified name must be separated out like 13 | * this in order for the Javadoc URL of a class to be generated correctly. 14 | */ 15 | private final String packageName; 16 | private final String simpleName; 17 | private final String fullyQualifiedName; 18 | private final List outerClassNames; 19 | 20 | /** 21 | * @param packageName the package name (e.g. "java.util") or null for the 22 | * default package 23 | * @param simpleName the simple name (e.g. "Map") 24 | */ 25 | public ClassName(String packageName, String simpleName) { 26 | this(packageName, Collections.emptyList(), simpleName); 27 | } 28 | 29 | /** 30 | * @param packageName the package name (e.g. "java.util") or null for the 31 | * default package 32 | * @param outerClassNames the outer classes that this class is inside of, 33 | * outer-most to inner-most (e.g. "Map" for the "Map.Entry" class) 34 | * @param simpleName the simple name (e.g. "Entry") 35 | */ 36 | public ClassName(String packageName, List outerClassNames, String simpleName) { 37 | this.packageName = packageName; 38 | this.outerClassNames = Collections.unmodifiableList(outerClassNames); 39 | this.simpleName = simpleName; 40 | 41 | var sb = new StringBuilder(); 42 | if (packageName != null) { 43 | sb.append(packageName).append('.'); 44 | } 45 | for (var outerClassName : outerClassNames) { 46 | sb.append(outerClassName).append('.'); 47 | } 48 | sb.append(simpleName); 49 | fullyQualifiedName = sb.toString(); 50 | } 51 | 52 | /** 53 | * Gets the fully-qualified class name 54 | * @return the fully-qualified class name (e.g. "java.lang.String") 55 | */ 56 | public String getFullyQualifiedName() { 57 | return fullyQualifiedName; 58 | } 59 | 60 | /** 61 | * Gets the name of the package that this class belongs to. 62 | * @return the package name (e.g. "java.lang") or null if it doesn't belong 63 | * to a package 64 | */ 65 | public String getPackageName() { 66 | return packageName; 67 | } 68 | 69 | /** 70 | * Gets the simple names of the outer classes that contain this class. 71 | * @return the outer class names, outer-most to inner-most (e.g. "Map" for 72 | * the "Map.Entry" class) 73 | */ 74 | public List getOuterClassNames() { 75 | return outerClassNames; 76 | } 77 | 78 | /** 79 | * Gets the simple class name. 80 | * @return the simple class name (e.g. "String") 81 | */ 82 | public String getSimpleName() { 83 | return simpleName; 84 | } 85 | 86 | @Override 87 | public String toString() { 88 | return getFullyQualifiedName(); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/javadoc/JavadocDao.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.javadoc; 2 | 3 | import java.io.IOException; 4 | import java.util.Collection; 5 | 6 | /** 7 | * Retrieves class information from Javadoc ZIP files generated by 8 | * oakbot-doclet. 9 | * @author Michael Angstadt 10 | */ 11 | public interface JavadocDao { 12 | /** 13 | * Searches for the fully-qualified name of a class. 14 | * @param query can be a simple class name (e.g. "string") or a 15 | * fully-qualified class name (e.g. "java.lang.String"). Case does not 16 | * matter. If a fully-qualified class name is entered and this DAO is not 17 | * aware of that class, then this method will return an empty list. 18 | * @return the fully-qualified class name(s) that were found or an empty 19 | * list if none were found 20 | * @throws IOException if there's a problem searching for the name 21 | */ 22 | Collection search(String query) throws IOException; 23 | 24 | /** 25 | * Gets the Javadoc info on a class. 26 | * @param fullyQualifiedClassName the class's fully-qualified class name 27 | * (e.g. "java.lang.String", case-sensitive) 28 | * @return the Javadoc info or null if the class was not found 29 | * @throws IOException if there's a problem retrieving the info 30 | */ 31 | ClassInfo getClassInfo(String fullyQualifiedClassName) throws IOException; 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/javadoc/JavadocDaoUncached.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.javadoc; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.util.ArrayList; 7 | import java.util.Collection; 8 | import java.util.HashSet; 9 | import java.util.List; 10 | 11 | /** 12 | * Stores nothing in memory, allowing for lower memory usage. 13 | * @author Michael Angstadt 14 | */ 15 | public class JavadocDaoUncached implements JavadocDao { 16 | private final Path dir; 17 | 18 | /** 19 | * @param dir the directory where the Javadoc ZIP files are stored 20 | */ 21 | public JavadocDaoUncached(Path dir) { 22 | this.dir = dir; 23 | } 24 | 25 | @Override 26 | public Collection search(String query) throws IOException { 27 | var names = new HashSet(); 28 | for (var file : getZipFiles()) { 29 | var zip = new JavadocZipFile(file); 30 | for (var className : zip.getClassNames()) { 31 | var fullName = className.getFullyQualifiedName(); 32 | var simpleName = className.getSimpleName(); 33 | if (fullName.equalsIgnoreCase(query) || simpleName.equalsIgnoreCase(query)) { 34 | names.add(fullName); 35 | } 36 | } 37 | } 38 | return names; 39 | } 40 | 41 | @Override 42 | public ClassInfo getClassInfo(String fullyQualifiedClassName) throws IOException { 43 | for (var file : getZipFiles()) { 44 | var zip = new JavadocZipFile(file); 45 | var info = zip.getClassInfo(fullyQualifiedClassName); 46 | if (info != null) { 47 | return info; 48 | } 49 | } 50 | 51 | return null; 52 | } 53 | 54 | private List getZipFiles() throws IOException { 55 | var files = new ArrayList(); 56 | try (var stream = Files.newDirectoryStream(dir, JavadocDaoUncached::isZipFile)) { 57 | stream.forEach(files::add); 58 | } 59 | return files; 60 | } 61 | 62 | /** 63 | * Determines if a file has a ".zip" extension (case sensitive). 64 | * @param file the file 65 | * @return true if it does, false it not 66 | */ 67 | private static boolean isZipFile(Path file) { 68 | return file.getFileName().toString().toLowerCase().endsWith(".zip"); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/javadoc/ParameterInfo.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.javadoc; 2 | 3 | /** 4 | * Contains information on a method parameter. 5 | * @author Michael Angstadt 6 | */ 7 | public record ParameterInfo(ClassName type, String name, boolean array, boolean varargs, String generic) { 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/learn/UnlearnCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.learn; 2 | 3 | import static oakbot.bot.ChatActions.reply; 4 | 5 | import java.util.List; 6 | 7 | import oakbot.bot.ChatActions; 8 | import oakbot.bot.ChatCommand; 9 | import oakbot.bot.IBot; 10 | import oakbot.command.Command; 11 | import oakbot.command.HelpDoc; 12 | 13 | /** 14 | * Removes a learned command. 15 | * @author Michael Angstadt 16 | */ 17 | public class UnlearnCommand implements Command { 18 | private final List hardcodedCommands; 19 | private final LearnedCommandsDao learnedCommands; 20 | 21 | public UnlearnCommand(List hardcodedCommands, LearnedCommandsDao learnedCommands) { 22 | this.hardcodedCommands = hardcodedCommands; 23 | this.learnedCommands = learnedCommands; 24 | } 25 | 26 | @Override 27 | public String name() { 28 | return "unlearn"; 29 | } 30 | 31 | @Override 32 | public List aliases() { 33 | return List.of("forget"); 34 | } 35 | 36 | @Override 37 | public HelpDoc help() { 38 | //@formatter:off 39 | return new HelpDoc.Builder(this) 40 | .summary("Deletes a learned command.") 41 | .example("happy", "Deletes the command called \"happy\".") 42 | .build(); 43 | //@formatter:on 44 | } 45 | 46 | @Override 47 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 48 | var commandName = chatCommand.getContent().trim(); 49 | if (commandName.isEmpty()) { 50 | return reply("You haven't specified the command name.", chatCommand); 51 | } 52 | 53 | if (hardcodedCommandExists(commandName)) { 54 | return reply("That command is not a learned command. You can only unlearn commands that were added with the \"learn\" command.", chatCommand); 55 | } 56 | 57 | var removed = learnedCommands.remove(commandName); 58 | if (!removed) { 59 | return reply("That command does not exist.", chatCommand); 60 | } 61 | 62 | return reply("Command forgotten.", chatCommand); 63 | } 64 | 65 | private boolean hardcodedCommandExists(String commandName) { 66 | for (var command : hardcodedCommands) { 67 | if (commandName.equalsIgnoreCase(command.name())) { 68 | return true; 69 | } 70 | for (var alias : command.aliases()) { 71 | if (commandName.equalsIgnoreCase(alias)) { 72 | return true; 73 | } 74 | } 75 | } 76 | return false; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/shibe/BirdCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.shibe; 2 | 3 | import static oakbot.bot.ChatActions.error; 4 | 5 | import java.io.IOException; 6 | import java.util.List; 7 | 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | import oakbot.bot.ChatActions; 12 | import oakbot.bot.ChatCommand; 13 | import oakbot.bot.IBot; 14 | import oakbot.bot.PostMessage; 15 | import oakbot.command.Command; 16 | import oakbot.command.HelpDoc; 17 | 18 | /** 19 | * Displays a bird picture. 20 | * @author Michael Angstadt 21 | * @see "https://shibe.online/" 22 | */ 23 | public class BirdCommand implements Command { 24 | private static final Logger logger = LoggerFactory.getLogger(BirdCommand.class); 25 | 26 | private final ShibeOnlineClient client; 27 | 28 | public BirdCommand(ShibeOnlineClient client) { 29 | this.client = client; 30 | } 31 | 32 | @Override 33 | public String name() { 34 | return "bird"; 35 | } 36 | 37 | @Override 38 | public List aliases() { 39 | return List.of("birb"); 40 | } 41 | 42 | @Override 43 | public HelpDoc help() { 44 | //@formatter:off 45 | return new HelpDoc.Builder(this) 46 | .summary("Displays an image of a bird.") 47 | .detail("Images from shibe.online.") 48 | .build(); 49 | //@formatter:on 50 | } 51 | 52 | @Override 53 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 54 | String url; 55 | try { 56 | url = client.getBird(); 57 | } catch (IOException e) { 58 | logger.atError().setCause(e).log(() -> "Problem getting bird."); 59 | return error("Error getting bird: ", e, chatCommand); 60 | } 61 | 62 | //@formatter:off 63 | return ChatActions.create( 64 | new PostMessage(url).bypassFilters(true) 65 | ); 66 | //@formatter:on 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/shibe/ShibaCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.shibe; 2 | 3 | import static oakbot.bot.ChatActions.error; 4 | 5 | import java.io.IOException; 6 | import java.util.List; 7 | 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | import oakbot.bot.ChatActions; 12 | import oakbot.bot.ChatCommand; 13 | import oakbot.bot.IBot; 14 | import oakbot.bot.PostMessage; 15 | import oakbot.command.Command; 16 | import oakbot.command.HelpDoc; 17 | 18 | /** 19 | * Displays a shiba dog picture. 20 | * @author Michael Angstadt 21 | * @see "https://shibe.online/" 22 | */ 23 | public class ShibaCommand implements Command { 24 | private static final Logger logger = LoggerFactory.getLogger(ShibaCommand.class); 25 | 26 | private final ShibeOnlineClient client; 27 | 28 | public ShibaCommand(ShibeOnlineClient client) { 29 | this.client = client; 30 | } 31 | 32 | @Override 33 | public String name() { 34 | return "shiba"; 35 | } 36 | 37 | @Override 38 | public List aliases() { 39 | return List.of("woof"); 40 | } 41 | 42 | @Override 43 | public HelpDoc help() { 44 | //@formatter:off 45 | return new HelpDoc.Builder(this) 46 | .summary("Displays an image of a shiba inu dog.") 47 | .detail("Images from shibe.online.") 48 | .build(); 49 | //@formatter:on 50 | } 51 | 52 | @Override 53 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 54 | String url; 55 | try { 56 | url = client.getShiba(); 57 | } catch (IOException e) { 58 | logger.atError().setCause(e).log(() -> "Problem getting shiba."); 59 | return error("Error getting shiba: ", e, chatCommand); 60 | } 61 | 62 | //@formatter:off 63 | return ChatActions.create( 64 | new PostMessage(url).bypassFilters(true) 65 | ); 66 | //@formatter:on 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/shibe/ShibeOnlineClient.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.shibe; 2 | 3 | import java.io.IOException; 4 | 5 | import org.apache.http.client.utils.URIBuilder; 6 | 7 | import com.github.mangstadt.sochat4j.util.Http; 8 | 9 | import oakbot.util.HttpFactory; 10 | 11 | /** 12 | * Displays random animal pictures using shibe.online. 13 | * @author Michael Angstadt 14 | * @see "https://shibe.online/" 15 | */ 16 | public class ShibeOnlineClient { 17 | public String getBird() throws IOException { 18 | return getAnimal("birds"); 19 | } 20 | 21 | public String getCat() throws IOException { 22 | return getAnimal("cats"); 23 | } 24 | 25 | public String getShiba() throws IOException { 26 | return getAnimal("shibes"); 27 | } 28 | 29 | private String getAnimal(String animal) throws IOException { 30 | //@formatter:off 31 | var url = new URIBuilder() 32 | .setScheme("https") 33 | .setHost("shibe.online") 34 | .setPathSegments("api", animal) 35 | .toString(); 36 | //@formatter:on 37 | 38 | Http.Response response; 39 | try (var http = HttpFactory.connect()) { 40 | response = http.get(url); 41 | } 42 | 43 | var node = response.getBodyAsJson().get(0); 44 | if (node == null) { 45 | throw new IOException("JSON response not structured as expected."); 46 | } 47 | 48 | return node.asText(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/stands4/AbbreviationCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.stands4; 2 | 3 | import static oakbot.bot.ChatActions.error; 4 | import static oakbot.bot.ChatActions.post; 5 | import static oakbot.bot.ChatActions.reply; 6 | 7 | import java.io.IOException; 8 | import java.util.List; 9 | 10 | import oakbot.bot.ChatActions; 11 | import oakbot.bot.ChatCommand; 12 | import oakbot.bot.IBot; 13 | import oakbot.command.Command; 14 | import oakbot.command.HelpDoc; 15 | import oakbot.util.ChatBuilder; 16 | 17 | /** 18 | * Gets abbreviation definitions from abbreviations.com. 19 | * @author Michael Angstadt 20 | * @see "https://www.abbreviations.com/abbr_api.php" 21 | */ 22 | public class AbbreviationCommand implements Command { 23 | private final Stands4Client client; 24 | private final int maxResultsToDisplay = 10; 25 | 26 | /** 27 | * @param client the STANDS4 API client 28 | */ 29 | public AbbreviationCommand(Stands4Client client) { 30 | this.client = client; 31 | } 32 | 33 | @Override 34 | public String name() { 35 | return "abbr"; 36 | } 37 | 38 | @Override 39 | public HelpDoc help() { 40 | //@formatter:off 41 | return new HelpDoc.Builder(this) 42 | .summary("Retrieves abbreviation definitions from abbreviations.com.") 43 | .example("asap", "Displays the " + maxResultsToDisplay + " most popular definitions for \"asap\".") 44 | .build(); 45 | //@formatter:on 46 | } 47 | 48 | @Override 49 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 50 | var abbr = chatCommand.getContent().trim(); 51 | if (abbr.isEmpty()) { 52 | return reply("Enter an abbreviation.", chatCommand); 53 | } 54 | 55 | List results; 56 | try { 57 | results = client.getAbbreviations(abbr, maxResultsToDisplay); 58 | } catch (IOException e) { 59 | return error("Sorry, an unexpected error occurred: ", e, chatCommand); 60 | } 61 | 62 | var url = client.getAbbreviationsAttributionUrl(abbr); 63 | 64 | //@formatter:off 65 | return post(new ChatBuilder() 66 | .reply(chatCommand) 67 | .append(results.isEmpty() ? "No results found." : String.join(" | ", results)) 68 | .append(" (").link("source", url).append(")") 69 | ); 70 | //@formatter:on 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/stands4/ConvertCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.stands4; 2 | 3 | import static oakbot.bot.ChatActions.error; 4 | import static oakbot.bot.ChatActions.post; 5 | import static oakbot.bot.ChatActions.reply; 6 | 7 | import java.io.IOException; 8 | 9 | import oakbot.bot.ChatActions; 10 | import oakbot.bot.ChatCommand; 11 | import oakbot.bot.IBot; 12 | import oakbot.command.Command; 13 | import oakbot.command.HelpDoc; 14 | import oakbot.util.ChatBuilder; 15 | 16 | /** 17 | * Performs unit conversions. 18 | * @author Michael Angstadt 19 | * @see "https://www.convert.net/conv_api.php" 20 | */ 21 | public class ConvertCommand implements Command { 22 | private final Stands4Client client; 23 | 24 | /** 25 | * @param client the STANDS4 API client 26 | */ 27 | public ConvertCommand(Stands4Client client) { 28 | this.client = client; 29 | } 30 | 31 | @Override 32 | public String name() { 33 | return "convert"; 34 | } 35 | 36 | @Override 37 | public HelpDoc help() { 38 | //@formatter:off 39 | return new HelpDoc.Builder(this) 40 | .summary("Performs a unit conversion.") 41 | .example("5 km in miles", "Displays how many miles are in 5 kilometers.") 42 | .build(); 43 | //@formatter:on 44 | } 45 | 46 | @Override 47 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 48 | var query = chatCommand.getContent().trim(); 49 | if (query.isEmpty()) { 50 | return reply("Specify what you want to convert.", chatCommand); 51 | } 52 | 53 | String result; 54 | try { 55 | result = client.convert(query); 56 | } catch (ConvertException e) { 57 | return error("What kind of garbage did you enter? ", e, chatCommand); 58 | } catch (IOException e) { 59 | return error("Sorry, an unexpected error occurred: ", e, chatCommand); 60 | } 61 | 62 | var url = client.getConvertAttributionUrl(); 63 | 64 | //@formatter:off 65 | return post(new ChatBuilder() 66 | .reply(chatCommand) 67 | .append(result) 68 | .append(" (").link("source", url).append(")") 69 | ); 70 | //@formatter:on 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/stands4/ConvertException.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.stands4; 2 | 3 | /** 4 | * Thrown when there is a problem doing a unit conversion. 5 | * @author Michael Angstadt 6 | * @see Stands4Client#convert 7 | */ 8 | public class ConvertException extends RuntimeException { 9 | private static final long serialVersionUID = 1L; 10 | 11 | private final int code; 12 | 13 | public ConvertException(int code, String message) { 14 | super(message); 15 | this.code = code; 16 | } 17 | 18 | public int getCode() { 19 | return code; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/stands4/ExplainCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.stands4; 2 | 3 | import static oakbot.bot.ChatActions.error; 4 | import static oakbot.bot.ChatActions.post; 5 | import static oakbot.bot.ChatActions.reply; 6 | 7 | import java.io.IOException; 8 | 9 | import oakbot.bot.ChatActions; 10 | import oakbot.bot.ChatCommand; 11 | import oakbot.bot.IBot; 12 | import oakbot.command.Command; 13 | import oakbot.command.HelpDoc; 14 | import oakbot.util.ChatBuilder; 15 | 16 | /** 17 | * Explains a common idiom using phrases.com. 18 | * @author Michael Angstadt 19 | * @see "https://www.phrases.com/phrases_api.php" 20 | */ 21 | public class ExplainCommand implements Command { 22 | private final Stands4Client client; 23 | 24 | /** 25 | * @param client the STANDS4 API client 26 | */ 27 | public ExplainCommand(Stands4Client client) { 28 | this.client = client; 29 | } 30 | 31 | @Override 32 | public String name() { 33 | return "explain"; 34 | } 35 | 36 | @Override 37 | public HelpDoc help() { 38 | //@formatter:off 39 | return new HelpDoc.Builder(this) 40 | .summary("Explains a common idiom using phrases.com.") 41 | .example("eat my shorts", "Displays an explanation of the given phrase.") 42 | .build(); 43 | //@formatter:on 44 | } 45 | 46 | @Override 47 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 48 | var phrase = chatCommand.getContent().trim(); 49 | if (phrase.isEmpty()) { 50 | return reply("Enter a phrase.", chatCommand); 51 | } 52 | 53 | Explanation result; 54 | try { 55 | result = client.explain(phrase); 56 | } catch (IOException e) { 57 | return error("Sorry, an unexpected error occurred: ", e, chatCommand); 58 | } 59 | 60 | var cb = new ChatBuilder().reply(chatCommand); 61 | if (result == null) { 62 | cb.append("No explanation found."); 63 | } else { 64 | cb.append(result.getExplanation()); 65 | 66 | var example = result.getExample(); 67 | if (example != null) { 68 | cb.append(" ").italic(result.getExample()); 69 | } 70 | } 71 | 72 | var url = client.getExplainAttributionUrl(phrase); 73 | cb.append(" (").link("source", url).append(")"); 74 | 75 | return post(cb); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/stands4/Explanation.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.stands4; 2 | 3 | /** 4 | * An explanation of a common idiom. 5 | * @author Michael Angstadt 6 | * @see Stands4Client#explain 7 | */ 8 | public class Explanation { 9 | private final String explanation; 10 | private final String example; 11 | 12 | public Explanation(String explanation, String example) { 13 | this.explanation = explanation; 14 | this.example = example; 15 | } 16 | 17 | public String getExplanation() { 18 | return explanation; 19 | } 20 | 21 | public String getExample() { 22 | return example; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/stands4/GrammarCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.stands4; 2 | 3 | import static oakbot.bot.ChatActions.error; 4 | import static oakbot.bot.ChatActions.post; 5 | import static oakbot.bot.ChatActions.reply; 6 | 7 | import java.io.IOException; 8 | import java.util.List; 9 | 10 | import oakbot.bot.ChatActions; 11 | import oakbot.bot.ChatCommand; 12 | import oakbot.bot.IBot; 13 | import oakbot.command.Command; 14 | import oakbot.command.HelpDoc; 15 | import oakbot.util.ChatBuilder; 16 | 17 | /** 18 | * Checks a sentence for grammar using grammar.com. 19 | * @author Michael Angstadt 20 | * @see "https://www.grammar.com/grammar_api.php" 21 | */ 22 | public class GrammarCommand implements Command { 23 | private final Stands4Client client; 24 | 25 | /** 26 | * @param client the STANDS4 API client 27 | */ 28 | public GrammarCommand(Stands4Client client) { 29 | this.client = client; 30 | } 31 | 32 | @Override 33 | public String name() { 34 | return "grammar"; 35 | } 36 | 37 | @Override 38 | public HelpDoc help() { 39 | //@formatter:off 40 | return new HelpDoc.Builder(this) 41 | .summary("Checks a sentence for grammar using grammar.com") 42 | .build(); 43 | //@formatter:on 44 | } 45 | 46 | @Override 47 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 48 | var sentence = chatCommand.getContent().trim(); 49 | if (sentence.isEmpty()) { 50 | return reply("Specify the sentence to check.", chatCommand); 51 | } 52 | 53 | List results; 54 | try { 55 | results = client.checkGrammar(sentence); 56 | } catch (IOException e) { 57 | return error("Sorry, an unexpected error occurred: ", e, chatCommand); 58 | } 59 | 60 | var url = client.getGrammarAttributionUrl(); 61 | 62 | if (results.isEmpty()) { 63 | //@formatter:off 64 | return post(new ChatBuilder() 65 | .reply(chatCommand) 66 | .append("No errors found.") 67 | .append(" (checked by ").append(url).append(")") 68 | ); 69 | //@formatter:on 70 | } 71 | 72 | //@formatter:off 73 | return post(new ChatBuilder() 74 | .reply(chatCommand) 75 | .append(String.join("\n", results)) 76 | .nl().append("checked by: ").append(url) 77 | ); 78 | //@formatter:on 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/stands4/RhymeCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.stands4; 2 | 3 | import static oakbot.bot.ChatActions.error; 4 | import static oakbot.bot.ChatActions.post; 5 | import static oakbot.bot.ChatActions.reply; 6 | 7 | import java.io.IOException; 8 | import java.util.List; 9 | 10 | import oakbot.bot.ChatActions; 11 | import oakbot.bot.ChatCommand; 12 | import oakbot.bot.IBot; 13 | import oakbot.command.Command; 14 | import oakbot.command.HelpDoc; 15 | import oakbot.util.ChatBuilder; 16 | 17 | /** 18 | * Gets words that rhyme from rhymes.com. 19 | * @author Michael Angstadt 20 | * @see "https://www.rhymes.com/rhymes_api.php" 21 | */ 22 | public class RhymeCommand implements Command { 23 | private final Stands4Client client; 24 | 25 | /** 26 | * @param client the STANDS4 API client 27 | */ 28 | public RhymeCommand(Stands4Client client) { 29 | this.client = client; 30 | } 31 | 32 | @Override 33 | public String name() { 34 | return "rhyme"; 35 | } 36 | 37 | @Override 38 | public HelpDoc help() { 39 | //@formatter:off 40 | return new HelpDoc.Builder(this) 41 | .summary("Finds words that rhyme with the given word.") 42 | .detail("Results are from rhymes.com.") 43 | .example("code", "Displays words that rhyme with \"code\".") 44 | .build(); 45 | //@formatter:on 46 | } 47 | 48 | @Override 49 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 50 | var word = chatCommand.getContent().trim(); 51 | if (word.isEmpty()) { 52 | return reply("Enter a word.", chatCommand); 53 | } 54 | 55 | List results; 56 | try { 57 | results = client.getRhymes(word); 58 | } catch (IOException e) { 59 | return error("Sorry, an unexpected error occurred: ", e, chatCommand); 60 | } 61 | 62 | var url = client.getRhymesAttributionUrl(word); 63 | 64 | //@formatter:off 65 | return post(new ChatBuilder() 66 | .reply(chatCommand) 67 | .append(results.isEmpty() ? "No results found." : String.join(", ", results)) 68 | .append(" (").link("source", url).append(")") 69 | ); 70 | //@formatter:on 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/urban/UrbanDefinition.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.urban; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | 6 | /** 7 | * Represents a word definition within an {@link UrbanResponse}. 8 | * @author Michael Angstadt 9 | */ 10 | @JsonIgnoreProperties(ignoreUnknown = true) 11 | public class UrbanDefinition { 12 | @JsonProperty("defid") 13 | private long id; 14 | 15 | private String word; 16 | private String author; 17 | private String permalink; 18 | private String definition; 19 | private String example; 20 | 21 | @JsonProperty("thumbs_up") 22 | private long thumbsUp; 23 | 24 | @JsonProperty("thumbs_down") 25 | private long thumbsDown; 26 | 27 | public long getId() { 28 | return id; 29 | } 30 | 31 | public void setId(long id) { 32 | this.id = id; 33 | } 34 | 35 | public String getWord() { 36 | return word; 37 | } 38 | 39 | public void setWord(String word) { 40 | this.word = word; 41 | } 42 | 43 | public String getAuthor() { 44 | return author; 45 | } 46 | 47 | public void setAuthor(String author) { 48 | this.author = author; 49 | } 50 | 51 | public String getPermalink() { 52 | return permalink; 53 | } 54 | 55 | public void setPermalink(String permalink) { 56 | this.permalink = permalink; 57 | } 58 | 59 | public String getDefinition() { 60 | return definition; 61 | } 62 | 63 | public void setDefinition(String definition) { 64 | this.definition = definition; 65 | } 66 | 67 | public String getExample() { 68 | return example; 69 | } 70 | 71 | public void setExample(String example) { 72 | this.example = example; 73 | } 74 | 75 | public long getThumbsUp() { 76 | return thumbsUp; 77 | } 78 | 79 | public void setThumbsUp(long thumbsUp) { 80 | this.thumbsUp = thumbsUp; 81 | } 82 | 83 | public long getThumbsDown() { 84 | return thumbsDown; 85 | } 86 | 87 | public void setThumbsDown(long thumbsDown) { 88 | this.thumbsDown = thumbsDown; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/oakbot/command/urban/UrbanResponse.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.urban; 2 | 3 | import java.util.List; 4 | 5 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 6 | import com.fasterxml.jackson.annotation.JsonProperty; 7 | 8 | /** 9 | * Represents a response from the Urban Dictionary API. 10 | * @author Michael Angstadt 11 | */ 12 | @JsonIgnoreProperties(ignoreUnknown = true) 13 | public class UrbanResponse { 14 | private List tags; 15 | 16 | @JsonProperty("result_type") 17 | private String resultType; 18 | 19 | @JsonProperty("list") 20 | private List definitions; 21 | 22 | private List sounds; 23 | 24 | public List getTags() { 25 | return tags; 26 | } 27 | 28 | public void setTags(List tags) { 29 | this.tags = tags; 30 | } 31 | 32 | public String getResultType() { 33 | return resultType; 34 | } 35 | 36 | public void setResultType(String resultType) { 37 | this.resultType = resultType; 38 | } 39 | 40 | public List getDefinitions() { 41 | return definitions; 42 | } 43 | 44 | public void setDefinitions(List definitions) { 45 | this.definitions = definitions; 46 | } 47 | 48 | public List getSounds() { 49 | return sounds; 50 | } 51 | 52 | public void setSounds(List sounds) { 53 | this.sounds = sounds; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/oakbot/discord/AboutCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.discord; 2 | 3 | import java.time.LocalDateTime; 4 | import java.time.ZoneId; 5 | 6 | import net.dv8tion.jda.api.events.message.MessageReceivedEvent; 7 | import oakbot.Main; 8 | import oakbot.command.HelpDoc; 9 | import oakbot.util.ChatBuilder; 10 | import oakbot.util.RelativeDateFormat; 11 | 12 | /** 13 | * Displays meta information about the bot. 14 | * @author Michael Angstadt 15 | */ 16 | public class AboutCommand implements DiscordCommand { 17 | private final LocalDateTime startedUp = LocalDateTime.now(); 18 | 19 | @Override 20 | public String name() { 21 | return "about"; 22 | } 23 | 24 | @Override 25 | public HelpDoc help() { 26 | //@formatter:off 27 | return new DiscordHelpDoc.Builder(this) 28 | .summary("Displays information about this bot.") 29 | .build(); 30 | //@formatter:on 31 | } 32 | 33 | @Override 34 | public void onMessage(String content, MessageReceivedEvent event, BotContext context) { 35 | var relativeDf = new RelativeDateFormat(); 36 | var built = LocalDateTime.ofInstant(Main.BUILT, ZoneId.systemDefault()); 37 | 38 | //@formatter:off 39 | var cb = new ChatBuilder() 40 | .bold("OakBot").append(" by ").link("Michael", "https://stackoverflow.com/users/13379/michael").nl() 41 | .link("source code", Main.URL).nl() 42 | .append("JAR built on: ").append(relativeDf.format(built)).append(" | ") 43 | .append("started up: ").append(relativeDf.format(startedUp)); 44 | //@formatter:on 45 | 46 | event.getMessage().reply(cb).queue(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/oakbot/discord/BotContext.java: -------------------------------------------------------------------------------- 1 | package oakbot.discord; 2 | 3 | /** 4 | * @author Michael Angstadt 5 | */ 6 | public record BotContext (boolean authorIsAdmin, String trigger) { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/oakbot/discord/CatCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.discord; 2 | 3 | import java.io.IOException; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; 9 | import net.dv8tion.jda.api.interactions.commands.build.Commands; 10 | import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; 11 | import oakbot.command.TheCatDogApiClient; 12 | 13 | /** 14 | * Displays a random cat picture. 15 | * @author Michael Angstadt 16 | * @see "https://thecatapi.com/" 17 | */ 18 | public class CatCommand implements DiscordSlashCommand { 19 | private static final Logger logger = LoggerFactory.getLogger(CatCommand.class); 20 | 21 | private final TheCatDogApiClient client; 22 | 23 | public CatCommand(TheCatDogApiClient client) { 24 | this.client = client; 25 | } 26 | 27 | @Override 28 | public SlashCommandData data() { 29 | var name = "cat"; 30 | var description = "Displays a cat GIF 🐱. Images from thecatapi.com."; 31 | 32 | return Commands.slash(name, description); 33 | } 34 | 35 | @Override 36 | public void onMessage(SlashCommandInteractionEvent event, BotContext context) { 37 | String url; 38 | try { 39 | url = client.getRandomCatGif(); 40 | } catch (IOException e) { 41 | logger.atError().setCause(e).log(() -> "Problem getting cat."); 42 | event.getChannel().sendMessage("Error getting cat: `" + e.getMessage() + "`").queue(); 43 | return; 44 | } 45 | 46 | event.reply(url).queue(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/oakbot/discord/CoffeeCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.discord; 2 | 3 | import java.io.IOException; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | import com.fasterxml.jackson.databind.JsonNode; 9 | 10 | import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; 11 | import net.dv8tion.jda.api.interactions.commands.build.Commands; 12 | import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; 13 | import oakbot.util.HttpFactory; 14 | import oakbot.util.JsonUtils; 15 | import okhttp3.Request; 16 | 17 | /** 18 | * Displays a coffee-related picture. 19 | * @author Michael Angstadt 20 | * @see "https://coffee.alexflipnote.dev" 21 | */ 22 | public class CoffeeCommand implements DiscordSlashCommand { 23 | private static final Logger logger = LoggerFactory.getLogger(CoffeeCommand.class); 24 | 25 | private final Request request = new Request.Builder().url("https://coffee.alexflipnote.dev/random.json").get().build(); 26 | 27 | @Override 28 | public SlashCommandData data() { 29 | var name = "coffee"; 30 | var description = "Displays a random coffee photo ☕. Images from https://coffee.alexflipnote.dev."; 31 | 32 | return Commands.slash(name, description); 33 | } 34 | 35 | @Override 36 | public void onMessage(SlashCommandInteractionEvent event, BotContext context) { 37 | String url; 38 | try { 39 | url = getCoffee(); 40 | } catch (IOException e) { 41 | logger.atError().setCause(e).log(() -> "Problem getting coffee."); 42 | event.reply("Error getting coffee: " + e.getMessage()).queue(); 43 | return; 44 | } 45 | 46 | event.reply(url).queue(); 47 | } 48 | 49 | private String getCoffee() throws IOException { 50 | var response = HttpFactory.okHttp().newCall(request).execute(); 51 | 52 | JsonNode body; 53 | try (var reader = response.body().charStream()) { 54 | body = JsonUtils.parse(reader); 55 | } 56 | 57 | var node = body.get("file"); 58 | if (node == null) { 59 | throw new IOException("Unexpected JSON structure."); 60 | } 61 | return node.asText(); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/oakbot/discord/CommandListener.java: -------------------------------------------------------------------------------- 1 | package oakbot.discord; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import net.dv8tion.jda.api.events.message.MessageReceivedEvent; 10 | 11 | /** 12 | * @author Michael Angstadt 13 | */ 14 | public class CommandListener implements DiscordListener { 15 | private static final Logger logger = LoggerFactory.getLogger(CommandListener.class); 16 | 17 | private final String trigger; 18 | private final List commands; 19 | 20 | public CommandListener(String trigger, List commands) { 21 | this.trigger = trigger; 22 | 23 | /* 24 | * Do not copy this list defensively. List must be modified after 25 | * constructor runs in order to add "help" command. 26 | */ 27 | this.commands = commands; 28 | } 29 | 30 | @Override 31 | public void onMessage(MessageReceivedEvent event, BotContext context) { 32 | var message = event.getMessage().getContentDisplay(); 33 | var partsOpt = parseCommandParts(message); 34 | if (!partsOpt.isPresent()) { 35 | return; 36 | } 37 | 38 | var parts = partsOpt.get(); 39 | 40 | //@formatter:off 41 | commands.stream() 42 | .filter(c -> c.name().equalsIgnoreCase(parts.name())) 43 | .forEach(c -> { 44 | try { 45 | c.onMessage(parts.content(), event, context); 46 | } catch (Exception e) { 47 | logger.atError().setCause(e).log(() -> "Unhandled exception thrown by " + c.getClass().getName() + "."); 48 | } 49 | }); 50 | //@formatter:on 51 | } 52 | 53 | private record CommandParts(String name, String content) { 54 | } 55 | 56 | private Optional parseCommandParts(String message) { 57 | if (!message.startsWith(trigger)) { 58 | return Optional.empty(); 59 | } 60 | 61 | String name; 62 | String content; 63 | var afterTrigger = message.substring(trigger.length()).trim(); 64 | var space = afterTrigger.indexOf(' '); 65 | if (space < 0) { 66 | name = afterTrigger; 67 | content = ""; 68 | } else { 69 | name = afterTrigger.substring(0, space).toLowerCase(); 70 | content = afterTrigger.substring(space + 1); 71 | } 72 | 73 | return Optional.of(new CommandParts(name, content)); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/oakbot/discord/DiscordCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.discord; 2 | 3 | import net.dv8tion.jda.api.events.message.MessageReceivedEvent; 4 | import oakbot.command.HelpDoc; 5 | 6 | /** 7 | * @author Michael Angstadt 8 | */ 9 | public interface DiscordCommand { 10 | String name(); 11 | 12 | HelpDoc help(); 13 | 14 | void onMessage(String content, MessageReceivedEvent event, BotContext context); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/oakbot/discord/DiscordHelpDoc.java: -------------------------------------------------------------------------------- 1 | package oakbot.discord; 2 | 3 | import static oakbot.util.StringUtils.plural; 4 | 5 | import java.util.List; 6 | 7 | import oakbot.util.ChatBuilder; 8 | 9 | /** 10 | * Contains all of the help documentation for a command or listener. 11 | * @author Michael Angstadt 12 | */ 13 | public class DiscordHelpDoc extends oakbot.command.HelpDoc { 14 | private DiscordHelpDoc(Builder builder) { 15 | super(builder); 16 | } 17 | 18 | /** 19 | * Builds the help message to post when the user requests more detail about 20 | * the command/listener. 21 | * @param trigger the bot's command trigger (only applicable for commands) 22 | * @return the help message 23 | */ 24 | @Override 25 | public String getHelpText(String trigger) { 26 | var cb = new ChatBuilder(); 27 | cb.code().append(trigger).append(name).code().nl(); 28 | 29 | if (includeSummaryWithDetail) { 30 | cb.append(summary); 31 | } 32 | if (detail != null) { 33 | cb.append(' ').append(detail); 34 | } 35 | 36 | if (!examples.isEmpty()) { 37 | cb.nl().nl().bold(plural("Example", examples.size())).append(":"); 38 | for (var example : examples) { 39 | cb.nl().code().append(trigger).append(name); 40 | if (!example.parameters().isEmpty()) { 41 | cb.append(' ').append(example.parameters()); 42 | } 43 | cb.code(); 44 | if (!example.description().isEmpty()) { 45 | cb.append(" ").append(example.description()); 46 | } 47 | } 48 | } 49 | 50 | if (!aliases.isEmpty()) { 51 | cb.nl().nl().bold(plural("Alias", aliases.size())).append(": ").append(String.join(",", aliases)); 52 | } 53 | 54 | return cb.toString(); 55 | } 56 | 57 | /** 58 | * Creates instances of {@link DiscordHelpDoc}. 59 | * @author Michael Angstadt 60 | */ 61 | public static class Builder extends oakbot.command.HelpDoc.Builder { 62 | /** 63 | * @param command the command this documentation is for 64 | */ 65 | public Builder(DiscordCommand command) { 66 | super(command.name(), List.of()); 67 | } 68 | 69 | /** 70 | * @param listener the listener this documentation is for 71 | */ 72 | public Builder(DiscordListener listener) { 73 | super(listener.name(), List.of()); 74 | } 75 | 76 | /** 77 | * Builds the {@link DiscordHelpDoc} instance. 78 | * @return the instance 79 | */ 80 | @Override 81 | public DiscordHelpDoc build() { 82 | return new DiscordHelpDoc(this); 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/oakbot/discord/DiscordListener.java: -------------------------------------------------------------------------------- 1 | package oakbot.discord; 2 | 3 | import net.dv8tion.jda.api.events.message.MessageReceivedEvent; 4 | import oakbot.command.HelpDoc; 5 | 6 | /** 7 | * @author Michael Angstadt 8 | */ 9 | public interface DiscordListener { 10 | default String name() { 11 | return null; 12 | } 13 | 14 | default HelpDoc help() { 15 | return null; 16 | } 17 | 18 | default boolean onlyRespondWhenMentioned() { 19 | return false; 20 | } 21 | 22 | void onMessage(MessageReceivedEvent event, BotContext context); 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/oakbot/discord/DiscordProperties.java: -------------------------------------------------------------------------------- 1 | package oakbot.discord; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Path; 5 | import java.util.List; 6 | 7 | import oakbot.util.PropertiesWrapper; 8 | 9 | /** 10 | * @author Michael Angstadt 11 | */ 12 | public class DiscordProperties extends PropertiesWrapper { 13 | private final String discordToken; 14 | private final String discordStatus; 15 | private final String openAIKey; 16 | private final String stabilityAIKey; 17 | private final int openAIMessageHistoryCount; 18 | private final String openAIPrompt; 19 | private final List adminUsers; 20 | private final List ignoredChannels; 21 | 22 | public DiscordProperties(Path path) throws IOException { 23 | super(path); 24 | discordToken = get("discord.token"); 25 | discordStatus = get("discord.status"); 26 | openAIKey = get("openai.key"); 27 | openAIMessageHistoryCount = getInteger("openai.messageHistoryCount", 10); 28 | openAIPrompt = get("openai.prompt"); 29 | stabilityAIKey = get("stabilityai.key"); 30 | adminUsers = getLongList("admins"); 31 | ignoredChannels = getLongList("ignoredChannels"); 32 | } 33 | 34 | public String getDiscordToken() { 35 | return discordToken; 36 | } 37 | 38 | public String getDiscordStatus() { 39 | return discordStatus; 40 | } 41 | 42 | public String getOpenAIKey() { 43 | return openAIKey; 44 | } 45 | 46 | public String getStabilityAIKey() { 47 | return stabilityAIKey; 48 | } 49 | 50 | public int getOpenAIMessageHistoryCount() { 51 | return openAIMessageHistoryCount; 52 | } 53 | 54 | public String getOpenAIPrompt() { 55 | return openAIPrompt; 56 | } 57 | 58 | public List getAdminUsers() { 59 | return adminUsers; 60 | } 61 | 62 | public List getIgnoredChannels() { 63 | return ignoredChannels; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/oakbot/discord/DiscordSlashCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.discord; 2 | 3 | import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; 4 | import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; 5 | 6 | /** 7 | * @author Michael Angstadt 8 | */ 9 | public interface DiscordSlashCommand { 10 | SlashCommandData data(); 11 | 12 | void onMessage(SlashCommandInteractionEvent event, BotContext context); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/oakbot/discord/DogCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.discord; 2 | 3 | import java.io.IOException; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; 9 | import net.dv8tion.jda.api.interactions.commands.build.Commands; 10 | import net.dv8tion.jda.api.interactions.commands.build.SlashCommandData; 11 | import oakbot.command.TheCatDogApiClient; 12 | 13 | /** 14 | * Displays a random dog picture. 15 | * @author Michael Angstadt 16 | * @see "https://thecatapi.com/" 17 | */ 18 | public class DogCommand implements DiscordSlashCommand { 19 | private static final Logger logger = LoggerFactory.getLogger(DogCommand.class); 20 | 21 | private final TheCatDogApiClient client; 22 | 23 | public DogCommand(TheCatDogApiClient client) { 24 | this.client = client; 25 | } 26 | 27 | @Override 28 | public SlashCommandData data() { 29 | var name = "dog"; 30 | var description = "Displays a dog GIF 🐶. Images from thedogapi.com."; 31 | 32 | return Commands.slash(name, description); 33 | } 34 | 35 | @Override 36 | public void onMessage(SlashCommandInteractionEvent event, BotContext context) { 37 | String url; 38 | try { 39 | url = client.getRandomDogGif(); 40 | } catch (IOException e) { 41 | logger.atError().setCause(e).log(() -> "Problem getting dog."); 42 | event.getChannel().sendMessage("Error getting dog: `" + e.getMessage() + "`").queue(); 43 | return; 44 | } 45 | 46 | event.reply(url).queue(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/oakbot/discord/MainDiscord.java: -------------------------------------------------------------------------------- 1 | package oakbot.discord; 2 | 3 | import java.nio.file.Paths; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.stream.Collectors; 7 | 8 | import net.dv8tion.jda.api.entities.Guild; 9 | import oakbot.ai.openai.OpenAIClient; 10 | import oakbot.ai.stabilityai.StabilityAIClient; 11 | import oakbot.command.TheCatDogApiClient; 12 | import oakbot.util.HttpRequestLogger; 13 | 14 | /** 15 | * Connects to a Discord app. 16 | * @author Michael Angstadt 17 | * @see "https://discord.com/developers" 18 | */ 19 | public class MainDiscord { 20 | public static void main(String[] args) throws Exception { 21 | var properties = new DiscordProperties(Paths.get(args[0])); 22 | var openAIClient = new OpenAIClient(properties.getOpenAIKey(), new HttpRequestLogger("openai-requests.discord.csv")); 23 | var stabilityAIClient = new StabilityAIClient(properties.getStabilityAIKey()); 24 | var theCatDogApiClient = new TheCatDogApiClient(); 25 | var trigger = "!"; 26 | 27 | //@formatter:off 28 | var slashCommands = List.of( 29 | new CatCommand(theCatDogApiClient), 30 | new CoffeeCommand(), 31 | new DogCommand(theCatDogApiClient), 32 | new ImagineCommand(openAIClient, stabilityAIClient) 33 | ); 34 | var commands = new ArrayList<>(List.of( 35 | new AboutCommand(), 36 | new ShutdownCommand() 37 | )); 38 | var listeners = List.of( 39 | new ChatGPTListener(openAIClient, "gpt-4o", properties.getOpenAIPrompt(), 2000, properties.getOpenAIMessageHistoryCount()), 40 | new WaveListener(), 41 | new CommandListener(trigger, commands) 42 | ); 43 | //@formatter:on 44 | 45 | //create help command 46 | var helpCommand = new HelpCommand(slashCommands, commands, listeners); 47 | commands.add(helpCommand); 48 | 49 | //@formatter:off 50 | var bot = new DiscordBot.Builder() 51 | .adminUsers(properties.getAdminUsers()) 52 | .ignoredChannels(properties.getIgnoredChannels()) 53 | .slashCommands(slashCommands) 54 | .listeners(listeners) 55 | .status(properties.getDiscordStatus()) 56 | .token(properties.getDiscordToken()) 57 | .trigger(trigger) 58 | .build(); 59 | //@formatter:on 60 | 61 | Runtime.getRuntime().addShutdownHook(new Thread(bot::shutdown)); 62 | 63 | var jda = bot.getJDA(); 64 | System.out.println("Guilds joined: " + jda.getGuildCache().stream().map(Guild::getName).collect(Collectors.joining(", "))); 65 | 66 | System.out.println("Bot has launched successfully. To move this process to the background, press Ctrl+Z then type \"bg\"."); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/oakbot/discord/ShutdownCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.discord; 2 | 3 | import net.dv8tion.jda.api.events.message.MessageReceivedEvent; 4 | import oakbot.command.HelpDoc; 5 | 6 | /** 7 | * @author Michael Angstadt 8 | */ 9 | public class ShutdownCommand implements DiscordCommand { 10 | @Override 11 | public String name() { 12 | return "shutdown"; 13 | } 14 | 15 | @Override 16 | public HelpDoc help() { 17 | //@formatter:off 18 | return new DiscordHelpDoc.Builder(this) 19 | .summary("Terminates the bot (admins only).") 20 | .build(); 21 | //@formatter:on 22 | } 23 | 24 | @Override 25 | public void onMessage(String content, MessageReceivedEvent event, BotContext context) { 26 | if (context.authorIsAdmin()) { 27 | event.getChannel().sendMessage("Shutting down...").queue(); 28 | event.getJDA().shutdown(); 29 | } else { 30 | event.getChannel().sendMessage("Only admins can shut me down.").queue(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/oakbot/discord/WaveListener.java: -------------------------------------------------------------------------------- 1 | package oakbot.discord; 2 | 3 | import net.dv8tion.jda.api.entities.emoji.Emoji; 4 | import net.dv8tion.jda.api.events.message.MessageReceivedEvent; 5 | import oakbot.command.HelpDoc; 6 | 7 | /** 8 | * @author Michael Angstadt 9 | */ 10 | public class WaveListener implements DiscordListener { 11 | @Override 12 | public String name() { 13 | return "wave"; 14 | } 15 | 16 | @Override 17 | public HelpDoc help() { 18 | //@formatter:off 19 | return new DiscordHelpDoc.Builder(this) 20 | .summary("Waves back at you. o/") 21 | .detail("Adds a \"wave\" reaction to your post when you post o/ or \\o.") 22 | .includeSummaryWithDetail(false) 23 | .build(); 24 | //@formatter:on 25 | } 26 | 27 | @Override 28 | public void onMessage(MessageReceivedEvent event, BotContext context) { 29 | var message = event.getMessage().getContentDisplay(); 30 | if ("o/".equals(message) || "\\o".equals(message)) { 31 | event.getMessage().addReaction(Emoji.fromUnicode("U+1F44B")).queue(); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/oakbot/filter/ChatResponseFilter.java: -------------------------------------------------------------------------------- 1 | package oakbot.filter; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * Modifies the content of a chat message before it is sent. 8 | * @author Michael Angstadt 9 | */ 10 | public abstract class ChatResponseFilter { 11 | /** 12 | * Is the filter enabled in all rooms? 13 | */ 14 | protected boolean globallyEnabled = false; 15 | 16 | /** 17 | * The rooms the filter is enabled in. 18 | */ 19 | protected Set enabledRooms = new HashSet<>(); 20 | 21 | /** 22 | * Determines if the filter is enabled in a given room. 23 | * @param roomId the room ID 24 | * @return true if enabled, false if not 25 | */ 26 | public boolean isEnabled(int roomId) { 27 | return globallyEnabled ? true : enabledRooms.contains(roomId); 28 | } 29 | 30 | /** 31 | * Toggles the filter in a given room. 32 | * @param roomId the room ID 33 | * @return true if the filter is now enabled, false if not 34 | */ 35 | public boolean toggle(int roomId) { 36 | boolean enabled = isEnabled(roomId); 37 | setEnabled(roomId, !enabled); 38 | return !enabled; 39 | } 40 | 41 | /** 42 | * Enables or disables the filter in all rooms. 43 | * @param enabled true to enable, false to disable 44 | */ 45 | public void setGloballyEnabled(boolean enabled) { 46 | globallyEnabled = enabled; 47 | } 48 | 49 | /** 50 | * Enables or disables the filter in a specific room. 51 | * @param roomId the room ID 52 | * @param enabled true to enable, false to disable 53 | */ 54 | public void setEnabled(int roomId, boolean enabled) { 55 | if (enabled) { 56 | enabledRooms.add(roomId); 57 | } else { 58 | enabledRooms.remove(roomId); 59 | } 60 | } 61 | 62 | /** 63 | * Performs the filter operation. This method is not responsible for 64 | * checking if the filter is enabled or not. 65 | * @param message the message to filter 66 | * @return the filtered message 67 | */ 68 | public abstract String filter(String message); 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/oakbot/filter/ToggleableFilter.java: -------------------------------------------------------------------------------- 1 | package oakbot.filter; 2 | 3 | import oakbot.bot.ChatActions; 4 | import oakbot.bot.ChatCommand; 5 | import oakbot.bot.IBot; 6 | import oakbot.bot.PostMessage; 7 | import oakbot.command.Command; 8 | import oakbot.util.ChatBuilder; 9 | 10 | /** 11 | * A filter which users can toggle using a command. 12 | * @author Michael Angstadt 13 | */ 14 | public abstract class ToggleableFilter extends ChatResponseFilter implements Command { 15 | @Override 16 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 17 | var roomId = chatCommand.getMessage().getRoomId(); 18 | var enabled = toggle(roomId); 19 | 20 | //@formatter:off 21 | return ChatActions.create( 22 | new PostMessage(new ChatBuilder() 23 | .reply(chatCommand) 24 | .append("Filter ").append(enabled ? "enabled" : "disabled").append(".") 25 | ).bypassFilters(true) 26 | ); 27 | //@formatter:on 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/oakbot/filter/UpsidedownTextFilter.java: -------------------------------------------------------------------------------- 1 | package oakbot.filter; 2 | 3 | import oakbot.command.HelpDoc; 4 | import oakbot.util.CharIterator; 5 | 6 | /** 7 | * Turns text upside down. 8 | * @author Michael Angstadt 9 | * @see http://stackoverflow.com/q/24371977/13379 10 | */ 11 | public class UpsidedownTextFilter extends ToggleableFilter { 12 | private final char[] map; 13 | { 14 | String normal, upsideDown; 15 | 16 | //@formatter:off 17 | normal = "abcdefghijklmnopqrstuvwxyz"; 18 | upsideDown = "ɐqɔpǝɟƃɥıɾʞlɯuodbɹsʇnʌʍxʎz"; 19 | 20 | normal += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 21 | upsideDown += "∀qϽᗡƎℲƃHIſʞ˥WNOԀὉᴚS⊥∩ΛMXʎZ"; 22 | 23 | normal += "0123456789"; 24 | upsideDown += "0ƖᄅƐㄣϛ9ㄥ86"; 25 | 26 | normal += "<>&,;.?!'\""; 27 | upsideDown += "><⅋'؛˙¿¡,„"; 28 | //@formatter:on 29 | 30 | var highestAsciiValue = normal.chars().max().getAsInt(); 31 | map = new char[highestAsciiValue + 1]; 32 | 33 | for (var i = 0; i < normal.length(); i++) { 34 | char n = normal.charAt(i); 35 | char u = upsideDown.charAt(i); 36 | map[n] = u; 37 | } 38 | } 39 | 40 | @Override 41 | public String name() { 42 | return "rollover"; 43 | } 44 | 45 | @Override 46 | public HelpDoc help() { 47 | //@formatter:off 48 | return new HelpDoc.Builder(this) 49 | .summary("Turns the bot upside down.") 50 | .detail("Toggles a filter that makes all the letters in the messages Oak posts look like they are upside down.") 51 | .includeSummaryWithDetail(false) 52 | .build(); 53 | //@formatter:on 54 | } 55 | 56 | @Override 57 | public String filter(String message) { 58 | var sb = new StringBuilder(message.length()); 59 | 60 | var flip = true; 61 | var inReplySyntax = false; 62 | var it = new CharIterator(message); 63 | while (it.hasNext()) { 64 | var n = it.next(); 65 | 66 | if (it.index() == 0 && n == ':') { 67 | //preserve reply syntax 68 | inReplySyntax = true; 69 | sb.append(n); 70 | continue; 71 | } 72 | 73 | if (inReplySyntax) { 74 | if (Character.isDigit(n)) { 75 | sb.append(n); 76 | continue; 77 | } 78 | inReplySyntax = false; 79 | } 80 | 81 | if (it.prev() == ']' && n == '(') { 82 | //preserve the URL that links are linked to 83 | flip = false; 84 | sb.append(n); 85 | continue; 86 | } 87 | 88 | if (!flip) { 89 | if (n == ')') { 90 | //end of link URL 91 | flip = true; 92 | } 93 | sb.append(n); 94 | continue; 95 | } 96 | 97 | sb.append(flipIfPossible(n)); 98 | } 99 | 100 | return sb.toString(); 101 | } 102 | 103 | private char flipIfPossible(char c) { 104 | if (c >= map.length) { 105 | return c; 106 | } 107 | 108 | var flipped = map[c]; 109 | return (flipped == 0) ? c : flipped; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/main/java/oakbot/imgur/ImgurClient.java: -------------------------------------------------------------------------------- 1 | package oakbot.imgur; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | 6 | import org.apache.http.client.methods.HttpPost; 7 | import org.apache.http.entity.ContentType; 8 | import org.apache.http.entity.mime.MultipartEntityBuilder; 9 | 10 | import com.fasterxml.jackson.databind.JsonNode; 11 | 12 | import oakbot.util.HttpFactory; 13 | import oakbot.util.JsonUtils; 14 | 15 | /** 16 | * @author Michael Angstadt 17 | * @see "https://apidocs.imgur.com" 18 | */ 19 | public class ImgurClient { 20 | private final String clientId; 21 | 22 | /** 23 | * @param clientId the client ID 24 | */ 25 | public ImgurClient(String clientId) { 26 | this.clientId = clientId; 27 | } 28 | 29 | /** 30 | * Uploads an image or video file. 31 | * @param data the file data 32 | * @return the URL of the uploaded file (e.g. 33 | * "https://i.imgur.com/m0VmUir.jpeg") 34 | * @throws ImgurException if an error response is returned 35 | * @throws IOException if there's a network error 36 | * @see Support 38 | * file types and API details 39 | */ 40 | public String uploadFile(byte[] data) throws ImgurException, IOException { 41 | var request = postRequestWithClientId("/image"); 42 | 43 | //@formatter:off 44 | request.setEntity(MultipartEntityBuilder.create() 45 | .addTextBody("type", "file") 46 | .addBinaryBody("image", data, ContentType.APPLICATION_OCTET_STREAM, "file") 47 | .build()); 48 | //@formatter:on 49 | 50 | try (var client = HttpFactory.connect().getClient()) { 51 | try (var response = client.execute(request)) { 52 | JsonNode responseBody; 53 | try (InputStream in = response.getEntity().getContent()) { 54 | responseBody = JsonUtils.parse(in); 55 | } 56 | 57 | lookForError(responseBody); 58 | 59 | return parseImageUploadResponse(responseBody); 60 | } 61 | } 62 | } 63 | 64 | private String parseImageUploadResponse(JsonNode node) { 65 | return node.path("data").path("link").asText(); 66 | } 67 | 68 | /** 69 | * Throws an exception if there is an error in the given response. 70 | * @param response the response 71 | * @throws ImgurException if there is an error in the given response 72 | */ 73 | private void lookForError(JsonNode response) throws ImgurException { 74 | var error = response.path("data").get("error"); 75 | if (error == null) { 76 | return; 77 | } 78 | 79 | var message = error.asText(); 80 | throw new ImgurException(message); 81 | } 82 | 83 | private HttpPost postRequestWithClientId(String uriPath) { 84 | var request = new HttpPost("https://api.imgur.com/3" + uriPath); 85 | request.setHeader("Authorization", "Client-ID " + clientId); 86 | return request; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/oakbot/imgur/ImgurException.java: -------------------------------------------------------------------------------- 1 | package oakbot.imgur; 2 | 3 | /** 4 | * @author Michael Angstadt 5 | */ 6 | public class ImgurException extends RuntimeException { 7 | private static final long serialVersionUID = 1L; 8 | 9 | public ImgurException(String message) { 10 | super(message); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/oakbot/inactivity/FillTheSilenceTask.java: -------------------------------------------------------------------------------- 1 | package oakbot.inactivity; 2 | 3 | import java.time.Duration; 4 | 5 | import com.github.mangstadt.sochat4j.IRoom; 6 | 7 | import oakbot.bot.IBot; 8 | import oakbot.bot.PostMessage; 9 | import oakbot.util.Rng; 10 | 11 | /** 12 | * Causes the bot to post messages when a room has been inactive for some 13 | * time. "Quiet" rooms are excluded from this. 14 | * @author Michael Angstadt 15 | */ 16 | public class FillTheSilenceTask implements InactivityTask { 17 | //@formatter:off 18 | private final String[] messages = { 19 | "*farts*", 20 | "*picks nose*", 21 | "*reads a book*", 22 | "*dreams of electric sheep*", 23 | "*twiddles thumbs*", 24 | "*yawns loudly*", 25 | "*solves P vs NP*", 26 | "*doodles*", 27 | "*hums a song*", 28 | "*nods off*", 29 | "*fights crime*", 30 | "*uses java.io.File*", 31 | "*uses java.util.Hashtable*", 32 | "*opens the pod bay doors*" 33 | }; 34 | //@formatter:on 35 | 36 | private final Duration inactivityTime; 37 | 38 | public FillTheSilenceTask(String inactivityTime) { 39 | this.inactivityTime = Duration.parse(inactivityTime); 40 | } 41 | 42 | @Override 43 | public Duration getInactivityTime(IRoom room, IBot bot) { 44 | //never post to quiet rooms 45 | if (bot.getQuietRooms().contains(room.getRoomId())) { 46 | return null; 47 | } 48 | 49 | return inactivityTime; 50 | } 51 | 52 | @Override 53 | public void run(IRoom room, IBot bot) throws Exception { 54 | var message = Rng.random(messages); 55 | bot.sendMessage(room.getRoomId(), new PostMessage(message)); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/oakbot/inactivity/InactivityTask.java: -------------------------------------------------------------------------------- 1 | package oakbot.inactivity; 2 | 3 | import java.time.Duration; 4 | 5 | import com.github.mangstadt.sochat4j.IRoom; 6 | 7 | import oakbot.bot.IBot; 8 | 9 | /** 10 | * A task that runs if no messages have been posted to a room for a certain 11 | * amount of time. 12 | * @author Michael Angstadt 13 | */ 14 | public interface InactivityTask { 15 | /** 16 | * Returns the amount of time the given room must be inactive for before 17 | * the task is run. 18 | * @param room the room 19 | * @param bot the bot 20 | * @return the amount of time or null to never run the task in this room 21 | */ 22 | Duration getInactivityTime(IRoom room, IBot bot); 23 | 24 | /** 25 | * The code to run when the inactivity time has been reached. 26 | * @param room the room 27 | * @param bot the bot 28 | */ 29 | void run(IRoom room, IBot bot) throws Exception; 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/oakbot/inactivity/LeaveRoomTask.java: -------------------------------------------------------------------------------- 1 | package oakbot.inactivity; 2 | 3 | import java.time.Duration; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | import com.github.mangstadt.sochat4j.IRoom; 9 | 10 | import oakbot.bot.IBot; 11 | import oakbot.bot.PostMessage; 12 | 13 | /** 14 | * Causes the bot to leave the room if the room has been inactive for some 15 | * time. "Home" rooms are excluded from this. 16 | * @author Michael Angstadt 17 | */ 18 | public class LeaveRoomTask implements InactivityTask { 19 | private static final Logger logger = LoggerFactory.getLogger(LeaveRoomTask.class); 20 | 21 | private final Duration inactivityTime; //e.g. 3 days 22 | 23 | public LeaveRoomTask(String inactivityTime) { 24 | this.inactivityTime = Duration.parse(inactivityTime); 25 | } 26 | 27 | @Override 28 | public Duration getInactivityTime(IRoom room, IBot bot) { 29 | //never leave home rooms 30 | if (bot.getHomeRooms().contains(room.getRoomId())) { 31 | return null; 32 | } 33 | 34 | return inactivityTime; 35 | } 36 | 37 | @Override 38 | public void run(IRoom room, IBot bot) throws Exception { 39 | try { 40 | bot.sendMessage(room.getRoomId(), new PostMessage("*quietly closes the door behind him*")); 41 | } catch (Exception e) { 42 | logger.atError().setCause(e).log(() -> "Could not post message to room " + room.getRoomId() + "."); 43 | } 44 | 45 | bot.leave(room.getRoomId()); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/oakbot/listener/BotlerListener.java: -------------------------------------------------------------------------------- 1 | package oakbot.listener; 2 | 3 | import static oakbot.bot.ChatActions.doNothing; 4 | import static oakbot.bot.ChatActions.post; 5 | 6 | import java.time.Duration; 7 | import java.time.Instant; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | import com.github.mangstadt.sochat4j.ChatMessage; 12 | 13 | import oakbot.bot.ChatActions; 14 | import oakbot.bot.ChatCommand; 15 | import oakbot.bot.IBot; 16 | import oakbot.command.Command; 17 | import oakbot.command.HelpDoc; 18 | import oakbot.util.Now; 19 | 20 | /** 21 | * Allows users to make the bot send commands to Botler, a bot by Captain 22 | * Obvious. Also, responds to Botler's startup message. 23 | * @author Michael Angstadt 24 | * @see "https://stackoverflow.com/users/13750349/botler" 25 | * @see "https://github.com/butler1233/stackoverflow-chatbot" 26 | */ 27 | public class BotlerListener implements Command, Listener { 28 | private final String botlerTrigger; 29 | private final int botlerUserId; 30 | private final String botlerStartupMessage; 31 | private final String response; 32 | private final Duration timeBetweenResponses; 33 | private final Map responseTimesPerRoom = new HashMap<>(); 34 | 35 | /** 36 | * @param botlerTrigger Botler's trigger 37 | * @param botlerUserId Botler's user ID 38 | * @param botlerStartupMessage the Botler message to respond to 39 | * @param response the response 40 | */ 41 | public BotlerListener(String botlerTrigger, int botlerUserId, String botlerStartupMessage, String response, String timeBetweenResponses) { 42 | this.botlerTrigger = botlerTrigger; 43 | this.botlerUserId = botlerUserId; 44 | this.botlerStartupMessage = botlerStartupMessage; 45 | this.response = response; 46 | this.timeBetweenResponses = Duration.parse(timeBetweenResponses); 47 | } 48 | 49 | @Override 50 | public String name() { 51 | return "botler"; 52 | } 53 | 54 | @Override 55 | public HelpDoc help() { 56 | //@formatter:off 57 | return new HelpDoc.Builder((Command)this) 58 | .summary("Makes Oak send commands to Botler, a bot by Captain Obvious (be nice).") 59 | .detail("Also, responds to Botler's startup message. Botler's GitHub: https://github.com/butler1233/stackoverflow-chatbot") 60 | .example("help", "Sends the help command to Botler.") 61 | .build(); 62 | //@formatter:on 63 | } 64 | 65 | @Override 66 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 67 | var content = chatCommand.getContentMarkdown(); 68 | if (content.isEmpty()) { 69 | return doNothing(); 70 | } 71 | 72 | return post(botlerTrigger + " " + content); 73 | } 74 | 75 | @Override 76 | public ChatActions onMessage(ChatMessage message, IBot bot) { 77 | if (message.getUserId() != botlerUserId) { 78 | return doNothing(); 79 | } 80 | 81 | if (!botlerStartupMessage.equals(message.getContent().getContent())) { 82 | return doNothing(); 83 | } 84 | 85 | var now = Now.instant(); 86 | var roomId = message.getRoomId(); 87 | var lastResponse = responseTimesPerRoom.get(roomId); 88 | 89 | if (lastResponse != null) { 90 | var sinceLastResponse = Duration.between(lastResponse, now); 91 | if (sinceLastResponse.compareTo(timeBetweenResponses) < 0) { 92 | return doNothing(); 93 | } 94 | } 95 | 96 | responseTimesPerRoom.put(roomId, now); 97 | return post(response); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/oakbot/listener/CatchAllMentionListener.java: -------------------------------------------------------------------------------- 1 | package oakbot.listener; 2 | 3 | /** 4 | * Used for listeners that respond to mentions containing nothing in particular. 5 | * Allows other listeners to respond to mentions and tell the "catch all" 6 | * mention listeners not to respond. 7 | * @author Michael Angstadt 8 | */ 9 | public interface CatchAllMentionListener extends Listener { 10 | /** 11 | * Tells this listener to not respond to the next message it receives. 12 | */ 13 | void ignoreNextMessage(); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/oakbot/listener/Listener.java: -------------------------------------------------------------------------------- 1 | package oakbot.listener; 2 | 3 | import com.github.mangstadt.sochat4j.ChatMessage; 4 | 5 | import oakbot.bot.ChatActions; 6 | import oakbot.bot.IBot; 7 | import oakbot.command.HelpDoc; 8 | 9 | /** 10 | * Listens to each new message and optionally responds to it. 11 | * @author Michael Angstadt 12 | */ 13 | public interface Listener { 14 | /** 15 | * Gets the listener's name to display in the help documentation. 16 | * @return the name or null not to display this listener in the help 17 | * documentation 18 | */ 19 | default String name() { 20 | return null; 21 | } 22 | 23 | /** 24 | * Gets the listener's help documentation. 25 | * @return the help documentation or null if this listener does not have any 26 | * help documentation 27 | */ 28 | default HelpDoc help() { 29 | return null; 30 | } 31 | 32 | /** 33 | * Called whenever a new message is received. 34 | * @param message the message 35 | * @param bot the bot instance 36 | * @return the action(s) to perform in response to the message 37 | */ 38 | ChatActions onMessage(ChatMessage message, IBot bot); 39 | } -------------------------------------------------------------------------------- /src/main/java/oakbot/listener/MentionListener.java: -------------------------------------------------------------------------------- 1 | package oakbot.listener; 2 | 3 | import static oakbot.bot.ChatActions.doNothing; 4 | import static oakbot.bot.ChatActions.post; 5 | import static oakbot.bot.ChatActions.reply; 6 | 7 | import java.time.Duration; 8 | import java.time.Instant; 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | import com.github.mangstadt.sochat4j.ChatMessage; 13 | 14 | import oakbot.bot.ChatActions; 15 | import oakbot.bot.IBot; 16 | import oakbot.command.HelpDoc; 17 | import oakbot.util.ChatBuilder; 18 | 19 | /** 20 | * Responds when a user mentions the bot's name. 21 | * @author Michael Angstadt 22 | */ 23 | public class MentionListener implements CatchAllMentionListener { 24 | private final Duration cooldownTimeBetweenResponses = Duration.ofMinutes(1); 25 | private final Map timeOfLastResponseByRoom = new HashMap<>(); 26 | 27 | private final Map responses; 28 | { 29 | var response = "You're welcome."; 30 | 31 | //@formatter:off 32 | responses = Map.of( 33 | "thank you", response, 34 | "thank u", response, 35 | "thanks", response, 36 | "thx", response, 37 | "ty", response 38 | ); 39 | //@formatter:on 40 | } 41 | 42 | private boolean ignore = false; 43 | 44 | @Override 45 | public String name() { 46 | return "mention"; 47 | } 48 | 49 | @Override 50 | public HelpDoc help() { 51 | //@formatter:off 52 | return new HelpDoc.Builder(this) 53 | .summary("Sends a reply message when someone mentions the bot's name.") 54 | .build(); 55 | //@formatter:on 56 | } 57 | 58 | @Override 59 | public ChatActions onMessage(ChatMessage message, IBot bot) { 60 | if (ignore) { 61 | ignore = false; 62 | return doNothing(); 63 | } 64 | 65 | if (!message.getContent().isMentioned(bot.getUsername())) { 66 | return doNothing(); 67 | } 68 | 69 | var prevResponse = timeOfLastResponseByRoom.get(message.getRoomId()); 70 | var now = Instant.now(); 71 | if (prevResponse != null) { 72 | var elapsed = Duration.between(prevResponse, now); 73 | if (elapsed.compareTo(cooldownTimeBetweenResponses) < 0) { 74 | return doNothing(); 75 | } 76 | } 77 | 78 | timeOfLastResponseByRoom.put(message.getRoomId(), now); 79 | 80 | var response = respond(message.getContent().getContent()); 81 | if (response != null) { 82 | return reply(response, message); 83 | } 84 | 85 | //@formatter:off 86 | return post(new ChatBuilder() 87 | .reply(message) 88 | .append("Type ").code().append(bot.getTrigger()).append("help").code().append(" to see all my commands.") 89 | ); 90 | //@formatter:on 91 | } 92 | 93 | @Override 94 | public void ignoreNextMessage() { 95 | ignore = true; 96 | } 97 | 98 | private String respond(String content) { 99 | //@formatter:off 100 | var strippedContent = content 101 | .replaceAll("@\\w+", "") //remove mentions 102 | .replaceAll("[^a-zA-Z ]", "") //remove everything but letters and spaces 103 | .replaceAll("\\s{2,}", " ") //remove duplicate spaces 104 | .trim() 105 | .toLowerCase(); 106 | //@formatter:on 107 | 108 | return responses.get(strippedContent); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/main/java/oakbot/listener/chatgpt/MoodCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.listener.chatgpt; 2 | 3 | import static oakbot.bot.ChatActions.reply; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | import oakbot.Database; 9 | import oakbot.bot.ChatActions; 10 | import oakbot.bot.ChatCommand; 11 | import oakbot.bot.IBot; 12 | import oakbot.command.Command; 13 | import oakbot.command.HelpDoc; 14 | 15 | /** 16 | * Allows users to change the bot's "mood" for ChatGPT interactions. 17 | * @author Michael Angstadt 18 | */ 19 | public class MoodCommand implements Command { 20 | private static final String MOODS_KEY = "chatgpt.moods"; 21 | 22 | private final Database db; 23 | private final String defaultMood; 24 | private final Map moodsByRoom; 25 | 26 | public MoodCommand(Database db, String defaultMood) { 27 | this.db = db; 28 | this.defaultMood = defaultMood; 29 | moodsByRoom = loadMoods(); 30 | } 31 | 32 | @Override 33 | public String name() { 34 | return "mood"; 35 | } 36 | 37 | @Override 38 | public HelpDoc help() { 39 | //@formatter:off 40 | return new HelpDoc.Builder(this) 41 | .summary("Set's the bot's \"mood\" for ChatGPT interactions. One word adjectives only.") 42 | .detail("Moods are defined per-room.") 43 | .example("grumpy", "Makes the bot grumpy.") 44 | .build(); 45 | //@formatter:on 46 | } 47 | 48 | @Override 49 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 50 | var roomId = chatCommand.getMessage().getRoomId(); 51 | var content = chatCommand.getContent(); 52 | 53 | if (content.isEmpty()) { 54 | var currentMood = getMood(roomId); 55 | return reply("I'm feeling a bit " + currentMood + ".", chatCommand); 56 | } 57 | 58 | if (content.indexOf(' ') >= 0) { 59 | return reply("Enter a one-word adjective to set my mood (e.g. happy, grumpy, nostalgic, etc).", chatCommand); 60 | } 61 | 62 | moodsByRoom.put(roomId, content); 63 | saveMoods(); 64 | 65 | return reply("I am now " + content + ". :D", chatCommand); 66 | } 67 | 68 | public String getMood(int roomId) { 69 | return moodsByRoom.getOrDefault(roomId, defaultMood); 70 | } 71 | 72 | /** 73 | * @return a mutable map containing the moods 74 | */ 75 | private Map loadMoods() { 76 | var map = db.getMap(MOODS_KEY); 77 | if (map == null) { 78 | return new HashMap<>(); 79 | } 80 | 81 | var moods = new HashMap(); 82 | 83 | for (var entry : map.entrySet()) { 84 | Integer roomId = Integer.valueOf(entry.getKey()); 85 | String mood = (String) entry.getValue(); 86 | moods.put(roomId, mood); 87 | } 88 | 89 | return moods; 90 | } 91 | 92 | private void saveMoods() { 93 | var map = new HashMap<>(); 94 | 95 | for (Map.Entry entry : moodsByRoom.entrySet()) { 96 | String key = Integer.toString(entry.getKey()); 97 | Object value = entry.getValue(); 98 | map.put(key, value); 99 | } 100 | 101 | db.set(MOODS_KEY, map); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/oakbot/listener/chatgpt/PromptCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.listener.chatgpt; 2 | 3 | import static oakbot.bot.ChatActions.reply; 4 | 5 | import oakbot.bot.ChatActions; 6 | import oakbot.bot.ChatCommand; 7 | import oakbot.bot.IBot; 8 | import oakbot.command.Command; 9 | import oakbot.command.HelpDoc; 10 | 11 | /** 12 | * Displays the room's ChatGPT prompt. 13 | * @author Michael Angstadt 14 | */ 15 | public class PromptCommand implements Command { 16 | private final ChatGPT chatGpt; 17 | 18 | public PromptCommand(ChatGPT chatGpt) { 19 | this.chatGpt = chatGpt; 20 | } 21 | 22 | @Override 23 | public String name() { 24 | return "prompt"; 25 | } 26 | 27 | @Override 28 | public HelpDoc help() { 29 | //@formatter:off 30 | return new HelpDoc.Builder(this) 31 | .summary("Displays the room's ChatGPT prompt.") 32 | .build(); 33 | //@formatter:on 34 | } 35 | 36 | @Override 37 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 38 | var roomId = chatCommand.getMessage().getRoomId(); 39 | var prompt = chatGpt.buildPrompt(roomId, bot); 40 | return reply(prompt, chatCommand); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/oakbot/listener/chatgpt/QuotaCommand.java: -------------------------------------------------------------------------------- 1 | package oakbot.listener.chatgpt; 2 | 3 | import static oakbot.bot.ChatActions.post; 4 | import static oakbot.util.StringUtils.plural; 5 | 6 | import oakbot.bot.ChatActions; 7 | import oakbot.bot.ChatCommand; 8 | import oakbot.bot.IBot; 9 | import oakbot.command.Command; 10 | import oakbot.command.HelpDoc; 11 | import oakbot.util.ChatBuilder; 12 | 13 | /** 14 | * Displays the user's usage quota for rate-limited functions. 15 | * @author Michael Angstadt 16 | */ 17 | public class QuotaCommand implements Command { 18 | private final ChatGPT chatGpt; 19 | private final ImagineCommand imagine; 20 | 21 | public QuotaCommand(ChatGPT chatGpt, ImagineCommand imagine) { 22 | this.chatGpt = chatGpt; 23 | this.imagine = imagine; 24 | } 25 | 26 | @Override 27 | public String name() { 28 | return "quota"; 29 | } 30 | 31 | @Override 32 | public HelpDoc help() { 33 | //@formatter:off 34 | return new HelpDoc.Builder(this) 35 | .summary("Displays the invoking user's usage quota for rate-limited functions.") 36 | .build(); 37 | //@formatter:on 38 | } 39 | 40 | @Override 41 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 42 | var userId = chatCommand.getMessage().getUserId(); 43 | 44 | var cb = new ChatBuilder().reply(chatCommand); 45 | printQuota("Conversation (ChatGPT)", chatGpt.getUsageQuota(), userId, cb); 46 | printQuota("Image generation", imagine.getUsageQuota(), userId, cb); 47 | 48 | return post(cb); 49 | } 50 | 51 | private void printQuota(String label, UsageQuota quota, int userId, ChatBuilder cb) { 52 | cb.append(label).append(": "); 53 | 54 | var max = quota.getRequestsPerPeriod(); 55 | if (max == 0) { 56 | cb.append("no limit").nl(); 57 | return; 58 | } 59 | 60 | var used = quota.getCurrent(userId); 61 | cb.append(used).append(" / ").append(max); 62 | 63 | if (used >= max) { 64 | var timeUntilNextRequest = quota.getTimeUntilUserCanMakeRequest(userId); 65 | var hours = timeUntilNextRequest.toHours() + 1; 66 | cb.append("; available in ").append(hours).append(plural(" hour", hours)); 67 | } 68 | 69 | var period = quota.getPeriod(); 70 | cb.append(" (period = ").append(period.toString()).append(")").nl(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/oakbot/task/FOTD.java: -------------------------------------------------------------------------------- 1 | package oakbot.task; 2 | 3 | import java.time.temporal.ChronoUnit; 4 | import java.util.regex.Pattern; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import com.github.mangstadt.sochat4j.SplitStrategy; 10 | 11 | import oakbot.bot.IBot; 12 | import oakbot.bot.PostMessage; 13 | import oakbot.command.HelpDoc; 14 | import oakbot.util.ChatBuilder; 15 | import oakbot.util.HttpFactory; 16 | import oakbot.util.Now; 17 | 18 | /** 19 | * Posts a fact once per day at noon. 20 | * @author Michael Angstadt 21 | */ 22 | public class FOTD implements ScheduledTask { 23 | private static final Logger logger = LoggerFactory.getLogger(FOTD.class); 24 | private static final String URL = "http://www.refdesk.com"; 25 | private static final String ARCHIVE_URL = URL + "/fotd-arch.html"; 26 | 27 | @Override 28 | public String name() { 29 | return "fotd"; 30 | } 31 | 32 | @Override 33 | public HelpDoc help() { 34 | //@formatter:off 35 | return new HelpDoc.Builder(this) 36 | .summary("Posts a fact every day.") 37 | .detail("Facts are from refdesk.com. Fact is posted at 12:00 server time to all non-quiet rooms.") 38 | .build(); 39 | //@formatter:on 40 | } 41 | 42 | @Override 43 | public long nextRun() { 44 | var now = Now.local(); 45 | var next = now.truncatedTo(ChronoUnit.DAYS).withHour(12); 46 | if (now.getHour() >= 12) { 47 | next = next.plusDays(1); 48 | } 49 | return now.until(next, ChronoUnit.MILLIS); 50 | } 51 | 52 | @Override 53 | public void run(IBot bot) throws Exception { 54 | String response; 55 | try (var http = HttpFactory.connect()) { 56 | response = http.get(URL).getBody(); 57 | } 58 | 59 | var fact = parseFact(response); 60 | if (fact == null) { 61 | logger.atWarn().log(() -> "Unable to parse FOTD from " + URL + "."); 62 | return; 63 | } 64 | 65 | fact = ChatBuilder.toMarkdown(fact, false, true, URL); 66 | var cb = new ChatBuilder(fact); 67 | 68 | var isMultiline = fact.contains("\n"); 69 | if (isMultiline) { 70 | cb.nl().append("Source: " + ARCHIVE_URL); 71 | } else { 72 | cb.append(' ').link("(source)", ARCHIVE_URL); 73 | } 74 | 75 | var postMessage = new PostMessage(cb).splitStrategy(SplitStrategy.WORD); 76 | bot.broadcastMessage(postMessage); 77 | } 78 | 79 | private String parseFact(String html) { 80 | var p = Pattern.compile("(.*?)Provided\\s*by", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); 81 | var m = p.matcher(html); 82 | if (!m.find()) { 83 | return null; 84 | } 85 | 86 | var fact = m.group(1); 87 | 88 | /* 89 | * Trim spaces and dashes from the end of the string (in the past, 90 | * there used to be a dash before "provided by"). 91 | */ 92 | for (var i = fact.length() - 1; i >= 0; i--) { 93 | var c = fact.charAt(i); 94 | if (Character.isWhitespace(c) || c == '-') { 95 | continue; 96 | } 97 | 98 | fact = fact.substring(0, i + 1); 99 | break; 100 | } 101 | 102 | //trim whitespace from the beginning of the string 103 | fact = fact.trim(); 104 | 105 | //fix single quote characters 106 | fact = fact.replace("�", "'"); 107 | 108 | return fact; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/main/java/oakbot/task/LinuxHealthMonitor.java: -------------------------------------------------------------------------------- 1 | package oakbot.task; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStreamReader; 5 | import java.util.List; 6 | 7 | /** 8 | * Monitors the health of a Linux server. 9 | * @author Michael Angstadt 10 | */ 11 | public class LinuxHealthMonitor extends HealthMonitor { 12 | private final String aptCheckPath; 13 | 14 | /** 15 | * @param roomIds the rooms to post the messages to 16 | * @param aptCheckPath the file system path to the "apt-check" command 17 | */ 18 | public LinuxHealthMonitor(List roomIds, String aptCheckPath) { 19 | super(roomIds); 20 | this.aptCheckPath = aptCheckPath; 21 | } 22 | 23 | @Override 24 | public int getNumSecurityUpdates() throws Exception { 25 | /* 26 | * The apt-check command returns output in the following format: 27 | * 28 | * NUM_TOTAL_UPDATES;NUM_SECURITY_UPDATES 29 | * 30 | * For example, the output "128;68" means there are 128 updates, 68 of 31 | * which are considered to be security updates. 32 | */ 33 | 34 | /* 35 | * For some reason, the command output is sent to the error stream, so 36 | * redirect all error output to the standard stream. 37 | */ 38 | var process = new ProcessBuilder(aptCheckPath).redirectErrorStream(true).start(); 39 | 40 | String line; 41 | try (var reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { 42 | line = reader.readLine(); 43 | } 44 | 45 | var split = line.split(";"); 46 | return Integer.parseInt(split[1]); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/oakbot/task/QOTD.java: -------------------------------------------------------------------------------- 1 | package oakbot.task; 2 | 3 | import java.io.IOException; 4 | import java.time.temporal.ChronoUnit; 5 | 6 | import org.jsoup.nodes.Document; 7 | 8 | import com.fasterxml.jackson.databind.JsonNode; 9 | import com.github.mangstadt.sochat4j.SplitStrategy; 10 | 11 | import oakbot.bot.IBot; 12 | import oakbot.bot.PostMessage; 13 | import oakbot.command.HelpDoc; 14 | import oakbot.util.ChatBuilder; 15 | import oakbot.util.HttpFactory; 16 | import oakbot.util.Now; 17 | 18 | /** 19 | * Posts a quote once per day at midnight. 20 | * @author Michael Angstadt 21 | */ 22 | public class QOTD implements ScheduledTask { 23 | @Override 24 | public String name() { 25 | return "qotd"; 26 | } 27 | 28 | @Override 29 | public HelpDoc help() { 30 | //@formatter:off 31 | return new HelpDoc.Builder(this) 32 | .summary("Posts a quote every day.") 33 | .detail("Quotes are from slashdot.org. Quote is posted at 0:00 server time to all non-quiet rooms.") 34 | .build(); 35 | //@formatter:on 36 | } 37 | 38 | @Override 39 | public long nextRun() { 40 | var now = Now.local(); 41 | var tomorrow = now.truncatedTo(ChronoUnit.DAYS).plusDays(1); 42 | return now.until(tomorrow, ChronoUnit.MILLIS); 43 | } 44 | 45 | @Override 46 | public void run(IBot bot) throws Exception { 47 | var cb = fromSlashdot(); 48 | bot.broadcastMessage(new PostMessage(cb).splitStrategy(SplitStrategy.WORD)); 49 | } 50 | 51 | ChatBuilder fromSlashdot() throws IOException { 52 | Document document; 53 | try (var http = HttpFactory.connect()) { 54 | document = http.get("https://slashdot.org").getBodyAsHtml(); 55 | } 56 | 57 | var element = document.selectFirst("blockquote[cite='https://slashdot.org'] p"); 58 | 59 | return new ChatBuilder() //@formatter:off 60 | .append(element.text()) 61 | .append(" (").link("source", "https://slashdot.org").append(")"); //@formatter:on 62 | } 63 | 64 | ChatBuilder fromTheySaidSo() throws IOException { 65 | JsonNode json; 66 | try (var http = HttpFactory.connect()) { 67 | json = http.get("http://quotes.rest/qod.json").getBodyAsJson(); 68 | } 69 | 70 | var quoteNode = json.get("contents").get("quotes").get(0); 71 | 72 | var quote = quoteNode.get("quote").asText(); 73 | var author = quoteNode.get("author").asText(); 74 | 75 | var node = quoteNode.get("permalink"); 76 | var permalink = (node == null) ? "https://theysaidso.com" : node.asText(); 77 | 78 | var cb = new ChatBuilder(); 79 | var quoteHasNewlines = (quote.indexOf('\n') >= 0); 80 | if (quoteHasNewlines) { 81 | cb.append(quote).nl(); 82 | cb.append('-').append(author); 83 | cb.append(" (source: ").append(permalink).append(')'); 84 | } else { 85 | cb.italic().append('"').append(quote).append('"').italic(); 86 | cb.append(" -").append(author); 87 | cb.append(' ').link("(source)", permalink); 88 | } 89 | return cb; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/oakbot/task/ScheduledTask.java: -------------------------------------------------------------------------------- 1 | package oakbot.task; 2 | 3 | import oakbot.bot.IBot; 4 | import oakbot.command.HelpDoc; 5 | 6 | /** 7 | * Represents a task that runs on a regular basis. 8 | * @author Michael Angstadt 9 | */ 10 | public interface ScheduledTask { 11 | /** 12 | * Runs the task. If an exception is thrown, the exception is logged and the 13 | * task is scheduled to run again. 14 | * @param bot the bot instance 15 | * @throws Exception if anything bad happens 16 | */ 17 | void run(IBot bot) throws Exception; 18 | 19 | /** 20 | * Determines how long to wait before running the task again. 21 | * @return the wait time (in milliseconds) or zero to stop running the task 22 | */ 23 | long nextRun(); 24 | 25 | /** 26 | * Gets the task's name to display in the help documentation. 27 | * @return the name or null not to display this task in the help 28 | * documentation 29 | */ 30 | default String name() { 31 | return null; 32 | } 33 | 34 | /** 35 | * Gets the task's help documentation. 36 | * @return the help documentation or null if this task does not have any 37 | * help documentation 38 | */ 39 | default HelpDoc help() { 40 | return null; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/oakbot/util/CharIterator.java: -------------------------------------------------------------------------------- 1 | package oakbot.util; 2 | 3 | /** 4 | * Iterates over the characters in a String. Provides additional functionality 5 | * over {@link String#chars}. 6 | * @author Michael Angstadt 7 | */ 8 | public class CharIterator { 9 | private final String s; 10 | private int i = -1; 11 | 12 | /** 13 | * @param s the string to iterate over 14 | */ 15 | public CharIterator(String s) { 16 | this.s = s; 17 | } 18 | 19 | /** 20 | * Determines if there are more characters to iterate over. 21 | * @return true if there are more characters, false if not 22 | */ 23 | public boolean hasNext() { 24 | return i + 1 < s.length(); 25 | } 26 | 27 | /** 28 | * Advances to the next character. 29 | * @return the next character 30 | */ 31 | public char next() { 32 | return s.charAt(++i); 33 | } 34 | 35 | /** 36 | * Gets the previous character. 37 | * @return the previous character or 0 if the iterator is at the beginning 38 | * of the string 39 | */ 40 | public char prev() { 41 | return (i <= 0) ? 0 : s.charAt(i - 1); 42 | } 43 | 44 | /** 45 | * Gets the index of the current character in the string. 46 | * @return the index 47 | */ 48 | public int index() { 49 | return i; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/oakbot/util/HttpFactory.java: -------------------------------------------------------------------------------- 1 | package oakbot.util; 2 | 3 | import org.apache.http.client.CookieStore; 4 | import org.apache.http.impl.client.CloseableHttpClient; 5 | import org.apache.http.impl.client.HttpClientBuilder; 6 | import org.apache.http.impl.client.HttpClients; 7 | 8 | import com.github.mangstadt.sochat4j.util.Http; 9 | 10 | import okhttp3.OkHttpClient; 11 | 12 | /** 13 | * Use this class when you want to send normal HTTP requests in production, but 14 | * want to inject a mock HTTP client during unit testing. 15 | * @author Michael Angstadt 16 | */ 17 | public class HttpFactory { 18 | private static final OkHttpClient okHttpClient = new OkHttpClient(); 19 | 20 | private static CloseableHttpClient mock; 21 | 22 | /** 23 | * Injects a mock HTTP client for unit testing. 24 | * @param mock the mock client 25 | */ 26 | public static void inject(CloseableHttpClient mock) { 27 | HttpFactory.mock = mock; 28 | } 29 | 30 | /** 31 | * Creates an HTTP client or returns a mock client injected using 32 | * {@link #inject}. 33 | * @return the HTTP client 34 | */ 35 | public static Http connect() { 36 | var client = (mock == null) ? HttpClients.createDefault() : mock; 37 | return new Http(client); 38 | } 39 | 40 | /** 41 | * Creates an HTTP client or returns a mock client injected using 42 | * {@link #inject}. 43 | * @param builder the client builder object 44 | * @return the HTTP client 45 | */ 46 | public static Http connect(HttpClientBuilder builder) { 47 | var client = (mock == null) ? builder.build() : mock; 48 | return new Http(client); 49 | } 50 | 51 | /** 52 | * Creates an HTTP client or returns a mock client injected using 53 | * {@link #inject}. 54 | * @param cookieStore the cookies to use 55 | * @return the HTTP client 56 | */ 57 | public static Http connect(CookieStore cookieStore) { 58 | var client = (mock == null) ? HttpClients.custom().setDefaultCookieStore(cookieStore).build() : mock; 59 | return new Http(client); 60 | } 61 | 62 | /** 63 | * Returns the shared OkHttpClient instance. Only a single instance should 64 | * be created for performance reasons. 65 | * @return the client instance 66 | */ 67 | public static OkHttpClient okHttp() { 68 | return okHttpClient; 69 | } 70 | 71 | /** 72 | * Removes the mock HTTP client, if present. 73 | */ 74 | public static void restore() { 75 | mock = null; 76 | } 77 | 78 | private HttpFactory() { 79 | //hide constructor 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/oakbot/util/HttpRequestLogger.java: -------------------------------------------------------------------------------- 1 | package oakbot.util; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | import java.nio.file.StandardOpenOption; 8 | import java.time.ZoneId; 9 | import java.time.format.DateTimeFormatter; 10 | 11 | import au.com.bytecode.opencsv.CSVWriter; 12 | 13 | /** 14 | * Logs HTTP requests and responses to a CSV file. 15 | * @author Michael Angstadt 16 | */ 17 | public class HttpRequestLogger { 18 | private final CSVWriter writer; 19 | private final DateTimeFormatter dtFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.of("America/New_York")); 20 | 21 | /** 22 | * @param path the path to the CSV file (will append onto the file) 23 | * @throws IOException if there is a problem creating the file 24 | */ 25 | public HttpRequestLogger(String path) throws IOException { 26 | this(Paths.get(path)); 27 | } 28 | 29 | /** 30 | * @param path the path to the CSV file (will append onto the file) 31 | * @throws IOException if there is a problem creating the file 32 | */ 33 | public HttpRequestLogger(Path path) throws IOException { 34 | var writeHeaders = !Files.exists(path); 35 | 36 | writer = new CSVWriter(Files.newBufferedWriter(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND)); 37 | 38 | if (writeHeaders) { 39 | writer.writeNext(new String[] { "Timestamp", "Request", "Response" }); 40 | writer.flush(); 41 | } 42 | } 43 | 44 | /** 45 | * Logs a request/response. 46 | * @param requestMethod the request method (e.g. "POST") 47 | * @param requestUrl the request URL 48 | * @param requestBody the request body 49 | * @param responseStatusCode the response status code (e.g. "200") 50 | * @param responseBody the response body 51 | * @throws IOException if there was a problem writing to the file 52 | */ 53 | public void log(String requestMethod, String requestUrl, String requestBody, int responseStatusCode, String responseBody) throws IOException { 54 | var timestamp = Now.local().format(dtFormatter); 55 | var request = "HTTP " + requestMethod + " " + requestUrl + "\n" + requestBody; 56 | var response = "HTTP " + responseStatusCode + "\n" + responseBody; 57 | 58 | var line = new String[] { timestamp, request, response }; 59 | synchronized (this) { 60 | writer.writeNext(line); 61 | writer.flush(); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/oakbot/util/ImageUtils.java: -------------------------------------------------------------------------------- 1 | package oakbot.util; 2 | 3 | import java.awt.image.BufferedImage; 4 | import java.io.ByteArrayInputStream; 5 | import java.io.ByteArrayOutputStream; 6 | import java.io.IOException; 7 | 8 | import javax.imageio.ImageIO; 9 | 10 | /** 11 | * @author Michael Angstadt 12 | */ 13 | public class ImageUtils { 14 | /** 15 | * Converts the given image data to PNG format. 16 | * @param data the image data 17 | * @return the PNG image 18 | * @throws IOException if there is a problem converting the image 19 | */ 20 | public static byte[] convertToPng(byte[] data) throws IOException { 21 | BufferedImage image; 22 | try (var in = new ByteArrayInputStream(data)) { 23 | image = ImageIO.read(in); 24 | } 25 | if (image == null) { 26 | return null; 27 | } 28 | 29 | try (var out = new ByteArrayOutputStream()) { 30 | ImageIO.write(image, "PNG", out); 31 | return out.toByteArray(); 32 | } 33 | } 34 | 35 | /** 36 | * Removes the alpha channel from the image, if present. 37 | * @param image the image 38 | * @return the image with alpha channel removed 39 | * @see "https://stackoverflow.com/a/72135983/13379" 40 | */ 41 | public static BufferedImage removeAlphaChannel(BufferedImage image) { 42 | if (!image.getColorModel().hasAlpha()) { 43 | return image; 44 | } 45 | 46 | var target = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); 47 | 48 | var g = target.createGraphics(); 49 | g.fillRect(0, 0, image.getWidth(), image.getHeight()); 50 | g.drawImage(image, 0, 0, null); 51 | g.dispose(); 52 | 53 | return target; 54 | } 55 | 56 | private ImageUtils() { 57 | //hide 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/oakbot/util/Now.java: -------------------------------------------------------------------------------- 1 | package oakbot.util; 2 | 3 | import java.time.Duration; 4 | import java.time.Instant; 5 | import java.time.LocalDateTime; 6 | 7 | /** 8 | * Use this class for when you want to call {@link Instant#now} or 9 | * {@link LocalDateTime#now} in production, but want to change what these 10 | * methods return during unit testing. 11 | * @author Michael Angstadt 12 | */ 13 | public class Now { 14 | private static Duration offset; 15 | 16 | /** 17 | * Gets the current time. 18 | * @return the current time 19 | */ 20 | public static Instant instant() { 21 | var now = Instant.now(); 22 | return (offset == null) ? now : now.plus(offset); 23 | } 24 | 25 | /** 26 | * Gets the current time. 27 | * @return the current time 28 | */ 29 | public static LocalDateTime local() { 30 | var now = LocalDateTime.now(); 31 | return (offset == null) ? now : now.plus(offset); 32 | } 33 | 34 | /** 35 | * Sets the current time. All future invocations of {@link #instant} and 36 | * {@link local} will be relative to this time. 37 | * @param ts the current time 38 | */ 39 | public static void setNow(LocalDateTime ts) { 40 | offset = Duration.between(LocalDateTime.now(), ts); 41 | } 42 | 43 | /** 44 | * Increase the current time. 45 | * @param d the amount to increase the current time by 46 | */ 47 | public static void fastForward(Duration d) { 48 | offset = (offset == null) ? d : offset.plus(d); 49 | } 50 | 51 | /** 52 | * Disables the offset and restores to present time. 53 | */ 54 | public static void restore() { 55 | offset = null; 56 | } 57 | 58 | private Now() { 59 | //hide constructor 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/oakbot/util/RelativeDateFormat.java: -------------------------------------------------------------------------------- 1 | package oakbot.util; 2 | 3 | import java.time.Duration; 4 | import java.time.LocalDateTime; 5 | import java.time.format.DateTimeFormatter; 6 | import java.time.format.FormatStyle; 7 | 8 | /** 9 | * Formats dates relative to the current time. 10 | * @author Michael Angstadt 11 | */ 12 | public class RelativeDateFormat { 13 | private final DateTimeFormatter timeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT); 14 | 15 | /** 16 | * Formats a date 17 | * @param date the date or format 18 | * @return the formatted date (e.g. "Today at 1:00 PM") 19 | */ 20 | public String format(LocalDateTime date) { 21 | var now = LocalDateTime.now(); 22 | var diff = Duration.between(date, now); 23 | 24 | if (diff.toMinutes() < 1) { 25 | return "A moment ago"; 26 | } 27 | 28 | if (diff.toHours() < 1) { 29 | return diff.toMinutes() + " minutes ago"; 30 | } 31 | 32 | var dayDiff = diff.toDays(); 33 | if (dayDiff == 0) { 34 | return "Today at " + timeFormatter.format(date); 35 | } 36 | if (dayDiff == 1) { 37 | return "Yesterday at " + timeFormatter.format(date); 38 | } 39 | if (dayDiff < 7) { 40 | return "About " + dayDiff + " days ago."; 41 | } 42 | if (dayDiff < 14) { 43 | return "Over a week ago."; 44 | } 45 | if (dayDiff < 30) { 46 | return "Over " + (dayDiff / 7) + " weeks ago."; 47 | } 48 | if (dayDiff < 60) { 49 | return "Over a month ago."; 50 | } 51 | return "Over " + (dayDiff / 30) + " months ago."; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/oakbot/util/Rng.java: -------------------------------------------------------------------------------- 1 | package oakbot.util; 2 | 3 | import java.util.List; 4 | import java.util.Random; 5 | 6 | /** 7 | * Allows random values to be injected during unit tests. 8 | * @author Michael Angstadt 9 | */ 10 | public class Rng { 11 | private static final Random instance = new Random(); 12 | private static Random random = instance; 13 | 14 | /** 15 | * Injects a mock {@link Random} instance. 16 | * @param mock the mock instance 17 | */ 18 | public static void inject(Random mock) { 19 | random = mock; 20 | } 21 | 22 | /** 23 | * Gets a random integer value between zero and a given number. 24 | * @param endExclusive end range exclusive 25 | * @return the random value 26 | */ 27 | public static int next(int endExclusive) { 28 | return next(0, endExclusive); 29 | } 30 | 31 | /** 32 | * Gets a random integer value. 33 | * @param startInclusive start range inclusive 34 | * @param endExclusive end range exclusive 35 | * @return the random value 36 | */ 37 | public static int next(int startInclusive, int endExclusive) { 38 | if (startInclusive == endExclusive) { 39 | return startInclusive; 40 | } 41 | 42 | return random.nextInt(startInclusive, endExclusive); 43 | } 44 | 45 | /** 46 | * Chooses a random element from a list. 47 | * @param list the list 48 | * @return the random element 49 | */ 50 | public static T random(List list) { 51 | var i = next(list.size()); 52 | return list.get(i); 53 | } 54 | 55 | /** 56 | * Chooses a random element from an array. 57 | * @param array the array 58 | * @return the random element 59 | */ 60 | @SafeVarargs 61 | public static T random(T ... array) { 62 | var i = next(array.length); 63 | return array[i]; 64 | } 65 | 66 | /** 67 | * Gets a random double in range [0.0, 1.0). 68 | * @return a random double 69 | */ 70 | public static double next() { 71 | return random.nextDouble(); 72 | } 73 | 74 | /** 75 | * Removes the mock instance that was set with {@link #inject}. 76 | */ 77 | public static void restore() { 78 | random = instance; 79 | } 80 | 81 | /** 82 | * Gets the {@link Random} instance. 83 | * @return the random instance 84 | */ 85 | public static Random get() { 86 | return random; 87 | } 88 | 89 | private Rng() { 90 | //hide 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/oakbot/util/StringUtils.java: -------------------------------------------------------------------------------- 1 | package oakbot.util; 2 | 3 | import java.util.regex.Pattern; 4 | 5 | /** 6 | * Contains miscellaneous string utility methods. 7 | * @author Michael Angstadt 8 | */ 9 | public interface StringUtils { 10 | /** 11 | * Determines if a word should be plural. 12 | * @param word the singular version of the word 13 | * @param number the number 14 | * @return the plural or singular version of the word, depending on the 15 | * provided number 16 | */ 17 | public static String plural(String word, long number) { 18 | if (number == 1) { 19 | return word; 20 | } 21 | 22 | return word + (word.endsWith("s") ? "es" : "s"); 23 | } 24 | 25 | /** 26 | * Generates the possessive form of the given word. 27 | * @param word the word (e.g. "cats") 28 | * @return the possessive form (e.g. "cats'") 29 | */ 30 | public static String possessive(String word) { 31 | return word + (word.endsWith("s") ? "'" : "'s"); 32 | } 33 | 34 | /** 35 | * Counts the number of words in a given string. 36 | * @param phrase the string 37 | * @return the number of words 38 | */ 39 | public static int countWords(String phrase) { 40 | phrase = phrase.trim(); 41 | if (phrase.isEmpty()) { 42 | return 0; 43 | } 44 | 45 | var p = Pattern.compile("\\s+"); 46 | var m = p.matcher(phrase); 47 | return (int) m.results().count() + 1; 48 | } 49 | 50 | /** 51 | * Returns "a" or "an", depending on what the first letter of the given word 52 | * is. 53 | * @param word the word 54 | * @return "an" if the first letter is a vowel, "a" otherwise 55 | */ 56 | public static String a(String word) { 57 | if (word.isEmpty()) { 58 | return "a"; 59 | } 60 | 61 | var first = Character.toLowerCase(word.charAt(0)); 62 | var vowel = ("aeiou".indexOf(first) >= 0); 63 | 64 | return vowel ? "an" : "a"; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/resources/info.properties: -------------------------------------------------------------------------------- 1 | version=${version} 2 | url=${url} 3 | built=${built} 4 | -------------------------------------------------------------------------------- /src/test/java/oakbot/bot/ChatActionsUtils.java: -------------------------------------------------------------------------------- 1 | package oakbot.bot; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | /** 7 | * Contains utility methods for asserting the contents of a {@link ChatActions} 8 | * object. 9 | * @author Michael Angstadt 10 | */ 11 | public class ChatActionsUtils { 12 | /** 13 | * Asserts the contents of a {@link ChatActions} object that contains only a 14 | * single {@link PostMessage} action. 15 | * @param expected the expected message 16 | * @param actions the actions 17 | */ 18 | public static void assertMessage(String expected, ChatActions actions) { 19 | var actual = getFirstPostMessage(actions); 20 | assertEquals(expected, actual.message()); 21 | } 22 | 23 | /** 24 | * Asserts the contents of a {@link ChatActions} object that contains only a 25 | * single {@link PostMessage} action. 26 | * @param expected the text that the message should start with 27 | * @param actions the actions 28 | */ 29 | public static void assertMessageStartsWith(String expected, ChatActions actions) { 30 | var actual = getFirstPostMessage(actions); 31 | assertTrue(actual.message().startsWith(expected)); 32 | } 33 | 34 | /** 35 | * Asserts the contents of a {@link ChatActions} object that contains only a 36 | * single {@link PostMessage} action. 37 | * @param expected the expected object 38 | * @param actions the actions 39 | */ 40 | public static void assertPostMessage(PostMessage expected, ChatActions actions) { 41 | var actual = getFirstPostMessage(actions); 42 | assertEquals(expected, actual); 43 | } 44 | 45 | private static PostMessage getFirstPostMessage(ChatActions actions) { 46 | assertEquals(1, actions.getActions().size(), () -> "ChatActions object is empty or contains more than one action."); 47 | return (PostMessage) actions.getActions().get(0); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/oakbot/bot/JsonDatabaseTest.java: -------------------------------------------------------------------------------- 1 | package oakbot.bot; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertNull; 5 | 6 | import java.nio.file.Files; 7 | import java.nio.file.Path; 8 | import java.time.LocalDateTime; 9 | import java.time.format.DateTimeFormatter; 10 | import java.util.Arrays; 11 | import java.util.HashMap; 12 | import java.util.List; 13 | import java.util.Map; 14 | 15 | import org.junit.jupiter.api.Test; 16 | import org.junit.jupiter.api.io.TempDir; 17 | 18 | import oakbot.JsonDatabase; 19 | 20 | /** 21 | * @author Michael Angstadt 22 | */ 23 | class JsonDatabaseTest { 24 | @TempDir 25 | private Path tempDir; 26 | 27 | @Test 28 | void round_trip() throws Exception { 29 | var file = Files.createTempFile(tempDir, "temp", ".json"); 30 | Files.delete(file); 31 | 32 | Map map = new HashMap<>(); 33 | { 34 | map.put("one", "One"); 35 | map.put("two", "Two"); 36 | map.put("three", 3); 37 | 38 | Map submap = new HashMap<>(); 39 | submap.put("five", "5"); 40 | map.put("four", Arrays.asList(1, "2", null, List.of(3, 4), submap)); 41 | 42 | map.put("five", date("2017-03-26 00:00:00")); 43 | map.put("six", null); 44 | map.put("seven", Integer.MAX_VALUE + 1L); //long value 45 | } 46 | 47 | var list = List.of(1, 2); 48 | var value = "three"; 49 | 50 | var db = new JsonDatabase(file); 51 | db.set("map", map); 52 | db.set("list", list); 53 | db.set("value", value); 54 | db.commit(); 55 | 56 | //System.out.println(new String(Files.readAllBytes(file))); 57 | 58 | db = new JsonDatabase(file); 59 | assertEquals(map, db.get("map")); 60 | assertEquals(list, db.get("list")); 61 | assertEquals(value, db.get("value")); 62 | } 63 | 64 | @Test 65 | void non_existant_key() throws Exception { 66 | var file = Files.createTempFile(tempDir, "temp", ".json"); 67 | Files.delete(file); 68 | 69 | var db = new JsonDatabase(file); 70 | assertNull(db.get("non-existant")); 71 | } 72 | 73 | private static LocalDateTime date(String date) { 74 | var formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); 75 | return LocalDateTime.parse(date, formatter); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/test/java/oakbot/command/CommandTest.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import java.util.List; 7 | 8 | import org.junit.jupiter.api.Test; 9 | 10 | import com.github.mangstadt.sochat4j.ChatMessage; 11 | 12 | import oakbot.bot.ChatActions; 13 | import oakbot.bot.ChatCommand; 14 | import oakbot.bot.IBot; 15 | 16 | /** 17 | * @author Michael Angstadt 18 | */ 19 | class CommandTest { 20 | @Test 21 | void isInvokingMe() { 22 | var command = new Command() { 23 | @Override 24 | public String name() { 25 | return "name"; 26 | } 27 | 28 | @Override 29 | public List aliases() { 30 | return List.of("one", "two"); 31 | } 32 | 33 | @Override 34 | public HelpDoc help() { 35 | return null; 36 | } 37 | 38 | @Override 39 | public ChatActions onMessage(ChatCommand chatCommand, IBot bot) { 40 | return null; 41 | } 42 | }; 43 | 44 | assertIsInvokingMe(command, "/name"); 45 | assertIsInvokingMe(command, "/name foo"); 46 | assertIsInvokingMe(command, "/one"); 47 | assertIsInvokingMe(command, "/one foo"); 48 | assertNotInvokingMe(command, "/three"); 49 | assertNotInvokingMe(command, "blah"); 50 | } 51 | 52 | private static void assertIsInvokingMe(Command command, String content) { 53 | var message = new ChatMessage.Builder().content(content).build(); 54 | assertTrue(command.isInvokingMe(message, "/")); 55 | } 56 | 57 | private static void assertNotInvokingMe(Command command, String content) { 58 | var message = new ChatMessage.Builder().content(content).build(); 59 | assertFalse(command.isInvokingMe(message, "/")); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/test/java/oakbot/command/EchoCommandTest.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActionsUtils.assertMessage; 4 | import static org.mockito.Mockito.mock; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | import oakbot.bot.IBot; 9 | import oakbot.util.ChatCommandBuilder; 10 | 11 | /** 12 | * @author Michael Angstadt 13 | */ 14 | class EchoCommandTest { 15 | @Test 16 | void onMessage() { 17 | assertOnMessage("foo bar", "foo bar"); 18 | assertOnMessage("", ":1 Tell me what to say."); 19 | assertOnMessage("foo bar", "**foo** bar"); 20 | } 21 | 22 | private static void assertOnMessage(String input, String expectedResponse) { 23 | var echo = new EchoCommand(); 24 | 25 | //@formatter:off 26 | var chatCommand = new ChatCommandBuilder(echo) 27 | .messageId(1) 28 | .content(input) 29 | .build(); 30 | //@formatter:on 31 | 32 | var bot = mock(IBot.class); 33 | 34 | var actions = echo.onMessage(chatCommand, bot); 35 | 36 | assertMessage(expectedResponse, actions); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/oakbot/command/WikiCommandTest.java: -------------------------------------------------------------------------------- 1 | package oakbot.command; 2 | 3 | import static oakbot.bot.ChatActionsUtils.assertMessage; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | import oakbot.util.ChatCommandBuilder; 8 | 9 | /** 10 | * @author Michael Angstadt 11 | */ 12 | class WikiCommandTest { 13 | private final WikiCommand command = new WikiCommand(); 14 | 15 | @Test 16 | void empty() { 17 | var message = new ChatCommandBuilder(command).messageId(1).build(); 18 | 19 | var response = command.onMessage(message, null); 20 | assertMessage(":1 Please specify the term you'd like to display.", response); 21 | } 22 | 23 | @Test 24 | void spaces() { 25 | //@formatter:off 26 | var message = new ChatCommandBuilder(command) 27 | .messageId(1) 28 | .content("John Doe") 29 | .build(); 30 | //@formatter:on 31 | 32 | var response = command.onMessage(message, null); 33 | assertMessage("https://en.wikipedia.org/wiki/John_Doe", response); 34 | } 35 | 36 | @Test 37 | void url_safe() { 38 | //@formatter:off 39 | var message = new ChatCommandBuilder(command) 40 | .messageId(1) 41 | .content("I/O") 42 | .build(); 43 | //@formatter:on 44 | 45 | var response = command.onMessage(message, null); 46 | assertMessage("https://en.wikipedia.org/wiki/I%2FO", response); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/test/java/oakbot/command/aoc/AdventOfCodeApiTest.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.aoc; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | import org.junit.jupiter.api.AfterEach; 8 | import org.junit.jupiter.api.Test; 9 | 10 | import oakbot.util.Gobble; 11 | import oakbot.util.HttpFactory; 12 | import oakbot.util.MockHttpClientBuilder; 13 | import oakbot.util.Now; 14 | 15 | /** 16 | * @author Michael Angstadt 17 | */ 18 | class AdventOfCodeApiTest { 19 | @AfterEach 20 | void after() { 21 | Now.restore(); 22 | HttpFactory.restore(); 23 | } 24 | 25 | @Test 26 | void getLeadeboard() throws Exception { 27 | Now.setNow(LocalDateTime.of(2018, 12, 1, 0, 0, 0)); 28 | var aoc2018 = new Gobble(getClass(), "advent-of-code-2018.json").asString(); 29 | 30 | //@formatter:off 31 | HttpFactory.inject(new MockHttpClientBuilder() 32 | .requestGet("http://adventofcode.com/2018/leaderboard/private/view/123456.json") 33 | .responseOk(aoc2018) 34 | .build()); 35 | //@formatter:on 36 | 37 | var api = new AdventOfCodeApi("123456"); 38 | 39 | var players = api.getLeaderboard("123456"); 40 | assertEquals(10, players.size()); 41 | 42 | var owner = players.get(0); 43 | assertEquals(256093, owner.id()); 44 | assertEquals("Mike Angstadt", owner.name()); 45 | assertEquals(18, owner.score()); 46 | assertEquals(2, owner.stars()); 47 | assertEquals(1, owner.completionTimes().size()); 48 | } 49 | 50 | @Test 51 | void getLeadeboardUrl() { 52 | Now.setNow(LocalDateTime.of(2018, 12, 1, 0, 0, 0)); 53 | 54 | var api = new AdventOfCodeApi(""); 55 | assertEquals("http://adventofcode.com/2018/leaderboard/private/view/123456", api.getLeaderboardWebsite("123456")); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/oakbot/command/effective/EffectiveDebuggingCommandTest.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.effective; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.fail; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | /** 9 | * @author Michael Angstadt 10 | */ 11 | class EffectiveDebuggingCommandTest { 12 | private final EffectiveDebuggingCommand command = new EffectiveDebuggingCommand(); 13 | 14 | @Test 15 | void itemNumbers() { 16 | var expected = 1; 17 | for (var item : command.items) { 18 | final var expected2 = expected; 19 | assertEquals(expected, item.number, () -> "Item numbers are not sequential at index " + (expected2 - 1) + "."); 20 | expected++; 21 | } 22 | } 23 | 24 | @Test 25 | void pageNumbers() { 26 | var prevPage = 0; 27 | 28 | for (var item : command.items) { 29 | if (item.page <= 0) { 30 | fail("Invalid page number: " + item.page); 31 | } 32 | 33 | if (item.page < prevPage) { 34 | fail("Page number for item " + item.number + " is less than previous item's page number."); 35 | } 36 | prevPage = item.page; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/oakbot/command/javadoc/JavadocDaoUncachedTest.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.javadoc; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertNull; 5 | import static org.junit.jupiter.api.Assertions.assertTrue; 6 | 7 | import java.nio.file.Path; 8 | import java.nio.file.Paths; 9 | import java.util.HashSet; 10 | import java.util.List; 11 | 12 | import org.junit.jupiter.api.Test; 13 | 14 | /** 15 | * @author Michael Angstadt 16 | */ 17 | class JavadocDaoUncachedTest { 18 | private final Path root = Paths.get("src", "test", "resources", "oakbot", "command", "javadoc"); 19 | private final JavadocDaoUncached dao; 20 | { 21 | dao = new JavadocDaoUncached(root); 22 | } 23 | 24 | @Test 25 | void search_multiple_results() throws Exception { 26 | var actual = new HashSet<>(dao.search("list")); 27 | var expected = new HashSet<>(List.of("java.awt.List", "java.util.List")); 28 | assertEquals(expected, actual); 29 | } 30 | 31 | @Test 32 | void search_single_result() throws Exception { 33 | var actual = new HashSet<>(dao.search("java.awt.list")); 34 | var expected = new HashSet<>(List.of("java.awt.List")); 35 | assertEquals(expected, actual); 36 | } 37 | 38 | @Test 39 | void search_no_results() throws Exception { 40 | var names = dao.search("lsit"); 41 | assertTrue(names.isEmpty()); 42 | } 43 | 44 | @Test 45 | void getClassInfo() throws Exception { 46 | var info = dao.getClassInfo("java.util.List"); 47 | assertEquals("java.util.List", info.getName().getFullyQualifiedName()); 48 | } 49 | 50 | @Test 51 | void getClassInfo_case_sensitive() throws Exception { 52 | var info = dao.getClassInfo("java.util.list"); 53 | assertNull(info); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/test/java/oakbot/command/javadoc/JavadocZipFileTest.java: -------------------------------------------------------------------------------- 1 | package oakbot.command.javadoc; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertNull; 5 | 6 | import java.io.IOException; 7 | import java.net.URISyntaxException; 8 | import java.nio.file.Paths; 9 | import java.util.Set; 10 | import java.util.stream.Collectors; 11 | 12 | import org.junit.jupiter.api.Test; 13 | 14 | /** 15 | * @author Michael Angstadt 16 | */ 17 | class JavadocZipFileTest { 18 | private final JavadocZipFile zip; 19 | { 20 | try { 21 | zip = load(""); 22 | } catch (IOException | URISyntaxException e) { 23 | throw new RuntimeException(e); 24 | } 25 | } 26 | 27 | @Test 28 | void info_without_file() throws Exception { 29 | var zip = load("-no-info"); 30 | assertNull(zip.getName()); 31 | assertNull(zip.getBaseUrl()); 32 | } 33 | 34 | @Test 35 | void info_without_attributes() throws Exception { 36 | var zip = load("-no-attributes"); 37 | assertNull(zip.getName()); 38 | assertNull(zip.getBaseUrl()); 39 | } 40 | 41 | @Test 42 | void info() { 43 | assertEquals("Java", zip.getName()); 44 | assertEquals("8", zip.getVersion()); 45 | assertEquals("https://docs.oracle.com/javase/8/docs/api/", zip.getBaseUrl()); 46 | assertEquals("http://java.oracle.com", zip.getProjectUrl()); 47 | } 48 | 49 | @Test 50 | void getUrl() { 51 | var info = new ClassInfo.Builder().name(new ClassName("java.util", "List")).build(); 52 | assertEquals("https://docs.oracle.com/javase/8/docs/api/java/util/List.html", zip.getUrl(info, false)); 53 | assertEquals("https://docs.oracle.com/javase/8/docs/api/index.html?java/util/List.html", zip.getUrl(info, true)); 54 | } 55 | 56 | @Test 57 | void getUrl_javadocUrlPattern() throws Exception { 58 | var zip = load("-javadocUrlPattern"); 59 | 60 | var info = new ClassInfo.Builder().name(new ClassName("android.app", "Application")).build(); 61 | assertEquals("http://developer.android.com/reference/android/app/Application.html", zip.getUrl(info, false)); 62 | assertEquals("http://developer.android.com/reference/android/app/Application.html", zip.getUrl(info, true)); 63 | } 64 | 65 | @Test 66 | void getClassNames() throws Exception { 67 | //@formatter:off 68 | var actual = zip.getClassNames().stream() 69 | .map(ClassName::getFullyQualifiedName) 70 | .collect(Collectors.toSet()); 71 | //@formatter:on 72 | 73 | //@formatter:off 74 | var expected = Set.of( 75 | "java.lang.Object", 76 | "java.awt.List", 77 | "java.util.List", 78 | "java.util.Collection" 79 | ); 80 | //@formatter:on 81 | 82 | assertEquals(expected, actual); 83 | } 84 | 85 | @Test 86 | void getClassInfo_not_found() throws Exception { 87 | var info = zip.getClassInfo("java.lang.Foo"); 88 | assertNull(info); 89 | } 90 | 91 | @Test 92 | void getClassInfo() throws Exception { 93 | var info = zip.getClassInfo("java.lang.Object"); 94 | assertEquals("java.lang.Object", info.getName().getFullyQualifiedName()); 95 | assertEquals("Object", info.getName().getSimpleName()); 96 | } 97 | 98 | private static JavadocZipFile load(String suffix) throws IOException, URISyntaxException { 99 | var uri = JavadocZipFileTest.class.getResource(JavadocZipFileTest.class.getSimpleName() + suffix + ".zip").toURI(); 100 | var file = Paths.get(uri); 101 | return new JavadocZipFile(file); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/test/java/oakbot/filter/UpsidedownTextFilterTest.java: -------------------------------------------------------------------------------- 1 | package oakbot.filter; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | /** 8 | * @author Michael Angstadt 9 | */ 10 | class UpsidedownTextFilterTest { 11 | @Test 12 | void filter() { 13 | var filter = new UpsidedownTextFilter(); 14 | assertEquals("Hǝllo' ʍoɹlp¡", filter.filter("Hello, world!")); 15 | assertEquals("Hǝllo' [ʍoɹlp¡](http://google.com)", filter.filter("Hello, [world!](http://google.com)")); 16 | assertEquals(":1 Hǝllo' ʍoɹlp¡", filter.filter(":1 Hello, world!")); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/oakbot/listener/MentionListenerTest.java: -------------------------------------------------------------------------------- 1 | package oakbot.listener; 2 | 3 | import static oakbot.bot.ChatActionsUtils.assertMessage; 4 | import static org.junit.jupiter.api.Assertions.assertFalse; 5 | import static org.junit.jupiter.api.Assertions.assertTrue; 6 | import static org.mockito.Mockito.mock; 7 | import static org.mockito.Mockito.when; 8 | 9 | import org.junit.jupiter.api.Test; 10 | 11 | import com.github.mangstadt.sochat4j.ChatMessage; 12 | 13 | import oakbot.bot.IBot; 14 | 15 | /** 16 | * @author Michael Angstadt 17 | */ 18 | class MentionListenerTest { 19 | @Test 20 | void respond() { 21 | assertResponse("Hey @OakBot", ":0 Type `/help` to see all my commands."); 22 | assertResponse("Hey @Oak", ":0 Type `/help` to see all my commands."); 23 | assertResponse("@Oak Thank you", ":0 You're welcome."); 24 | assertResponse("Thanks @Oak", ":0 You're welcome."); 25 | assertResponse("@Oak thx!", ":0 You're welcome."); 26 | assertNoResponse("Hey @OakBott"); 27 | assertNoResponse("Hey"); 28 | } 29 | 30 | private static void assertNoResponse(String message) { 31 | //@formatter:off 32 | var chatMessage = new ChatMessage.Builder() 33 | .content(message) 34 | .build(); 35 | //@formatter:on 36 | 37 | var bot = mock(IBot.class); 38 | when(bot.getTrigger()).thenReturn("/"); 39 | when(bot.getUsername()).thenReturn("OakBot"); 40 | 41 | var listener = new MentionListener(); 42 | 43 | var actions = listener.onMessage(chatMessage, bot); 44 | assertTrue(actions.isEmpty()); 45 | } 46 | 47 | private static void assertResponse(String message, String expectedResponse) { 48 | //@formatter:off 49 | var chatMessage = new ChatMessage.Builder() 50 | .content(message) 51 | .build(); 52 | //@formatter:on 53 | 54 | var bot = mock(IBot.class); 55 | when(bot.getTrigger()).thenReturn("/"); 56 | when(bot.getUsername()).thenReturn("OakBot"); 57 | 58 | var listener = new MentionListener(); 59 | 60 | var actions = listener.onMessage(chatMessage, bot); 61 | assertMessage(expectedResponse, actions); 62 | } 63 | 64 | @Test 65 | void prevent_spam() { 66 | //@formatter:off 67 | var chatMessage = new ChatMessage.Builder() 68 | .content("Hey @Oakbot") 69 | .build(); 70 | //@formatter:on 71 | 72 | var bot = mock(IBot.class); 73 | when(bot.getTrigger()).thenReturn("/"); 74 | when(bot.getUsername()).thenReturn("OakBot"); 75 | 76 | var listener = new MentionListener(); 77 | 78 | var response = listener.onMessage(chatMessage, bot); 79 | assertFalse(response.isEmpty()); 80 | 81 | response = listener.onMessage(chatMessage, bot); 82 | assertTrue(response.isEmpty()); 83 | } 84 | 85 | @Test 86 | void ignore_next_message() { 87 | //@formatter:off 88 | var chatMessage = new ChatMessage.Builder() 89 | .content("Hey @Oakbot") 90 | .build(); 91 | //@formatter:on 92 | 93 | var bot = mock(IBot.class); 94 | when(bot.getTrigger()).thenReturn("/"); 95 | when(bot.getUsername()).thenReturn("OakBot"); 96 | 97 | var listener = new MentionListener(); 98 | listener.ignoreNextMessage(); 99 | 100 | var response = listener.onMessage(chatMessage, bot); 101 | assertTrue(response.isEmpty()); 102 | 103 | response = listener.onMessage(chatMessage, bot); 104 | assertFalse(response.isEmpty()); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/test/java/oakbot/listener/chatgpt/ResponseSamples.java: -------------------------------------------------------------------------------- 1 | package oakbot.listener.chatgpt; 2 | 3 | import com.fasterxml.jackson.databind.node.ObjectNode; 4 | 5 | import oakbot.util.JsonUtils; 6 | 7 | /** 8 | * OpenAI response samples. 9 | * @author Michael Angstadt 10 | */ 11 | public class ResponseSamples { 12 | public static String chatCompletion(String responseMessage) { 13 | var root = JsonUtils.newObject(); 14 | 15 | //@formatter:off 16 | return JsonUtils.toString(root 17 | .put("id", "chatcmpl-8739H6quSXU5gws7FoIIutD3TsOsZ") 18 | .put("object", "chat.completion") 19 | .put("created", 1714414784L) 20 | .put("model", "gpt-3.5-turbo-0613") 21 | .set("choices", root.arrayNode().add(root.objectNode() 22 | .put("index", 0) 23 | .set("message", root.objectNode() 24 | .put("role", "assistant") 25 | .put("content", responseMessage) 26 | ) 27 | .put("finish_reason", "stop") 28 | )) 29 | .set("usage", root.objectNode() 30 | .put("prompt_tokens", 50) 31 | .put("completion_tokens", 9) 32 | .put("total_tokens", 59) 33 | )); 34 | //@formatter:on 35 | } 36 | 37 | public static String createImage(String url) { 38 | var root = JsonUtils.newObject(); 39 | 40 | //@formatter:off 41 | return JsonUtils.toString(root 42 | .put("created", 1696771460) 43 | .set("data", root.arrayNode().add(root.objectNode() 44 | .put("url", url) 45 | ))); 46 | //@formatter:on 47 | } 48 | 49 | public static String createImageVariation(String url) { 50 | return createImage(url); 51 | } 52 | 53 | public static String error(String message) { 54 | var root = JsonUtils.newObject(); 55 | 56 | //@formatter:off 57 | return JsonUtils.toString(root 58 | .set("error", root.objectNode() 59 | .put("message", message) 60 | .put("type", "invalid_request_error") 61 | .put("param", (String)null) 62 | .put("code", "code_goes_here") 63 | )); 64 | //@formatter:on 65 | } 66 | 67 | private ResponseSamples() { 68 | //empty 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/test/java/oakbot/task/QOTDTest.java: -------------------------------------------------------------------------------- 1 | package oakbot.task; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import java.nio.charset.StandardCharsets; 7 | import java.time.Duration; 8 | import java.time.LocalDateTime; 9 | 10 | import org.junit.jupiter.api.AfterEach; 11 | import org.junit.jupiter.api.Test; 12 | 13 | import oakbot.util.Gobble; 14 | import oakbot.util.HttpFactory; 15 | import oakbot.util.MockHttpClientBuilder; 16 | import oakbot.util.Now; 17 | 18 | class QOTDTest { 19 | /** 20 | * Live test. Outputs current QOTD to stdout. 21 | */ 22 | public static void main(String args[]) throws Exception { 23 | var qotd = new QOTD(); 24 | System.out.println(qotd.fromSlashdot()); 25 | } 26 | 27 | @AfterEach 28 | void after() { 29 | Now.restore(); 30 | HttpFactory.restore(); 31 | } 32 | 33 | @Test 34 | void fromSlashdot() throws Exception { 35 | var slashdot = new Gobble(getClass(), "slashdot.html").asString(StandardCharsets.UTF_8); 36 | 37 | //@formatter:off 38 | HttpFactory.inject(new MockHttpClientBuilder() 39 | .requestGet("https://slashdot.org") 40 | .responseOk(slashdot) 41 | .build()); 42 | //@formatter:on 43 | 44 | var qotd = new QOTD(); 45 | 46 | var expected = "\"For a male and female to live continuously together is... biologically speaking, an extremely unnatural condition.\" -- Robert Briffault ([source](https://slashdot.org))"; 47 | var actual = qotd.fromSlashdot().toString(); 48 | assertEquals(expected, actual); 49 | } 50 | 51 | @Test 52 | void fromTheySaidSo() throws Exception { 53 | var theySaidSo = new Gobble(getClass(), "theysaidso.json").asString(StandardCharsets.UTF_8); 54 | 55 | //@formatter:off 56 | HttpFactory.inject(new MockHttpClientBuilder() 57 | .requestGet("http://quotes.rest/qod.json") 58 | .responseOk(theySaidSo) 59 | .build()); 60 | //@formatter:on 61 | 62 | var qotd = new QOTD(); 63 | 64 | var expected = "*\"If you like what you do, and you’re lucky enough to be good at it, do it for that reason.\"* -Phil Grimshaw [(source)](https://theysaidso.com)"; 65 | var actual = qotd.fromTheySaidSo().toString(); 66 | assertEquals(expected, actual); 67 | } 68 | 69 | @Test 70 | void fromTheySaidSo_newline() throws Exception { 71 | var theySaidSo = new Gobble(getClass(), "theysaidso_newline.json").asString(StandardCharsets.UTF_8); 72 | 73 | //@formatter:off 74 | HttpFactory.inject(new MockHttpClientBuilder() 75 | .requestGet("http://quotes.rest/qod.json") 76 | .responseOk(theySaidSo) 77 | .build()); 78 | //@formatter:on 79 | 80 | var qotd = new QOTD(); 81 | 82 | var expected = "If you like what you do,\nand you’re lucky enough to be good at it, do it for that reason.\n-Phil Grimshaw (source: https://theysaidso.com)"; 83 | var actual = qotd.fromTheySaidSo().toString(); 84 | assertEquals(expected, actual); 85 | } 86 | 87 | @Test 88 | void nextRun() { 89 | Now.setNow(LocalDateTime.of(2018, 7, 19, 11, 0, 0)); 90 | 91 | var task = new QOTD(); 92 | 93 | var expected = Duration.ofHours(13).toMillis(); 94 | var actual = task.nextRun(); 95 | assertApprox(expected, actual); 96 | } 97 | 98 | private static void assertApprox(long expected, long actual) { 99 | assertTrue(expected - actual < 1000, () -> "Expected " + expected + " but was " + actual + "."); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/test/java/oakbot/util/ChatCommandBuilder.java: -------------------------------------------------------------------------------- 1 | package oakbot.util; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | import com.github.mangstadt.sochat4j.ChatMessage; 6 | 7 | import oakbot.bot.ChatCommand; 8 | import oakbot.command.Command; 9 | 10 | /** 11 | * Builds mock {@link ChatCommand} objects for unit testing. 12 | * @author Michael Angstadt 13 | */ 14 | public class ChatCommandBuilder { 15 | private final String commandName; 16 | private int messageId, roomId, userId; 17 | private String trigger = "/", username, content = ""; 18 | private LocalDateTime timestamp; 19 | 20 | /** 21 | * @param command the command that is being tested 22 | */ 23 | public ChatCommandBuilder(Command command) { 24 | commandName = command.name(); 25 | } 26 | 27 | /** 28 | * Sets the command trigger. 29 | * @param trigger the trigger (defaults to "/") 30 | * @return this 31 | */ 32 | public ChatCommandBuilder trigger(String trigger) { 33 | this.trigger = trigger; 34 | return this; 35 | } 36 | 37 | /** 38 | * Sets the message ID. 39 | * @param messageId the message ID (defaults to 0) 40 | * @return this 41 | */ 42 | public ChatCommandBuilder messageId(int messageId) { 43 | this.messageId = messageId; 44 | return this; 45 | } 46 | 47 | /** 48 | * Sets the room ID. 49 | * @param roomId the room ID (defaults to 0) 50 | * @return this 51 | */ 52 | public ChatCommandBuilder roomId(int roomId) { 53 | this.roomId = roomId; 54 | return this; 55 | } 56 | 57 | /** 58 | * Sets the user ID. 59 | * @param userId the user ID (defaults to 0) 60 | * @return this 61 | */ 62 | public ChatCommandBuilder userId(int userId) { 63 | this.userId = userId; 64 | return this; 65 | } 66 | 67 | /** 68 | * Sets the username. 69 | * @param username the username (defaults to null) 70 | * @return this 71 | */ 72 | public ChatCommandBuilder username(String username) { 73 | this.username = username; 74 | return this; 75 | } 76 | 77 | /** 78 | * Sets the timestamp. 79 | * @param timestamp the timestamp (defaults to null) 80 | * @return this 81 | */ 82 | public ChatCommandBuilder timestamp(LocalDateTime timestamp) { 83 | this.timestamp = timestamp; 84 | return this; 85 | } 86 | 87 | /** 88 | * Sets the message content (excludes the command name). 89 | * @param content the content (defaults to empty string) 90 | * @return this 91 | */ 92 | public ChatCommandBuilder content(String content) { 93 | this.content = content; 94 | return this; 95 | } 96 | 97 | /** 98 | * Constructs the mock {@link ChatCommand} object. 99 | * @return the chat command 100 | */ 101 | public ChatCommand build() { 102 | //@formatter:off 103 | var message = new ChatMessage.Builder() 104 | .messageId(messageId) 105 | .roomId(roomId) 106 | .userId(userId) 107 | .username(username) 108 | .timestamp(timestamp) 109 | .content(trigger + commandName + " " + content) 110 | .build(); 111 | //@formatter:on 112 | 113 | return new ChatCommand(message, commandName, content); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/test/java/oakbot/util/GobbleTest.java: -------------------------------------------------------------------------------- 1 | package oakbot.util; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertArrayEquals; 4 | import static org.junit.jupiter.api.Assertions.assertEquals; 5 | import static org.junit.jupiter.api.Assertions.assertThrows; 6 | 7 | import java.io.ByteArrayInputStream; 8 | import java.io.StringReader; 9 | import java.nio.file.Files; 10 | import java.nio.file.Path; 11 | 12 | import org.junit.jupiter.api.Test; 13 | import org.junit.jupiter.api.io.TempDir; 14 | 15 | /** 16 | * @author Michael Angstadt 17 | */ 18 | class GobbleTest { 19 | @TempDir 20 | private Path tempDir; 21 | 22 | @Test 23 | void file() throws Exception { 24 | var data = "one two three"; 25 | 26 | var file = Files.createTempFile(tempDir, null, null); 27 | Files.write(file, data.getBytes()); 28 | 29 | var stream = new Gobble(file); 30 | assertEquals(data, stream.asString()); 31 | assertArrayEquals(data.getBytes(), stream.asByteArray()); 32 | } 33 | 34 | @Test 35 | void inputStream() throws Exception { 36 | var data = "one two three"; 37 | 38 | var in = new ByteArrayInputStream(data.getBytes()); 39 | var stream = new Gobble(in); 40 | assertEquals(data, stream.asString()); 41 | assertArrayEquals(new byte[0], stream.asByteArray()); //input stream was consumed 42 | 43 | in = new ByteArrayInputStream(data.getBytes()); 44 | stream = new Gobble(in); 45 | assertArrayEquals(data.getBytes(), stream.asByteArray()); 46 | } 47 | 48 | @Test 49 | void reader() throws Exception { 50 | var data = "one two three"; 51 | 52 | var reader = new StringReader(data); 53 | var stream = new Gobble(reader); 54 | assertEquals(data, stream.asString()); 55 | 56 | assertThrows(IllegalStateException.class, () -> stream.asByteArray()); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/test/java/oakbot/util/RelativeDateFormatTest.java: -------------------------------------------------------------------------------- 1 | package oakbot.util; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import java.time.LocalDateTime; 7 | 8 | import org.junit.jupiter.api.Test; 9 | 10 | /** 11 | * @author Michael Angstadt 12 | */ 13 | class RelativeDateFormatTest { 14 | private final RelativeDateFormat relativeDf = new RelativeDateFormat(); 15 | 16 | @Test 17 | void format() { 18 | var now = LocalDateTime.now(); 19 | assertEquals("A moment ago", relativeDf.format(now)); 20 | 21 | now = now.minusMinutes(30); 22 | assertTrue(relativeDf.format(now).matches("\\d+ minutes ago")); 23 | 24 | now = now.minusHours(1); 25 | assertTrue(relativeDf.format(now).matches("Today at .*")); 26 | 27 | now = now.minusDays(1); 28 | assertTrue(relativeDf.format(now).matches("Yesterday at .*")); 29 | 30 | now = now.minusDays(1); 31 | assertEquals("About 2 days ago.", relativeDf.format(now)); 32 | 33 | now = now.minusWeeks(1); 34 | assertEquals("Over a week ago.", relativeDf.format(now)); 35 | 36 | now = now.minusWeeks(1); 37 | assertEquals("Over 2 weeks ago.", relativeDf.format(now)); 38 | 39 | now = now.minusWeeks(3); 40 | assertEquals("Over a month ago.", relativeDf.format(now)); 41 | 42 | now = now.minusMonths(1); 43 | assertEquals("Over 2 months ago.", relativeDf.format(now)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/oakbot/util/StringUtilsTest.java: -------------------------------------------------------------------------------- 1 | package oakbot.util; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | /** 8 | * @author Michael Angstadt 9 | */ 10 | class StringUtilsTest { 11 | @Test 12 | void plural() { 13 | assertEquals("cats", StringUtils.plural("cat", 0)); 14 | assertEquals("cat", StringUtils.plural("cat", 1)); 15 | assertEquals("cats", StringUtils.plural("cat", 2)); 16 | 17 | assertEquals("buses", StringUtils.plural("bus", 0)); 18 | assertEquals("bus", StringUtils.plural("bus", 1)); 19 | assertEquals("buses", StringUtils.plural("bus", 2)); 20 | } 21 | 22 | @Test 23 | void possessive() { 24 | assertEquals("cat's", StringUtils.possessive("cat")); 25 | assertEquals("cats'", StringUtils.possessive("cats")); 26 | } 27 | 28 | @Test 29 | void countWords() { 30 | assertEquals(0, StringUtils.countWords("")); 31 | assertEquals(0, StringUtils.countWords(" ")); 32 | assertEquals(1, StringUtils.countWords(" one ")); 33 | assertEquals(3, StringUtils.countWords("one two\tthree")); 34 | } 35 | 36 | @Test 37 | void a() { 38 | assertEquals("a", StringUtils.a("")); 39 | assertEquals("a", StringUtils.a("cat")); 40 | assertEquals("an", StringUtils.a("animal")); 41 | assertEquals("an", StringUtils.a("egg")); 42 | assertEquals("an", StringUtils.a("igloo")); 43 | assertEquals("an", StringUtils.a("olive")); 44 | assertEquals("an", StringUtils.a("umbrella")); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/test/resources/logging.properties: -------------------------------------------------------------------------------- 1 | #Global logging level 2 | .level=OFF 3 | -------------------------------------------------------------------------------- /src/test/resources/oakbot/ai/openai/image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChat/OakBot/e1f4d2d5fb51abfee27d0af5a8c079ececffb2cf/src/test/resources/oakbot/ai/openai/image.jpg -------------------------------------------------------------------------------- /src/test/resources/oakbot/chat/stackexchange-login-form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 22 | 23 | 24 | 25 | 26 |
    27 | 28 | 29 | 30 | 31 | 32 |
    33 | Sign in with your account 34 |
    35 | 36 | 37 | 38 | 63 | 64 |
    65 |
    66 |
    67 | 68 | 69 | 70 | 75 |
    76 | 77 | 78 | -------------------------------------------------------------------------------- /src/test/resources/oakbot/chat/stackexchange-login-redirect-page.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 21 | 22 | 28 | 29 | 30 | 31 |
    32 | 33 | 34 | 35 | 36 |
    37 | 38 |
    39 | 40 | 41 | 45 | 46 |
    49 | 50 | 51 | -------------------------------------------------------------------------------- /src/test/resources/oakbot/command/aoc/advent-of-code-2018.json: -------------------------------------------------------------------------------- 1 | { 2 | "members": { 3 | "55305": { 4 | "global_score": 187, 5 | "name": "Unihedron", 6 | "stars": 2, 7 | "id": "55305", 8 | "last_star_ts": "1543640570", 9 | "local_score": 18, 10 | "completion_day_level": { 11 | "1": { 12 | "1": { 13 | "get_star_ts": "1543640433" 14 | }, 15 | "2": { 16 | "get_star_ts": "1543640570" 17 | } 18 | } 19 | } 20 | }, 21 | "196939": { 22 | "global_score": 0, 23 | "completion_day_level": { 24 | "1": { 25 | "1": { 26 | "get_star_ts": "1543690914" 27 | }, 28 | "2": { 29 | "get_star_ts": "1543692958" 30 | } 31 | } 32 | }, 33 | "id": "196939", 34 | "stars": 2, 35 | "name": "geisterfurz007", 36 | "local_score": 16, 37 | "last_star_ts": "1543692958" 38 | }, 39 | "213234": { 40 | "stars": 0, 41 | "name": "Neoares", 42 | "id": "213234", 43 | "last_star_ts": 0, 44 | "local_score": 0, 45 | "completion_day_level": {}, 46 | "global_score": 0 47 | }, 48 | "238844": { 49 | "id": "238844", 50 | "stars": 0, 51 | "name": "Zoe", 52 | "local_score": 0, 53 | "last_star_ts": 0, 54 | "completion_day_level": {}, 55 | "global_score": 0 56 | }, 57 | "256093": { 58 | "name": "Mike Angstadt", 59 | "stars": 2, 60 | "id": "256093", 61 | "last_star_ts": "1543640570", 62 | "local_score": 18, 63 | "completion_day_level": { 64 | "1": { 65 | "1": { 66 | "get_star_ts": "1543640433" 67 | }, 68 | "2": { 69 | "get_star_ts": "1543640570" 70 | } 71 | } 72 | }, 73 | "global_score": 187 74 | }, 75 | "284596": { 76 | "completion_day_level": {}, 77 | "stars": 0, 78 | "name": "Jenna Sloan", 79 | "id": "284596", 80 | "last_star_ts": 0, 81 | "local_score": 0, 82 | "global_score": 0 83 | }, 84 | "302170": { 85 | "global_score": 0, 86 | "name": "Patrick Stegmann", 87 | "stars": 0, 88 | "id": "302170", 89 | "local_score": 0, 90 | "last_star_ts": 0, 91 | "completion_day_level": {} 92 | }, 93 | "371917": { 94 | "global_score": 0, 95 | "completion_day_level": {}, 96 | "local_score": 0, 97 | "last_star_ts": 0, 98 | "name": "nicktar", 99 | "stars": 0, 100 | "id": "371917" 101 | }, 102 | "376542": { 103 | "global_score": 0, 104 | "stars": 0, 105 | "id": "376542", 106 | "name": null, 107 | "last_star_ts": 0, 108 | "local_score": 0, 109 | "completion_day_level": {} 110 | }, 111 | "376568": { 112 | "global_score": 0, 113 | "stars": 0, 114 | "id": "376568", 115 | "name": "Hey @Michael", 116 | "last_star_ts": 0, 117 | "local_score": 0, 118 | "completion_day_level": {} 119 | } 120 | }, 121 | "event": "2018", 122 | "owner_id": "256093" 123 | } -------------------------------------------------------------------------------- /src/test/resources/oakbot/command/javadoc/JavadocZipFileTest-javadocUrlPattern.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChat/OakBot/e1f4d2d5fb51abfee27d0af5a8c079ececffb2cf/src/test/resources/oakbot/command/javadoc/JavadocZipFileTest-javadocUrlPattern.zip -------------------------------------------------------------------------------- /src/test/resources/oakbot/command/javadoc/JavadocZipFileTest-no-attributes.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChat/OakBot/e1f4d2d5fb51abfee27d0af5a8c079ececffb2cf/src/test/resources/oakbot/command/javadoc/JavadocZipFileTest-no-attributes.zip -------------------------------------------------------------------------------- /src/test/resources/oakbot/command/javadoc/JavadocZipFileTest-no-info.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChat/OakBot/e1f4d2d5fb51abfee27d0af5a8c079ececffb2cf/src/test/resources/oakbot/command/javadoc/JavadocZipFileTest-no-info.zip -------------------------------------------------------------------------------- /src/test/resources/oakbot/command/javadoc/JavadocZipFileTest.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaChat/OakBot/e1f4d2d5fb51abfee27d0af5a8c079ececffb2cf/src/test/resources/oakbot/command/javadoc/JavadocZipFileTest.zip -------------------------------------------------------------------------------- /src/test/resources/oakbot/command/juiceboxify-face.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Juicebox yourself! 5 | 6 | 7 | 8 |
    9 | 25 | 26 |
    27 | 28 |
    29 | 30 | 31 |
    32 | 33 |
    34 |

    35 | created with 36 | 37 | (and Ruby) by 38 | Cereal 39 | and 40 | Ikari 41 |

    42 |

    43 | Github 44 |

    45 |
    46 | 47 | 48 | -------------------------------------------------------------------------------- /src/test/resources/oakbot/command/juiceboxify-no-face.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Juicebox yourself! 5 | 6 | 7 | 8 |
    9 | 25 | 26 | 27 |
    28 |

    Whoops, we couldn't find any faces!

    29 |
    30 | 31 |
    32 | 33 |
    34 |

    35 | created with 36 | 37 | (and Ruby) by 38 | Cereal 39 | and 40 | Ikari 41 |

    42 |

    43 | Github 44 |

    45 |
    46 | 47 | 48 | -------------------------------------------------------------------------------- /src/test/resources/oakbot/task/theysaidso.json: -------------------------------------------------------------------------------- 1 | { 2 | "success": { 3 | "total": 1 4 | }, 5 | "contents": { 6 | "quotes": [ 7 | { 8 | "quote": "If you like what you do, and you’re lucky enough to be good at it, do it for that reason.", 9 | "author": "Phil Grimshaw", 10 | "length": "96", 11 | "tags": [ 12 | "inspire", 13 | "luck", 14 | "reason", 15 | "tso-life" 16 | ], 17 | "category": "inspire", 18 | "title": "Inspiring Quote of the day", 19 | "date": "2019-03-08", 20 | "id": null 21 | } 22 | ], 23 | "copyright": "2017-19 theysaidso.com" 24 | } 25 | } -------------------------------------------------------------------------------- /src/test/resources/oakbot/task/theysaidso_newline.json: -------------------------------------------------------------------------------- 1 | { 2 | "success": { 3 | "total": 1 4 | }, 5 | "contents": { 6 | "quotes": [ 7 | { 8 | "quote": "If you like what you do,\nand you’re lucky enough to be good at it, do it for that reason.", 9 | "author": "Phil Grimshaw", 10 | "length": "96", 11 | "tags": [ 12 | "inspire", 13 | "luck", 14 | "reason", 15 | "tso-life" 16 | ], 17 | "category": "inspire", 18 | "title": "Inspiring Quote of the day", 19 | "date": "2019-03-08", 20 | "id": null 21 | } 22 | ], 23 | "copyright": "2017-19 theysaidso.com" 24 | } 25 | } --------------------------------------------------------------------------------