├── .gitignore ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src └── main └── java └── fr └── ordinalteam └── bot └── api ├── OrdinalBot.java ├── command ├── AbstractCommand.java └── ICommandRegistry.java ├── config └── PluginConfig.java ├── listener └── IJDAListenerRegistry.java ├── plugin ├── InvalidPluginException.java ├── Plugin.java ├── PluginDescriptor.java └── PluginLoader.java └── utils └── OrdinalConstant.java /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | build/ 3 | .idea/ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # OrdinalBot-API 3 | 4 | ![forthebadge](https://forthebadge.com/images/badges/made-with-java.svg) 5 | ![Discord](https://img.shields.io/badge/Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white) 6 | [![GitHub last commit](https://img.shields.io/github/last-commit/Ordinal-Team/OrdinalBot-API.svg?style=flat)]() 7 | [![GitHub commit activity the past week, 4 weeks](https://img.shields.io/github/commit-activity/y/Ordinal-Team/OrdinalBot-API.svg?style=flat)]() 8 | 9 | ## Overview 10 | **OrdinalBot-API** is a framework similar to Spigot, designed to enable the creation of plugins for Discord bots. 11 | 12 | ## Version 13 | Current Version: **0.1.0** 14 | 15 | ## Features 16 | - Create custom modules for your Bot. 17 | - Simplified API similar to Spigot. 18 | - Create customs / commands and use JDAListener 19 | 20 | ## Getting Started 21 | 22 | ### Installation 23 | 1. Download the library from the [releases page](https://github.com/Ordinal-Team/OrdinalBot-API/releases) and place it in the `libs` directory of your project. 24 | 2. Add the library to your local dependency manager. 25 | 26 | #### Gradle 27 | Add the following to your `build.gradle`: 28 | ```groovy 29 | repositories { 30 | mavenCentral() 31 | } 32 | 33 | dependencies { 34 | implementation(fileTree("/libs")) 35 | } 36 | ``` 37 | 38 | 39 | ### Usage 40 | Create a `plugin.json` in your resources directory: 41 | ```json 42 | { 43 | "name": "Module Test", 44 | "main": "fr.ordinalteam.moduletest.Main", 45 | "version": "1.0.0", 46 | "author": "Arinonia" 47 | } 48 | ``` 49 | 50 | Implement your main class: 51 | ```java 52 | public class Main extends Plugin { 53 | 54 | @Override 55 | public void onEnable() { 56 | this.logger.log("Registering test module"); 57 | } 58 | } 59 | ``` 60 | 61 | Register commands and listeners: 62 | ```java 63 | public class Main extends Plugin { 64 | 65 | @Override 66 | public void onEnable() { 67 | this.logger.log("Registering test module"); 68 | this.getJDAListenerManager().registerJDAListener(new YourListenerAdapter()); 69 | this.getCommandRegistry().registerCommand(new YourCommand(), this); 70 | } 71 | } 72 | 73 | public class YourListenerAdapter extends ListenerAdapter { 74 | // Your listeners 75 | } 76 | 77 | public class YourCommand extends Command { 78 | public YourCommand() { 79 | super("test", "!test <@user> to tag user"); 80 | } 81 | 82 | @Override 83 | public void onCommand(final SlashCommandInteractionEvent event) { 84 | // Command logic 85 | } 86 | } 87 | ``` 88 | 89 | ## Contributing 90 | Feel free to submit issues and pull requests. For suggestions and discussions, join our [Discord server](https://discord.gg/XQnNJYv). 91 | 92 | ## License 93 | This project is licensed under the GPLv3 License - see the [LICENSE](LICENSE) file for details. 94 | 95 | ## Contact 96 | For more information, visit our [Website](http://185.229.220.75:8090/). 97 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group = 'fr.ordinalteam' 6 | version = '0.1.0' 7 | 8 | repositories { 9 | mavenCentral() 10 | } 11 | 12 | dependencies { 13 | implementation("net.dv8tion:JDA:5.0.0-beta.24") { 14 | exclude module: 'opus-java' 15 | } 16 | implementation("com.google.code.gson:gson:2.10.1") 17 | } 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ordinal-Team/OrdinalBot-API/08093d713a0f9563134aec68da005988ee37141b/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed May 22 11:59:08 CEST 2024 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'OrdinalBot-API' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/fr/ordinalteam/bot/api/OrdinalBot.java: -------------------------------------------------------------------------------- 1 | package fr.ordinalteam.bot.api; 2 | 3 | import fr.ordinalteam.bot.api.command.ICommandRegistry; 4 | import fr.ordinalteam.bot.api.listener.IJDAListenerRegistry; 5 | 6 | public abstract class OrdinalBot { 7 | 8 | private static OrdinalBot instance; 9 | 10 | public OrdinalBot() { 11 | instance = this; 12 | } 13 | 14 | public abstract ICommandRegistry getCommandRegistry(); 15 | public abstract IJDAListenerRegistry getJDAListenerRegistry(); 16 | 17 | public static OrdinalBot getInstance() { 18 | return instance; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/fr/ordinalteam/bot/api/command/AbstractCommand.java: -------------------------------------------------------------------------------- 1 | package fr.ordinalteam.bot.api.command; 2 | 3 | import fr.ordinalteam.bot.api.utils.OrdinalConstant; 4 | import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; 5 | import net.dv8tion.jda.api.interactions.commands.build.OptionData; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | public abstract class AbstractCommand { 11 | 12 | private final String name; 13 | private final String description; 14 | private final List options = new ArrayList<>(); 15 | 16 | public AbstractCommand(final String name, final String description) { 17 | this.name = name; 18 | this.description = description; 19 | } 20 | 21 | public AbstractCommand(final String name) { 22 | this(name, OrdinalConstant.APP_NAME); 23 | } 24 | 25 | public abstract void onCommand(final SlashCommandInteractionEvent event); 26 | 27 | public String getName() { 28 | return this.name; 29 | } 30 | 31 | public String getDescription() { 32 | return this.description; 33 | } 34 | 35 | public void addOption(final OptionData option) { 36 | this.options.add(option); 37 | } 38 | 39 | public List getOptions() { 40 | return this.options; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/fr/ordinalteam/bot/api/command/ICommandRegistry.java: -------------------------------------------------------------------------------- 1 | package fr.ordinalteam.bot.api.command; 2 | 3 | import fr.ordinalteam.bot.api.plugin.Plugin; 4 | 5 | import java.util.List; 6 | import java.util.Set; 7 | 8 | public interface ICommandRegistry { 9 | 10 | void registerCommand(final AbstractCommand command, final Plugin plugin); 11 | void unRegisterCommand(final AbstractCommand command); 12 | Set getPluginCommands(final Plugin plugin); 13 | List getCommands(); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/fr/ordinalteam/bot/api/config/PluginConfig.java: -------------------------------------------------------------------------------- 1 | package fr.ordinalteam.bot.api.config; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.GsonBuilder; 5 | import com.google.gson.JsonObject; 6 | 7 | import java.io.File; 8 | import java.io.FileReader; 9 | import java.io.FileWriter; 10 | import java.io.IOException; 11 | 12 | public class PluginConfig { 13 | 14 | //! TO FIX: object are not working for now 15 | private final File configFile; 16 | private final Gson gson; 17 | private JsonObject configData; 18 | 19 | public PluginConfig(final File configFile) { 20 | this.configFile = configFile; 21 | this.gson = new GsonBuilder().setPrettyPrinting().create(); 22 | loadConfig(); 23 | } 24 | 25 | private void loadConfig() { 26 | try (final FileReader reader = new FileReader(this.configFile)) { 27 | this.configData = this.gson.fromJson(reader, JsonObject.class); 28 | } catch (final IOException e) { 29 | e.printStackTrace(); 30 | this.configData = new JsonObject(); 31 | } 32 | } 33 | 34 | public void saveConfig() { 35 | try (final FileWriter writer = new FileWriter(this.configFile)) { 36 | this.gson.toJson(this.configData, writer); 37 | } catch (final IOException e) { 38 | e.printStackTrace(); 39 | } 40 | } 41 | 42 | public String getString(final String key) { 43 | return this.configData.has(key) ? this.configData.get(key).getAsString() : null; 44 | } 45 | 46 | public T getObject(final String key, final Class classOfT) { 47 | return this.configData.has(key) ? this.gson.fromJson(this.configData.get(key), classOfT) : null; 48 | } 49 | 50 | public void set(final String key, final Object value) { 51 | this.configData.add(key, this.gson.toJsonTree(value)); 52 | saveConfig(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/fr/ordinalteam/bot/api/listener/IJDAListenerRegistry.java: -------------------------------------------------------------------------------- 1 | package fr.ordinalteam.bot.api.listener; 2 | 3 | import net.dv8tion.jda.api.hooks.ListenerAdapter; 4 | 5 | public interface IJDAListenerRegistry { 6 | void registerJDAListener(final ListenerAdapter listenerAdapter); 7 | void unRegisterJDAListener(final ListenerAdapter listenerAdapter); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/fr/ordinalteam/bot/api/plugin/InvalidPluginException.java: -------------------------------------------------------------------------------- 1 | package fr.ordinalteam.bot.api.plugin; 2 | 3 | public class InvalidPluginException extends Exception { 4 | 5 | public InvalidPluginException(final String message) { 6 | super(message); 7 | } 8 | 9 | public InvalidPluginException(final String message, final Throwable cause) { 10 | super(message, cause); 11 | } 12 | 13 | public InvalidPluginException(final Throwable cause) { 14 | super(cause); 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/fr/ordinalteam/bot/api/plugin/Plugin.java: -------------------------------------------------------------------------------- 1 | package fr.ordinalteam.bot.api.plugin; 2 | 3 | import fr.ordinalteam.bot.api.OrdinalBot; 4 | import fr.ordinalteam.bot.api.config.PluginConfig; 5 | 6 | import java.io.File; 7 | 8 | public abstract class Plugin { 9 | 10 | private final OrdinalBot ordinalBot; 11 | private PluginConfig defaultConfig; 12 | private PluginDescriptor pluginDescriptor; 13 | 14 | public Plugin() { 15 | this.ordinalBot = OrdinalBot.getInstance(); 16 | } 17 | 18 | public void onEnable() {} 19 | 20 | 21 | public void onDisable() {} 22 | 23 | public File getPluginFolder() { 24 | if (this.pluginDescriptor == null) { 25 | throw new IllegalStateException("PluginDescriptor is not set"); 26 | } 27 | return new File("plugins", this.pluginDescriptor.name()); 28 | } 29 | 30 | private boolean createPluginFolder() { 31 | if (this.pluginDescriptor == null) { 32 | throw new IllegalStateException("PluginDescriptor is not set"); 33 | } 34 | final File file = new File("plugins", pluginDescriptor.name()); 35 | if (!file.exists()) { 36 | if (!file.mkdirs()) { 37 | System.err.println("Failed to create plugin folder: " + file.getAbsolutePath()); 38 | return false; 39 | } 40 | } 41 | return true; 42 | } 43 | public PluginConfig getDefaultConfig() { 44 | if (this.defaultConfig == null) { 45 | this.defaultConfig = new PluginConfig(new File(getPluginFolder(), "config.json")); 46 | } 47 | return this.defaultConfig; 48 | } 49 | 50 | public OrdinalBot getOrdinalBot() { 51 | return this.ordinalBot; 52 | } 53 | 54 | public PluginDescriptor getPluginDescriptor() { 55 | return this.pluginDescriptor; 56 | } 57 | 58 | public void setPluginDescriptor(final PluginDescriptor pluginDescriptor) { 59 | this.pluginDescriptor = pluginDescriptor; 60 | if (!createPluginFolder()) { 61 | System.err.println("Failed to create plugin folder: " + pluginDescriptor.name()); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/fr/ordinalteam/bot/api/plugin/PluginDescriptor.java: -------------------------------------------------------------------------------- 1 | package fr.ordinalteam.bot.api.plugin; 2 | 3 | 4 | public record PluginDescriptor(String name, String main, String version, String author, String description) { 5 | 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/fr/ordinalteam/bot/api/plugin/PluginLoader.java: -------------------------------------------------------------------------------- 1 | package fr.ordinalteam.bot.api.plugin; 2 | 3 | import com.google.gson.JsonObject; 4 | import com.google.gson.JsonParser; 5 | 6 | import java.io.File; 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | import java.lang.reflect.InvocationTargetException; 10 | import java.net.URL; 11 | import java.net.URLClassLoader; 12 | import java.nio.file.Files; 13 | import java.nio.file.StandardCopyOption; 14 | import java.util.ArrayList; 15 | import java.util.HashMap; 16 | import java.util.List; 17 | import java.util.Map; 18 | import java.util.Scanner; 19 | import java.util.jar.JarEntry; 20 | import java.util.jar.JarFile; 21 | 22 | public class PluginLoader { 23 | 24 | private final List plugins = new ArrayList<>(); 25 | private final Map pluginClassLoaders = new HashMap<>(); 26 | private final File pluginFolder = new File("plugins"); 27 | 28 | public void start() { 29 | if (!this.pluginFolder.exists()) { 30 | if (this.pluginFolder.mkdir()) { 31 | System.out.println("Created folder " + this.pluginFolder.getName()); 32 | } else { 33 | System.err.println("Cannot create folder " + this.pluginFolder.getName()); 34 | } 35 | } 36 | loadAllPlugins(); 37 | } 38 | 39 | private void loadAllPlugins() { 40 | final ArrayList jarFiles = this.listFilesJar(this.pluginFolder); 41 | jarFiles.forEach(file -> { 42 | try { 43 | this.loadPlugin(file); 44 | } catch (final InvalidPluginException e) { 45 | e.printStackTrace(); 46 | } 47 | }); 48 | } 49 | 50 | private ArrayList listFilesJar(final File file) { 51 | final ArrayList jarFiles = new ArrayList<>(); 52 | final File[] files = file.listFiles(); 53 | 54 | if (files != null) { 55 | for (final File f : files) { 56 | if (f.getName().endsWith(".jar")) { 57 | jarFiles.add(f); 58 | } 59 | } 60 | } 61 | 62 | return jarFiles; 63 | } 64 | 65 | public void loadPlugin(final File file) throws InvalidPluginException { 66 | URLClassLoader classLoader = null; 67 | try { 68 | final JarFile jarFile = new JarFile(file); 69 | final JsonObject json = loadPluginJson(jarFile, file); 70 | 71 | if (json == null) { 72 | System.err.println("Skipping JAR: " + file.getName() + " (missing plugin.json)"); 73 | return; 74 | } 75 | final PluginDescriptor pluginDescriptor = createPluginDescriptor(json); 76 | classLoader = createClassLoader(file); 77 | final Class pluginClass = loadPluginClass(classLoader, pluginDescriptor, file); 78 | final Plugin plugin = instantiatePlugin(pluginClass, pluginDescriptor, jarFile); 79 | addPlugin(plugin, classLoader); 80 | } catch (IOException e) { 81 | throw new InvalidPluginException("IOException occurred while processing file: " + file.getName(), e); 82 | } finally { 83 | closeClassLoader(classLoader); 84 | } 85 | } 86 | 87 | private JsonObject loadPluginJson(final JarFile jarFile, final File file) throws InvalidPluginException { 88 | final JarEntry entry = jarFile.getJarEntry("plugin.json"); 89 | if (entry == null) { 90 | return null; 91 | } 92 | try (final InputStream stream = jarFile.getInputStream(entry)) { 93 | return inputStreamToJSON(stream); 94 | } catch (final IOException e) { 95 | throw new InvalidPluginException("Failed to read 'plugin.json' in " + file.getName(), e); 96 | } 97 | } 98 | 99 | private PluginDescriptor createPluginDescriptor(final JsonObject json) { 100 | return new PluginDescriptor( 101 | json.get("name").getAsString(), 102 | json.get("main").getAsString(), 103 | json.get("version").getAsString(), 104 | json.get("author").getAsString(), 105 | json.has("description") ? json.get("description").getAsString() : "" 106 | ); 107 | } 108 | 109 | private URLClassLoader createClassLoader(final File file) throws InvalidPluginException { 110 | try { 111 | return new URLClassLoader(new URL[]{file.toURI().toURL()}, this.getClass().getClassLoader()); 112 | } catch (final IOException e) { 113 | throw new InvalidPluginException("Failed to create URLClassLoader for " + file.getName(), e); 114 | } 115 | } 116 | 117 | private Class loadPluginClass(final URLClassLoader classLoader, final PluginDescriptor pluginDescriptor, final File file) throws InvalidPluginException { 118 | try { 119 | final Class jarClass = classLoader.loadClass(pluginDescriptor.main()); 120 | return jarClass.asSubclass(Plugin.class); 121 | } catch (final ClassNotFoundException e) { 122 | throw new InvalidPluginException("Cannot find main class '" + pluginDescriptor.main() + "' in " + file.getName(), e); 123 | } catch (final ClassCastException e) { 124 | throw new InvalidPluginException("Main class '" + pluginDescriptor.main() + "' does not extend Plugin in " + file.getName(), e); 125 | } 126 | } 127 | 128 | private Plugin instantiatePlugin(final Class pluginClass, final PluginDescriptor pluginDescriptor, final JarFile file) throws InvalidPluginException { 129 | try { 130 | final Plugin plugin = pluginClass.getDeclaredConstructor().newInstance(); 131 | plugin.setPluginDescriptor(pluginDescriptor); 132 | final File plugin_folder = plugin.getPluginFolder(); 133 | final File configFile = new File(plugin_folder, "config.json"); 134 | if (!configFile.exists()) { 135 | copyDefaultConfig(file, configFile); 136 | } 137 | plugin.onEnable(); 138 | return plugin; 139 | } catch (final InstantiationException | IllegalAccessException e) { 140 | throw new InvalidPluginException("Failed to instantiate plugin class '" + pluginDescriptor.main() + "' in " + file.getName(), e); 141 | } catch (final InvocationTargetException e) { 142 | throw new InvalidPluginException("Invocation target exception while instantiating plugin class '" + pluginDescriptor.main() + "' in " + file.getName(), e); 143 | } catch (final NoSuchMethodException e) { 144 | throw new InvalidPluginException("No suitable constructor found for plugin class '" + pluginDescriptor.main() + "' in " + file.getName(), e); 145 | } 146 | } 147 | 148 | private void copyDefaultConfig(final JarFile jarFile, final File configFile) throws InvalidPluginException { 149 | final JarEntry configEntry = jarFile.getJarEntry("config.json"); 150 | if (configEntry == null) { 151 | //! Need to be change 152 | throw new InvalidPluginException("Default config.json not found in JAR"); 153 | } 154 | try (final InputStream input = jarFile.getInputStream(configEntry)) { 155 | Files.copy(input, configFile.toPath(), StandardCopyOption.REPLACE_EXISTING); 156 | } catch (IOException e) { 157 | throw new InvalidPluginException("Failed to copy default config.json", e); 158 | } 159 | } 160 | 161 | private void addPlugin(final Plugin plugin, final URLClassLoader classLoader) { 162 | this.plugins.add(plugin); 163 | this.pluginClassLoaders.put(plugin, classLoader); 164 | } 165 | 166 | private void closeClassLoader(final URLClassLoader classLoader) { 167 | if (classLoader != null) { 168 | try { 169 | classLoader.close(); 170 | } catch (final IOException e) { 171 | e.printStackTrace(); 172 | } 173 | } 174 | } 175 | 176 | private JsonObject inputStreamToJSON(final InputStream inputStream) { 177 | final Scanner s = new Scanner(inputStream).useDelimiter("\\A"); 178 | final String jsonString = s.hasNext() ? s.next() : ""; 179 | return JsonParser.parseString(jsonString).getAsJsonObject(); 180 | } 181 | 182 | public void unloadPlugin(final Plugin plugin) { 183 | plugin.onDisable(); 184 | final URLClassLoader classLoader = this.pluginClassLoaders.get(plugin); 185 | 186 | try { 187 | classLoader.close(); 188 | } catch (final IOException e) { 189 | e.printStackTrace(); 190 | } 191 | 192 | this.plugins.remove(plugin); 193 | this.pluginClassLoaders.remove(plugin); 194 | } 195 | 196 | public void reloadPlugin(final File file) { 197 | Plugin pluginToReload = null; 198 | for (final Plugin plugin : plugins) { 199 | if (plugin.getPluginDescriptor().name().equals(file.getName())) { 200 | pluginToReload = plugin; 201 | break; 202 | } 203 | } 204 | if (pluginToReload != null) { 205 | unloadPlugin(pluginToReload); 206 | } 207 | try { 208 | loadPlugin(file); 209 | } catch (final InvalidPluginException e) { 210 | e.printStackTrace(); 211 | } 212 | } 213 | 214 | public List getPlugins() { 215 | return this.plugins; 216 | } 217 | } 218 | -------------------------------------------------------------------------------- /src/main/java/fr/ordinalteam/bot/api/utils/OrdinalConstant.java: -------------------------------------------------------------------------------- 1 | package fr.ordinalteam.bot.api.utils; 2 | 3 | public class OrdinalConstant { 4 | 5 | public static final String APP_NAME = "OrdinalBot-API"; 6 | public static final String API_VERSION = "0.1.0"; 7 | } 8 | --------------------------------------------------------------------------------