diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..f3d281e --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,39 @@ +name: Publish to GitHub Packages + +on: + push: + branches: + - main + +jobs: + build-and-publish: + runs-on: ubuntu-latest + + permissions: + packages: write + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + - name: Set up JDK 17 + uses: actions/setup-java@v3 + with: + distribution: "zulu" + java-version: "17" + + - name: Grant execute permission for Gradlew + run: chmod +x gradlew + + - name: Build with Gradle + run: ./gradlew build + + - name: Publish to GitHub Packages + run: ./gradlew publish + env: + USERNAME: ${{ github.actor }} + TOKEN: ${{ secrets.GITHUB_TOKEN }} + GPG_KEY_ID: ${{ secrets.GPG_KEY_ID }} + GPG_KEY: ${{ secrets.GPG_KEY }} + GPG_KEY_PASSWORD: ${{ secrets.GPG_KEY_PASSWORD }} diff --git a/.gitignore b/.gitignore index 4788b4b..e2de805 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,24 @@ -# User-specific stuff -.idea/ +.gradle +**/build/ +!src/**/build/ -*.iml -*.ipr -*.iws +# Ignore Gradle GUI config +gradle-app.setting -# IntelliJ -out/ +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath # Compiled class file *.class @@ -17,6 +29,9 @@ out/ # BlueJ files *.ctxt +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + # Package Files # *.jar *.war @@ -28,86 +43,4 @@ out/ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* - -*~ - -# temporary files which can be created if a process still has a handle open of a deleted file -.fuse_hidden* - -# KDE directory preferences -.directory - -# Linux trash folder which might appear on any partition or disk -.Trash-* - -# .nfs files are created when an open file is removed but is still being accessed -.nfs* - -# General -.DS_Store -.AppleDouble -.LSOverride - -# Icon must end with two \r -Icon - -# Thumbnails -._* - -# Files that might appear in the root of a volume -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns -.com.apple.timemachine.donotpresent - -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk - -# Windows thumbnail cache files -Thumbs.db -Thumbs.db:encryptable -ehthumbs.db -ehthumbs_vista.db - -# Dump file -*.stackdump - -# Folder config file -[Dd]esktop.ini - -# Recycle Bin used on file shares -$RECYCLE.BIN/ - -# Windows Installer files -*.cab -*.msi -*.msix -*.msm -*.msp - -# Windows shortcuts -*.lnk - -target/ - -pom.xml.tag -pom.xml.releaseBackup -pom.xml.versionsBackup -pom.xml.next - -release.properties -dependency-reduced-pom.xml -buildNumber.properties -.mvn/timing.properties -.mvn/wrapper/maven-wrapper.jar -.flattened-pom.xml - -# Common working directory -run/ +replay_pid* \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index 1472dfe..66fd94b 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -4,6 +4,10 @@ "https://json.schemastore.org/bukkit-plugin.json": "file:///Users/shadow/Documents/Coding/KiaiMC/src/main/resources/plugin.yml" }, "cSpell.words": [ - "kiaimc" - ] + "addxp", + "gson", + "kiaimc", + "removexp" + ], + "java.jdt.ls.vmargs": "-XX:+UseParallelGC -XX:GCTimeRatio=4 -XX:AdaptiveSizePolicyWeight=90 -Dsun.zip.disableMemoryMapping=true -Xmx2G -Xms100m -Xlog:disable" } \ No newline at end of file diff --git a/README.md b/README.md index 83b491e..b8591e3 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,12 @@ KiaiMC is a simple plugin that enables players to receive XP in [Kiai](https://kiai.app) for their messages sent in-game. +There are three ways that players can receive XP + +1. Players can send messages in-game that will be converted into XP, just like Discord messages would +2. Every X seconds, the user will receive a fixed amount of XP. +3. Every X seconds, the user will receive a "bonus message", where they get the same amount of XP calculated as they would have received if they had sent a message, based on your settings in Kiai on Discord. + This plugin uses [DiscordSRV](https://modrinth.com/plugin/discordsrv) as the linking system between your Minecraft server and Discord server, so make sure that you have it installed and setup using the `linking.yml` file in DiscordSRV's configuration, and have a chat channel set within Discord. You can use the `global` channel you setup in DiscordSRV to add any multipliers or blacklists to in-game chat. User and role blacklists will be applied based on the Minecraft player's linked Discord account. @@ -23,3 +29,9 @@ We are working on a web dashboard to make this process automated, but in the mea - A unique ID (typically your bot's ID) - An application name + + +[KiaiMC] Sending request to https://api.kiai.app/v1/guild/1041045270659604701/virtual_message with body + + + diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..bcc6197 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,117 @@ +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar + +plugins { + id("java") + id("java-library") + id("maven-publish") + id("signing") + id("com.gradleup.shadow") version "8.3.0" +} + +repositories { + mavenCentral() + maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/") + maven("https://nexus.scarsz.me/content/groups/public/") + maven("https://papermc.io/repo/repository/maven-public/") + maven("https://repo1.maven.org/maven2/") + maven("https://repo.codemc.org/repository/maven-public/") +} + +dependencies { + compileOnly("com.discordsrv:discordsrv:1.28.0") + compileOnly("io.papermc.paper:paper-api:1.21.1-R0.1-SNAPSHOT") + implementation("commons-io:commons-io:2.16.1") + implementation("dev.jorel:commandapi-bukkit-shade:9.5.2") +} + +tasks.withType { + dependencies { + include(dependency("dev.jorel:commandapi-bukkit-shade:9.5.2")) + include(dependency("org.bstats:bstats-bukkit:3.0.3")) + } + + relocate("dev.jorel.commandapi", "com.buape.kiaimc.commandapi") +} + +tasks.named("shadowJar") { + archiveClassifier.set("") +} + +tasks.build { + dependsOn("shadowJar") +} + +group = "com.buape" +version = "2.0.0" +description = "KiaiMC - Integrating Kiai's extensive leveling system with Minecraft servers" + +java { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 +} + +publishing { + publications { + create("mavenJava") { + from(components["java"]) + + pom { + name.set("KiaiMC API") + description.set("KiaiMC - Integrating Kiai's extensive leveling system with Minecraft servers") + url.set("https://github.com/buape/kiaimc") + + licenses { + license { + name.set("GNU General Public License, Version 3.0") + url.set("https://www.gnu.org/licenses/gpl-3.0.html") + } + } + + developers { + developer { + id.set("buape") + name.set("Buape Studios") + email.set("support@buape.com") + } + developer { + id.set("thewilloftheshadow") + name.set("Shadow") + email.set("hi@shadowing.dev") + } + } + + scm { + connection.set("scm:git:git://github.com/buape/kiaimc.git") + developerConnection.set("scm:git:ssh://github.com:buape/kiaimc.git") + url.set("https://github.com/buape/kiaimc") + } + } + } + } + + repositories { + maven { + name = "GitHubPackages" + url = uri("https://maven.pkg.github.com/buape/kiaimc") + credentials { + username = System.getenv("USERNAME") + password = System.getenv("TOKEN") + } + } + } +} + +signing { + useInMemoryPgpKeys( + System.getenv("GPG_KEY_ID"), + System.getenv("GPG_KEY"), + System.getenv("GPG_KEY_PASSWORD") + ) + sign(publishing.publications["mavenJava"]) +} + +tasks.processResources { + filesMatching("plugin.yml") { + expand("version" to project.version) + } +} \ No newline at end of file diff --git a/gradle/gradle-daemon-jvm.properties b/gradle/gradle-daemon-jvm.properties new file mode 100644 index 0000000..63e5bbd --- /dev/null +++ b/gradle/gradle-daemon-jvm.properties @@ -0,0 +1,2 @@ +#This file is generated by updateDaemonJvm +toolchainVersion=21 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..ca86ffb --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,16 @@ +# This file was generated by the Gradle 'init' task. +# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format + +[versions] +com-discordsrv-discordsrv = "1.28.0" +com-fasterxml-jackson-core-jackson-databind = "2.17.1" +commons-io-commons-io = "2.16.1" +io-papermc-paper-paper-api = "1.20-R0.1-SNAPSHOT" +org-bstats-bstats-bukkit = "3.0.2" + +[libraries] +com-discordsrv-discordsrv = { module = "com.discordsrv:discordsrv", version.ref = "com-discordsrv-discordsrv" } +com-fasterxml-jackson-core-jackson-databind = { module = "com.fasterxml.jackson.core:jackson-databind", version.ref = "com-fasterxml-jackson-core-jackson-databind" } +commons-io-commons-io = { module = "commons-io:commons-io", version.ref = "commons-io-commons-io" } +io-papermc-paper-paper-api = { module = "io.papermc.paper:paper-api", version.ref = "io-papermc-paper-paper-api" } +org-bstats-bstats-bukkit = { module = "org.bstats:bstats-bukkit", version.ref = "org-bstats-bstats-bukkit" } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9355b41 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9b42019 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/pom.xml b/pom.xml deleted file mode 100644 index e458609..0000000 --- a/pom.xml +++ /dev/null @@ -1,145 +0,0 @@ - - - - - 4.0.0 - - com.buape - KiaiMC - 1.0.1 - jar - - KiaiMC - - - 17 - UTF-8 - - - - - - maven-clean-plugin - 3.3.2 - - - - auto-clean - initialize - - clean - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.13.0 - - ${java.version} - ${java.version} - - - - org.apache.maven.plugins - maven-shade-plugin - 3.5.3 - - - - org.bstats - com.buape.kiaimc.bstats - - - org.json - com.buape.kiaimc.json - - - - - - package - - shade - - - false - - - - - - - - src/main/resources - true - - - - - - - spigotmc-repo - https://hub.spigotmc.org/nexus/content/repositories/snapshots/ - - - - Scarsz-Nexus - https://nexus.scarsz.me/content/groups/public/ - - - - papermc - https://papermc.io/repo/repository/maven-public/ - - - - - - org.bstats - bstats-bukkit - 3.0.2 - compile - - - com.discordsrv - discordsrv - 1.27.0 - provided - - - io.papermc.paper - paper-api - 1.20-R0.1-SNAPSHOT - provided - - - commons-io - commons-io - 2.16.1 - - - com.fasterxml.jackson.core - jackson-databind - 2.17.1 - - - \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..5118e7c --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,5 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +rootProject.name = "KiaiMC" diff --git a/src/main/java/com/buape/kiaimc/KiaiMC.java b/src/main/java/com/buape/kiaimc/KiaiMC.java index e6dffbf..58f9e3d 100644 --- a/src/main/java/com/buape/kiaimc/KiaiMC.java +++ b/src/main/java/com/buape/kiaimc/KiaiMC.java @@ -5,30 +5,25 @@ import java.util.logging.Logger; import org.apache.commons.io.FileUtils; -import org.bstats.bukkit.Metrics; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.util.HashMap; +import com.buape.kiaimc.api.Kiai; +import com.buape.kiaimc.modules.BonusMessageModule; +import com.buape.kiaimc.modules.ChatModule; +import com.buape.kiaimc.modules.CommandModule; +import com.buape.kiaimc.modules.PlayTimeModule; -import com.buape.kiaimc.listeners.AsyncChatListener; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import github.scarsz.discordsrv.DiscordSRV; -import github.scarsz.discordsrv.dependencies.jda.api.entities.Guild; -import github.scarsz.discordsrv.dependencies.jda.api.entities.Member; +import dev.jorel.commandapi.CommandAPI; +import dev.jorel.commandapi.CommandAPIBukkitConfig; +import dev.jorel.commandapi.CommandAPILogger; +import github.scarsz.discordsrv.dependencies.bstats.bukkit.Metrics; public final class KiaiMC extends JavaPlugin { public final Logger logger = this.getLogger(); - public final int currentConfig = 1; - private String token; + public final int currentConfig = 2; + public Kiai api; @Override public void onEnable() { @@ -36,82 +31,41 @@ public void onEnable() { if (configIsValid) { getConfig().options().copyDefaults(); saveDefaultConfig(); - new Metrics(this, 18414); - this.token = getConfig().getString("token"); - if (this.token.isBlank()) { + String token = getConfig().getString("token"); + + if (token == null || token.isBlank()) { logger.severe("No token was supplied for the Kiai API, stopping KiaiMC."); Bukkit.getPluginManager().disablePlugin(this); + return; } - getServer().getPluginManager().registerEvents(new AsyncChatListener(this), this); - } - } - - public void triggerMessage(String guildId, String userId, String channelId) { - Guild mainGuild = DiscordSRV.getPlugin().getMainGuild(); - - Member guildMember = mainGuild.getMemberById(userId); - - // Channel ID - HashMap channel = new HashMap<>(); - channel.put("id", channelId); - - // Member ID - HashMap member = new HashMap<>(); - member.put("id", userId); - - // Role list - HashMap role = new HashMap<>(); - guildMember.getRoles().forEach(r -> role.put("id", r.getId())); - - // Add roles to member - member.put("roles", new HashMap[] { role }); - - // Guild ID - HashMap guild = new HashMap<>(); - guild.put("id", guildId); + this.api = new Kiai(token, this.logger, this.getConfig().getBoolean("debug")); - // Combine them together - HashMap jsonMap = new HashMap<>(); - jsonMap.put("channel", channel); - jsonMap.put("member", member); - jsonMap.put("guild", guild); - - var objectMapper = new ObjectMapper(); - String requestBody; - try { - requestBody = objectMapper - .writeValueAsString(jsonMap); - - this.debug("Sending request with body from DiscordSRV data: " + requestBody); - - HttpClient client = HttpClient.newHttpClient(); - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create("https://api.kiai.app/v1/guild/" + guildId + "/virtual_message")) - .header("Authorization", this.token) - .header("Content-Type", "application/json") - .POST(HttpRequest.BodyPublishers.ofString(requestBody)) - .build(); - - HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); - - if (response.statusCode() == 401 || response.statusCode() == 403) { - this.logger.warning( - "Your API token is not authorized in guild " + mainGuild + " (ID received from DiscordSRV)"); + if (getConfig().getBoolean("chat.enabled")) { + getServer().getPluginManager().registerEvents(new ChatModule(this), this); + } + if (getConfig().getBoolean("bonus-message.enabled")) { + new BonusMessageModule(this); + } + if (getConfig().getBoolean("playtime-xp.enabled")) { + new PlayTimeModule(this); } - this.debug( - "Response with DiscordSRV data: " + response.body() + " and status code " + response.statusCode()); - } catch (JsonProcessingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); + CommandAPI.onEnable(); + new CommandModule(this).registerAllCommands(); } + } + @Override + public void onLoad() { + CommandAPI.setLogger(CommandAPILogger.fromJavaLogger(getLogger())); + CommandAPI.onLoad( + new CommandAPIBukkitConfig(this) + .verboseOutput(this.getConfig().getBoolean("debug")) + .usePluginNamespace() + .dispatcherFile(new File(getDataFolder(), "command_registration.json"))); } @Override @@ -143,7 +97,6 @@ public Boolean checkConfig() { this.logger.severe( "Your config is outdated, but I could not move your old config to a backup or copy in the new config format."); } - } this.logger.severe( @@ -163,5 +116,4 @@ public void debug(String message) { this.logger.info(message); } } - } \ No newline at end of file diff --git a/src/main/java/com/buape/kiaimc/api/Kiai.java b/src/main/java/com/buape/kiaimc/api/Kiai.java new file mode 100644 index 0000000..702a84b --- /dev/null +++ b/src/main/java/com/buape/kiaimc/api/Kiai.java @@ -0,0 +1,71 @@ +package com.buape.kiaimc.api; + +import java.util.HashMap; +import java.util.concurrent.CompletableFuture; +import java.util.logging.Logger; + +import github.scarsz.discordsrv.dependencies.jda.api.entities.Member; + +public class Kiai { + private final Logger logger; + private final Boolean debug; + private final RequestQueueManager requestQueueManager; + + public Kiai(String token, Logger logger, Boolean debug) { + this.logger = logger; + this.debug = debug; + this.requestQueueManager = new RequestQueueManager(logger, token, debug); + } + + public void debug(String message) { + if (this.debug) { + this.logger.info(message); + } + } + + public void virtualMessage(String guildId, String channelId, Member guildMember, String channelParentId) { + HashMap channel = new HashMap<>(); + channel.put("id", channelId); + channel.put("parentId", channelParentId); + + HashMap member = new HashMap<>(); + member.put("id", guildMember.getId()); + + HashMap role = new HashMap<>(); + guildMember.getRoles().forEach(r -> role.put("id", r.getId())); + + member.put("roles", new HashMap[] { role }); + + HashMap guild = new HashMap<>(); + guild.put("id", guildId); + + HashMap jsonMap = new HashMap<>(); + jsonMap.put("channel", channel); + jsonMap.put("member", member); + jsonMap.put("guild", guild); + + requestQueueManager.queueRequest("/guild/" + guildId + "/virtual_message", "POST", jsonMap); + } + + public void addXp(String guildId, String userId, int amount) { + HashMap jsonMap = new HashMap<>(); + jsonMap.put("xp", amount); + + requestQueueManager.queueRequest("/guild/" + guildId + "/member/" + userId + "/xp", "PATCH", jsonMap); + } + + public void removeXp(String guildId, String userId, int amount) { + HashMap jsonMap = new HashMap<>(); + jsonMap.put("xp", amount); + jsonMap.put("remove", true); + + requestQueueManager.queueRequest("/guild/" + guildId + "/member/" + userId + "/xp", "PATCH", jsonMap); + } + + public CompletableFuture getUser(String guildId, String userId) { + HashMap jsonMap = new HashMap<>(); + jsonMap.put("user", userId); + + return requestQueueManager.queueRequest("/guild/" + guildId + "/member/" + userId + "/xp", "GET", jsonMap); + } +} \ No newline at end of file diff --git a/src/main/java/com/buape/kiaimc/api/RequestQueueManager.java b/src/main/java/com/buape/kiaimc/api/RequestQueueManager.java new file mode 100644 index 0000000..c2d6ec4 --- /dev/null +++ b/src/main/java/com/buape/kiaimc/api/RequestQueueManager.java @@ -0,0 +1,113 @@ +package com.buape.kiaimc.api; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.Queue; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.CompletableFuture; +import java.util.logging.Logger; +import com.google.gson.Gson; + +public class RequestQueueManager { + private final HttpClient client; + private final Logger logger; + private final String token; + private final ScheduledExecutorService executorService; + private final Queue requestQueue = new LinkedList<>(); + private final Boolean debug; + private final Gson gson; + + public RequestQueueManager(Logger logger, String token, Boolean debug) { + this.client = HttpClient.newHttpClient(); + this.logger = logger; + this.token = token; + this.debug = debug; + this.executorService = Executors.newSingleThreadScheduledExecutor(); + this.gson = new Gson(); + } + + public CompletableFuture queueRequest(String endpoint, String method, HashMap requestBody) { + CompletableFuture future = new CompletableFuture<>(); + requestQueue.add(new QueuedRequest(endpoint, method, requestBody, future)); + executeNextRequest(); + return future; + } + + private void executeNextRequest() { + if (!requestQueue.isEmpty()) { + QueuedRequest queuedRequest = requestQueue.poll(); + executorService.submit(() -> { + try { + HttpResponse response = sendRequest(queuedRequest); + handleResponse(response, queuedRequest); + } catch (IOException | InterruptedException e) { + queuedRequest.future.completeExceptionally(e); + e.printStackTrace(); + } + }); + } + } + + private HttpResponse sendRequest(QueuedRequest queuedRequest) throws IOException, InterruptedException { + String jsonBody = gson.toJson(queuedRequest.requestBody); + + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://api.kiai.app/v1" + queuedRequest.endpoint)) + .header("Authorization", this.token) + .header("Content-Type", "application/json") + .method(queuedRequest.method, HttpRequest.BodyPublishers.ofString(jsonBody)) + .build(); + + debug(String.format("Sending request to %s with body %s", request.uri(), jsonBody)); + + return this.client.send(request, HttpResponse.BodyHandlers.ofString()); + } + + private void handleResponse(HttpResponse response, QueuedRequest queuedRequest) { + if (response.statusCode() == 401 || response.statusCode() == 403) { + this.logger.warning( + "Your Kiai API token is not authorized, please use the /application authorize command from Kiai in Discord to authorize your bot."); + queuedRequest.future.completeExceptionally(new RuntimeException("Unauthorized")); + return; + } + + if (response.statusCode() == 429) { + this.logger.warning("Kiai rate limit hit. Retrying in 5 seconds..."); + requestQueue.add(queuedRequest); + executorService.schedule(this::executeNextRequest, 5, TimeUnit.SECONDS); + return; + } + + debug("Response with data: " + response.body() + " and status code " + response.statusCode()); + queuedRequest.future.complete(response.body()); + executeNextRequest(); + } + + private void debug(String message) { + if (this.debug) { + this.logger.info(message); + } + } + + private static class QueuedRequest { + private String endpoint; + private String method; + private HashMap requestBody; + private CompletableFuture future; + + private QueuedRequest(String endpoint, String method, HashMap requestBody, + CompletableFuture future) { + this.endpoint = endpoint; + this.method = method; + this.requestBody = requestBody; + this.future = future; + } + } +} \ No newline at end of file diff --git a/src/main/java/com/buape/kiaimc/modules/BonusMessageModule.java b/src/main/java/com/buape/kiaimc/modules/BonusMessageModule.java new file mode 100644 index 0000000..6e736f9 --- /dev/null +++ b/src/main/java/com/buape/kiaimc/modules/BonusMessageModule.java @@ -0,0 +1,47 @@ +package com.buape.kiaimc.modules; + +import org.bukkit.event.Listener; + +import com.buape.kiaimc.KiaiMC; + +import github.scarsz.discordsrv.DiscordSRV; +import github.scarsz.discordsrv.dependencies.jda.api.entities.Guild; +import github.scarsz.discordsrv.dependencies.jda.api.entities.Member; +import github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel; +import github.scarsz.discordsrv.objects.managers.AccountLinkManager; + +public class BonusMessageModule implements Listener { + private final KiaiMC plugin; + + public BonusMessageModule(KiaiMC kiaiMC) { + this.plugin = kiaiMC; + + int interval = plugin.getConfig().getInt("bonus-message.interval"); + + plugin.getServer().getScheduler().runTaskTimer(plugin, this::checkBonusMessage, interval * 20, interval * 20); + + this.plugin.debug(String + .format("Bonus message module has been enabled, will give a bonus message every %s seconds", interval)); + } + + public void disable() { + plugin.getServer().getScheduler().cancelTasks(plugin); + } + + public void checkBonusMessage() { + plugin.debug("Checking for bonus message"); + plugin.getServer().getOnlinePlayers().forEach(player -> { + plugin.debug("Checking player " + player.getName()); + TextChannel channel = DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName("global"); + Guild mainGuild = DiscordSRV.getPlugin().getMainGuild(); + AccountLinkManager accountLinkManager = DiscordSRV.getPlugin().getAccountLinkManager(); + String discordPlayerId = accountLinkManager.getDiscordId(player.getUniqueId()); + if (discordPlayerId == null || discordPlayerId.isBlank()) { + plugin.debug("Player " + player.getName() + " is not linked, not processing bonus message"); + return; + } + Member guildMember = mainGuild.getMemberById(discordPlayerId); + plugin.api.virtualMessage(mainGuild.getId(), channel.getId(), guildMember, channel.getParent().getId()); + }); + } +} \ No newline at end of file diff --git a/src/main/java/com/buape/kiaimc/listeners/AsyncChatListener.java b/src/main/java/com/buape/kiaimc/modules/ChatModule.java similarity index 63% rename from src/main/java/com/buape/kiaimc/listeners/AsyncChatListener.java rename to src/main/java/com/buape/kiaimc/modules/ChatModule.java index 8f49a43..18ca09e 100644 --- a/src/main/java/com/buape/kiaimc/listeners/AsyncChatListener.java +++ b/src/main/java/com/buape/kiaimc/modules/ChatModule.java @@ -1,4 +1,4 @@ -package com.buape.kiaimc.listeners; +package com.buape.kiaimc.modules; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -9,16 +9,19 @@ import github.scarsz.discordsrv.DiscordSRV; import github.scarsz.discordsrv.dependencies.jda.api.entities.Guild; +import github.scarsz.discordsrv.dependencies.jda.api.entities.Member; import github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel; import github.scarsz.discordsrv.objects.managers.AccountLinkManager; import io.papermc.paper.event.player.AsyncChatEvent; -public class AsyncChatListener implements Listener { +public class ChatModule implements Listener { - private final KiaiMC kiaiMC; + private final KiaiMC plugin; - public AsyncChatListener(KiaiMC kiaiMC) { - this.kiaiMC = kiaiMC; + public ChatModule(KiaiMC kiaiMC) { + this.plugin = kiaiMC; + + this.plugin.debug("Chat module has been enabled"); } @EventHandler(priority = EventPriority.MONITOR) @@ -31,12 +34,12 @@ public void onAsyncPlayerChat(AsyncChatEvent event) { String discordPlayerId = accountLinkManager.getDiscordId(player.getUniqueId()); if (discordPlayerId == null || discordPlayerId.isBlank()) { - this.kiaiMC - .debug("Player " + player.getName() + " is not linked, not processing Kiai XP through DiscordSRV."); + plugin.debug("Player " + player.getName() + " is not linked, not processing Kiai XP through DiscordSRV."); } else { - this.kiaiMC.debug("Player " + player.getName() + " is linked to " + discordPlayerId + plugin.debug("Player " + player.getName() + " is linked to " + discordPlayerId + ", processing Kiai XP through DiscordSRV. (Guild ID: " + mainGuild.getId() + ")"); - this.kiaiMC.triggerMessage(mainGuild.getId(), discordPlayerId, channel.getId()); + Member guildMember = mainGuild.getMemberById(discordPlayerId); + plugin.api.virtualMessage(mainGuild.getId(), channel.getId(), guildMember, channel.getParent().getId()); } } diff --git a/src/main/java/com/buape/kiaimc/modules/CommandModule.java b/src/main/java/com/buape/kiaimc/modules/CommandModule.java new file mode 100644 index 0000000..e1de989 --- /dev/null +++ b/src/main/java/com/buape/kiaimc/modules/CommandModule.java @@ -0,0 +1,67 @@ +package com.buape.kiaimc.modules; + +import org.bukkit.entity.Player; + +import com.buape.kiaimc.KiaiMC; + +import dev.jorel.commandapi.CommandAPI; +import dev.jorel.commandapi.CommandAPICommand; +import dev.jorel.commandapi.arguments.PlayerArgument; +import dev.jorel.commandapi.arguments.IntegerArgument; +import github.scarsz.discordsrv.DiscordSRV; +import net.md_5.bungee.api.ChatColor; + +public class CommandModule { + private final KiaiMC plugin; + + public CommandModule(KiaiMC plugin) { + this.plugin = plugin; + } + + public void registerAllCommands() { + new CommandAPICommand("addxp") + .withArguments(new PlayerArgument("player")) + .withArguments(new IntegerArgument("amount")) + .withHelp("Add XP to a player", "Add XP in Kiai to player through Minecraft") + .withUsage("/addxp ") + .executes((sender, args) -> { + Player player = (Player) args.get("player"); + int amount = (int) args.get("amount"); + String discordId = DiscordSRV.getPlugin().getAccountLinkManager() + .getDiscordId(player.getUniqueId()); + if (discordId == null || discordId.isBlank()) { + throw CommandAPI.failWithString( + String.format("%s is not linked to a Discord account!", player.getName())); + } + plugin.api.addXp(DiscordSRV.getPlugin().getMainGuild().getId(), player.getUniqueId().toString(), + amount); + if (sender instanceof Player) { + sender.sendMessage( + ChatColor.GREEN + "You have given " + player.getName() + " " + amount + " XP"); + } + }).register(); + + new CommandAPICommand("removexp") + .withArguments(new PlayerArgument("player")) + .withArguments(new IntegerArgument("amount")) + .withHelp("Remove XP from a player", "Remove XP in Kiai from player through Minecraft") + .withUsage("/removexp ") + .executes((sender, args) -> { + Player player = (Player) args.get("player"); + int amount = (int) args.get("amount"); + String discordId = DiscordSRV.getPlugin().getAccountLinkManager() + .getDiscordId(player.getUniqueId()); + if (discordId == null || discordId.isBlank()) { + throw CommandAPI.failWithString( + String.format("%s is not linked to a Discord account!", player.getName())); + } + plugin.api.removeXp(DiscordSRV.getPlugin().getMainGuild().getId(), player.getUniqueId() + .toString(), amount); + if (sender instanceof Player) { + sender.sendMessage(net.md_5.bungee.api.ChatColor.GREEN + "You have taken " + amount + + " XP from " + player.getName()); + } + }).register(); + } + +} diff --git a/src/main/java/com/buape/kiaimc/modules/PlayTimeModule.java b/src/main/java/com/buape/kiaimc/modules/PlayTimeModule.java new file mode 100644 index 0000000..664a8bc --- /dev/null +++ b/src/main/java/com/buape/kiaimc/modules/PlayTimeModule.java @@ -0,0 +1,44 @@ +package com.buape.kiaimc.modules; + +import com.buape.kiaimc.KiaiMC; + +import github.scarsz.discordsrv.DiscordSRV; +import github.scarsz.discordsrv.dependencies.jda.api.entities.Guild; +import github.scarsz.discordsrv.objects.managers.AccountLinkManager; + +public class PlayTimeModule { + private final KiaiMC plugin; + + public PlayTimeModule(KiaiMC plugin) { + this.plugin = plugin; + + int interval = plugin.getConfig().getInt("playtime-xp.interval"); + int amount = plugin.getConfig().getInt("playtime-xp.amount"); + + plugin.getServer().getScheduler().runTaskTimer(plugin, this::playTimeXp, interval * 20, interval * 20); + + this.plugin.debug( + String.format("Playtime XP module has been enabled, will give %s xp every %s seconds", amount, + interval)); + } + + public void disable() { + plugin.getServer().getScheduler().cancelTasks(plugin); + } + + public void playTimeXp() { + plugin.debug("Checking for playtime XP"); + plugin.getServer().getOnlinePlayers().forEach(player -> { + plugin.debug("Checking player " + player.getName()); + Guild mainGuild = DiscordSRV.getPlugin().getMainGuild(); + AccountLinkManager accountLinkManager = DiscordSRV.getPlugin().getAccountLinkManager(); + String discordPlayerId = accountLinkManager.getDiscordId(player.getUniqueId()); + if (discordPlayerId == null || discordPlayerId.isBlank()) { + plugin.debug("Player " + player.getName() + " is not linked, not processing playtime XP"); + return; + } + plugin.api.addXp(mainGuild.getId(), discordPlayerId, plugin.getConfig().getInt("playtime-xp.amount")); + }); + } + +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index ac29a58..f8fd3b0 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -3,7 +3,30 @@ # See https://docs.kiai.app/features/api for more information on how to get this token: "" +# There are three ways that players can receive XP +# 1. Players can send messages in-game that will be converted into XP, just like Discord messages would +# 2. Every X seconds, the user will receive a fixed amount of XP. +# 3. Every X seconds, the user will receive a "bonus message", where they get the same amount of XP calculated as they would have received if they had sent a message, based on your settings in Kiai on Discord. + +chat: + # Whether or not to enable the chat module + enabled: true + +playtime-xp: + # Whether or not to enable the playtime XP mode + enabled: false + # The number of seconds between each xp award + interval: 300 + # The amount of XP to award + amount: 1 + +bonus-message: + # Whether or not to enable the bonus message mode + enabled: false + # The number of seconds between each bonus message + interval: 300 + # Debug mode debug: false # DO NOT MANUALLY CHANGE THIS -config-version: 1 +config-version: 2 diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index adfae9b..f29bc7f 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,9 +1,9 @@ name: KiaiMC -version: ${project.version} +version: ${version} main: com.buape.kiaimc.KiaiMC api-version: 1.20 author: thewilloftheshadow depend: [DiscordSRV] load: POSTWORLD website: "https://github.com/buape/KiaiMC" -description: Synchronize your in-game messages with Kiai's XP +description: Synchronize your in-game messages and playtime with Kiai's XP