diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6783f77..bd17a6c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,21 +1,38 @@ name: Build on: + push: + branches: [ "develop", "hotfix/**" ] pull_request: - branches: - - main - - develop + branches: [ "develop", "hotfix/**" ] + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true jobs: build: + + name: 🏗️ Build TurnipTales Discord Bot runs-on: ubuntu-latest + steps: - - uses: actions/checkout@v3 - - name: Set up JDK 17 - uses: actions/setup-java@v3 + - uses: actions/checkout@v4 with: - distribution: 'corretto' - java-version: '17' + fetch-depth: 0 + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' cache: maven + + - name: Set application properties + env: + DISCORD_BOT_TOKEN: ${{ secrets.DISCORD_BOT_TOKEN }} + run: | + echo "discord.bot.token=$DISCORD_BOT_TOKEN" >> src/main/resources/application.properties + - name: Build with Maven - run: mvn -B package --file pom.xml \ No newline at end of file + run: mvn -B test package --file pom.xml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f1cf653..1bc6b72 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,24 +2,57 @@ name: Release on: push: - branches: - - main + branches: [ "main" ] jobs: release: + + name: 🎉 Release TurnipTales Discord Bot runs-on: ubuntu-latest + steps: - - uses: actions/checkout@v3 - - name: Set up JDK 17 - uses: actions/setup-java@v3 + - uses: actions/checkout@v4 with: - distribution: 'corretto' - java-version: '17' + fetch-depth: 0 + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' cache: maven + + - name: Set application properties + env: + DISCORD_BOT_TOKEN: ${{ secrets.DISCORD_BOT_TOKEN }} + run: | + echo "discord.bot.token=$DISCORD_BOT_TOKEN" >> src/main/resources/application.properties + - name: Build with Maven - run: mvn -B package --file pom.xml - - name: Upload Artifact - uses: actions/upload-artifact@v3 + run: mvn -B test package --file pom.xml + + - if: github.event_name == 'push' + name: Upload via SCP + uses: appleboy/scp-action@v0.1.7 + with: + host: turniptales.net + username: ${{ secrets.USERNAME }} + key: ${{ secrets.KEY }} + port: 22 + source: "target/turniptales-discord.jar" + target: "/home/discord" + timeout: 120s + strip_components: 1 + + - if: github.event_name == 'push' + name: Restart TurnipTales API + uses: appleboy/ssh-action@v1.0.3 with: - name: Artifacts - path: target/discord-1.0.0.jar \ No newline at end of file + host: turniptales.net + username: ${{ secrets.USERNAME }} + key: ${{ secrets.KEY }} + port: 22 + script: | + cd /home/discord + chown -R root:root turniptales-discord.jar + ./run.sh diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index b7cb93e..f95f1ee 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -1,2 +1,19 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# http://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. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.8/apache-maven-3.9.8-bin.zip diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index d76a4c7..0000000 --- a/Dockerfile +++ /dev/null @@ -1,7 +0,0 @@ -FROM openjdk:17 - -WORKDIR /app - -COPY discord.jar /app/discord.jar - -CMD ["java", "-jar", "discord.jar"] \ No newline at end of file diff --git a/mvnw b/mvnw index 8a8fb22..19529dd 100644 --- a/mvnw +++ b/mvnw @@ -8,7 +8,7 @@ # "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 +# http://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 @@ -19,298 +19,241 @@ # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- -# Maven Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir +# Apache Maven Wrapper startup batch script, version 3.3.2 # # Optional ENV vars # ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output # ---------------------------------------------------------------------------- -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /usr/local/etc/mavenrc ] ; then - . /usr/local/etc/mavenrc - fi - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac -fi +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + 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" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 fi fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" +} - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" done + printf %x\\n $h +} - saveddir=`pwd` +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } - M2_HOME=`dirname "$PRG"`/.. +die() { + printf %s\\n "$1" >&2 + exit 1 +} - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" fi -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac -if [ -z "$JAVACMD" ] ; then - 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 - else - JAVACMD="`\\unset -f command; \\command -v java`" - fi +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" fi -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi +mkdir -p -- "${MAVEN_HOME%/*}" -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" fi -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; fi -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" -exec "$JAVACMD" \ - $MAVEN_OPTS \ - $MAVEN_DEBUG_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" \ - "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" +clean || : +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd index 1d8ab01..b150b91 100644 --- a/mvnw.cmd +++ b/mvnw.cmd @@ -1,188 +1,149 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. 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, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* -if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" - -FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% ^ - %JVM_CONFIG_MAVEN_PROPS% ^ - %MAVEN_OPTS% ^ - %MAVEN_DEBUG_OPTS% ^ - -classpath %WRAPPER_JAR% ^ - "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ - %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" -if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%"=="on" pause - -if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% - -cmd /C exit /B %ERROR_CODE% +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml index 2fdd400..0e87cfc 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.springframework.boot spring-boot-starter-parent - 3.1.4 + 3.3.1 @@ -14,12 +14,13 @@ 1.0.0 jar - Discord + TurnipTales-Discord Discord application of TurnipTales - 17 - 17 + 21 + 21 + UTF-8 @@ -36,24 +37,18 @@ spring-boot-starter-webflux - - org.apache.tomcat.embed - tomcat-embed-core - 11.0.0-M15 - - com.google.code.gson gson - 2.10.1 + 2.11.0 net.dv8tion JDA - 5.0.0-alpha.21 + 5.0.1 @@ -69,15 +64,18 @@ 1.1.1 + org.projectlombok lombok + 1.18.34 + provided true - discord + turniptales-discord org.springframework.boot @@ -86,5 +84,4 @@ - diff --git a/src/main/java/net/turniptales/discord/Application.java b/src/main/java/net/turniptales/discord/Application.java deleted file mode 100644 index be85a42..0000000 --- a/src/main/java/net/turniptales/discord/Application.java +++ /dev/null @@ -1,69 +0,0 @@ -package net.turniptales.discord; - -import lombok.extern.log4j.Log4j2; -import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.JDABuilder; -import net.turniptales.discord.commands.StatsCommand; -import net.turniptales.discord.commands.TicketCommand; -import net.turniptales.discord.commands.VerifyCommand; -import net.turniptales.discord.events.GuildBanEventHandler; -import net.turniptales.discord.events.GuildMemberJoinEventHandler; -import net.turniptales.discord.events.GuildMemberRemoveEventHandler; -import net.turniptales.discord.events.TicketEventHandler; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -import static java.lang.System.currentTimeMillis; -import static net.dv8tion.jda.api.interactions.commands.OptionType.STRING; -import static net.dv8tion.jda.api.requests.GatewayIntent.GUILD_MEMBERS; -import static net.dv8tion.jda.api.requests.GatewayIntent.MESSAGE_CONTENT; -import static net.dv8tion.jda.api.utils.Compression.NONE; -import static net.dv8tion.jda.api.utils.cache.CacheFlag.MEMBER_OVERRIDES; -import static net.dv8tion.jda.api.utils.cache.CacheFlag.VOICE_STATE; - -@Log4j2 -@SpringBootApplication -public class Application implements WebMvcConfigurer { - - public static JDA TURNIPTALES_BOT; - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - - long discordBotStartTime = currentTimeMillis(); - log.info("Discord bot starting"); - startDiscordBot(); - log.info("Discord bot started in {}ms", currentTimeMillis() - discordBotStartTime); - } - - private static void startDiscordBot() { - TURNIPTALES_BOT = JDABuilder - .createDefault("MTE5MDcxNDY0MzU1MTg5MTQ3OA.GdvTJE.EMI9oOxjzEe-unfAXWPtOKgb2qGtWkqonPq5OY") - .disableCache(MEMBER_OVERRIDES, VOICE_STATE) // Disable parts of the cache - .setBulkDeleteSplittingEnabled(false) // Enable the bulk delete event - .setCompression(NONE) // Disable compression (not recommended) - .enableIntents(MESSAGE_CONTENT) - .enableIntents(GUILD_MEMBERS) - .addEventListeners(new TicketCommand(), new VerifyCommand(), new StatsCommand()) - .addEventListeners(new GuildMemberJoinEventHandler()) - .addEventListeners(new GuildMemberRemoveEventHandler()) - .addEventListeners(new GuildBanEventHandler()) - .addEventListeners(new TicketEventHandler()) - .build(); - - TURNIPTALES_BOT - .upsertCommand("ticket", "Erstellt die Nachricht um Tickets zu erstellen") - .queue(); - - TURNIPTALES_BOT - .upsertCommand("verify", "Verifiziert deinen Minecraft Account") - .addOption(STRING, "code", "Verifizierungscode", true) - .queue(); - - TURNIPTALES_BOT - .upsertCommand("stats", "Statistiken eines Nutzers") - .addOption(STRING, "player", "Spielername", true) - .queue(); - } -} diff --git a/src/main/java/net/turniptales/discord/Config.java b/src/main/java/net/turniptales/discord/Config.java deleted file mode 100644 index 30b429d..0000000 --- a/src/main/java/net/turniptales/discord/Config.java +++ /dev/null @@ -1,38 +0,0 @@ -package net.turniptales.discord; - -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Role; -import net.dv8tion.jda.api.entities.channel.concrete.Category; -import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; - -import static net.turniptales.discord.Application.TURNIPTALES_BOT; - -public class Config { - - public static final Guild GUILD = TURNIPTALES_BOT.getGuildById("1008928645185810463"); - public static final Member BOT; - // channels - public static final TextChannel SYSTEM_TEXT_CHANNEL = GUILD.getSystemChannel(); - public static final TextChannel TICKET_TEXT_CHANNEL = GUILD.getTextChannelById("1009477703990267954"); - // - public static final Category TICKET_CATEGORY = GUILD.getCategoryById("1009478372847517727"); - // team roles - public static final Role MODERATOR_ROLE = GUILD.getRoleById("1025864289346658355"); - public static final Role SUPPORTER_ROLE = GUILD.getRoleById("1009477020427747408"); - // user time roles - public static final Role ROLE_0 = GUILD.getRoleById("1134487019058372649"); - public static final Role ROLE_1_WEEK = GUILD.getRoleById("1134487221349650462"); - public static final Role ROLE_2_WEEK = GUILD.getRoleById("1134487277205192744"); - public static final Role ROLE_1_MONTH = GUILD.getRoleById("1134487413125820477"); - public static final Role ROLE_3_MONTH = GUILD.getRoleById("1134487461452583043"); - public static final Role ROLE_6_MONTH = GUILD.getRoleById("1134487539588268094"); - public static final Role ROLE_1_YEAR = GUILD.getRoleById("1134487593585745920"); - public static final Role ROLE_2_YEAR = GUILD.getRoleById("1134487644110336010"); - public static final Role ROLE_3_YEAR = GUILD.getRoleById("1134487702864142356"); - - static { - assert GUILD != null; - BOT = GUILD.getMemberById("1033057310605586533"); - } -} diff --git a/src/main/java/net/turniptales/discord/TurnipTalesDiscord.java b/src/main/java/net/turniptales/discord/TurnipTalesDiscord.java new file mode 100644 index 0000000..8662e14 --- /dev/null +++ b/src/main/java/net/turniptales/discord/TurnipTalesDiscord.java @@ -0,0 +1,115 @@ +package net.turniptales.discord; + +import lombok.extern.log4j.Log4j2; +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.JDABuilder; +import net.dv8tion.jda.api.interactions.commands.build.Commands; +import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; +import net.turniptales.discord.buttons.GiveawayWinnerPublishButton; +import net.turniptales.discord.buttons.SyncButton; +import net.turniptales.discord.buttons.TicketCloseAbortButton; +import net.turniptales.discord.buttons.TicketCloseButton; +import net.turniptales.discord.buttons.TicketCloseConfirmButton; +import net.turniptales.discord.buttons.TicketCreateButton; +import net.turniptales.discord.commands.GiveawayCommand; +import net.turniptales.discord.commands.MessageCommand; +import net.turniptales.discord.commands.RolesCommand; +import net.turniptales.discord.commands.StatsCommand; +import net.turniptales.discord.commands.SyncPermissionCommand; +import net.turniptales.discord.common.api.Api; +import net.turniptales.discord.common.configuration.DiscordBotProperties; +import net.turniptales.discord.events.GuildAccessListener; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.time.ZoneId; + +import static java.lang.System.currentTimeMillis; +import static java.time.ZoneId.of; +import static net.dv8tion.jda.api.Permission.ADMINISTRATOR; +import static net.dv8tion.jda.api.Permission.VIEW_AUDIT_LOGS; +import static net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions.enabledFor; +import static net.dv8tion.jda.api.interactions.commands.OptionType.STRING; +import static net.dv8tion.jda.api.interactions.commands.OptionType.USER; +import static net.dv8tion.jda.api.requests.GatewayIntent.GUILD_MEMBERS; +import static net.dv8tion.jda.api.requests.GatewayIntent.MESSAGE_CONTENT; +import static net.dv8tion.jda.api.utils.Compression.NONE; +import static net.dv8tion.jda.api.utils.cache.CacheFlag.MEMBER_OVERRIDES; +import static net.dv8tion.jda.api.utils.cache.CacheFlag.VOICE_STATE; + +@Log4j2 +@SpringBootApplication +public class TurnipTalesDiscord implements WebMvcConfigurer { + + public static final ZoneId ZONE_ID = of("Europe/Berlin"); + public static JDA discordBot; + public static DiscordBotProperties discordBotProperties; + public static Api api; + + public static void main(String[] args) throws InterruptedException { + ConfigurableApplicationContext context = SpringApplication.run(TurnipTalesDiscord.class, args); + + discordBotProperties = context.getBean(DiscordBotProperties.class); + + long discordBotStartTime = currentTimeMillis(); + log.info("Discord bot starting"); + startDiscordBot(); + log.info("Discord bot started in {}ms", currentTimeMillis() - discordBotStartTime); + + api = new Api(); + } + + private static void startDiscordBot() throws InterruptedException { + discordBot = JDABuilder + .createDefault(discordBotProperties.getToken()) + .disableCache(MEMBER_OVERRIDES, VOICE_STATE) // Disable parts of the cache + .setBulkDeleteSplittingEnabled(false) // Enable the bulk delete event + .setCompression(NONE) // Disable compression (not recommended) + .enableIntents(MESSAGE_CONTENT) + .enableIntents(GUILD_MEMBERS) + .addEventListeners( + new GiveawayCommand("giveaway"), + new MessageCommand("nachricht"), + new RolesCommand("rollen"), + new StatsCommand("statistik"), + new SyncPermissionCommand("synchronisieren") + ) + .addEventListeners( + new GuildAccessListener() + ) + .addEventListeners( + new GiveawayWinnerPublishButton(), + new SyncButton(), + new TicketCloseAbortButton(), + new TicketCloseButton(), + new TicketCloseConfirmButton(), + new TicketCreateButton() + ) + .build().awaitReady(); + + discordBotProperties.getGuild().updateCommands().addCommands( + // only administrator + Commands.slash("nachricht", "Nachrichten Vorlagen") + .addSubcommands( + new SubcommandData("sync", "Nachrichten Vorlage für die Synchronisierung"), + new SubcommandData("ticket", "Nachrichten Vorlage für Tickets")) + .setDefaultPermissions(enabledFor(ADMINISTRATOR)), + + // only supporter, moderator, senior-moderator + Commands.slash("giveaway", "Lost einen Spieler anhand der Reaktionen einer Nachricht aus") + .addOption(STRING, "message", "Nachricht mit den Reaktionen", true) + .setDefaultPermissions(enabledFor(VIEW_AUDIT_LOGS)), + Commands.slash("rollen", "Informationen zu den Rollen auf diesem Discord") + .setDefaultPermissions(enabledFor(VIEW_AUDIT_LOGS)), + Commands.slash("synchronisieren", "Rechte eines Members synchronisieren") + .addOption(USER, "member", "Discord Nutzer dessen Rechte synchronisiert werden sollen (Discord Nutzer muss sich verknüpft haben)", true) + .setDefaultPermissions(enabledFor(VIEW_AUDIT_LOGS)), + + // everyone + Commands.slash("statistik", "Deine Statistiken (nicht öffentlich) oder die eines anderen Nutzers (öffentlich)") + .addOption(USER, "player", "Discord Nutzer dessen Statistiken angezeigt werden sollen (Discord Nutzer muss sich verknüpft haben)", false) + ).queue(); + } +} diff --git a/src/main/java/net/turniptales/discord/api/API.java b/src/main/java/net/turniptales/discord/api/API.java deleted file mode 100644 index 80567e9..0000000 --- a/src/main/java/net/turniptales/discord/api/API.java +++ /dev/null @@ -1,18 +0,0 @@ -package net.turniptales.discord.api; - -import net.turniptales.discord.api.schema.PlayerStats; -import net.turniptales.discord.api.schema.Verification; - -import static java.util.UUID.fromString; - -public class API { - - public static Verification getVerification(String verificationCode, long memberId) { - // rettichlp.de:8090/turniptales/v1/verification/check?code=&memberId= - return new Verification(fromString("25855f4d-3874-4a7f-a6ad-e9e4f3042e19"), "RettichLP"); - } - - public static PlayerStats getPlayerStats(String playerName) { - return new PlayerStats(fromString("25855f4d-3874-4a7f-a6ad-e9e4f3042e19"), "RettichLP", 20, true); - } -} diff --git a/src/main/java/net/turniptales/discord/api/schema/PlayerStats.java b/src/main/java/net/turniptales/discord/api/schema/PlayerStats.java deleted file mode 100644 index 7c6f423..0000000 --- a/src/main/java/net/turniptales/discord/api/schema/PlayerStats.java +++ /dev/null @@ -1,16 +0,0 @@ -package net.turniptales.discord.api.schema; - -import lombok.AllArgsConstructor; -import lombok.Data; - -import java.util.UUID; - -@Data -@AllArgsConstructor -public class PlayerStats { - - private UUID minecraftUuid; - private String minecraftName; - private int level; - private boolean online; -} diff --git a/src/main/java/net/turniptales/discord/api/schema/Verification.java b/src/main/java/net/turniptales/discord/api/schema/Verification.java deleted file mode 100644 index 7cf2eb4..0000000 --- a/src/main/java/net/turniptales/discord/api/schema/Verification.java +++ /dev/null @@ -1,14 +0,0 @@ -package net.turniptales.discord.api.schema; - -import lombok.AllArgsConstructor; -import lombok.Data; - -import java.util.UUID; - -@Data -@AllArgsConstructor -public class Verification { - - private UUID minecraftUuid; - private String minecraftName; -} diff --git a/src/main/java/net/turniptales/discord/buttons/ButtonBase.java b/src/main/java/net/turniptales/discord/buttons/ButtonBase.java new file mode 100644 index 0000000..cbcaa1c --- /dev/null +++ b/src/main/java/net/turniptales/discord/buttons/ButtonBase.java @@ -0,0 +1,23 @@ +package net.turniptales.discord.buttons; + +import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; + +public abstract class ButtonBase extends ListenerAdapter { + + private final String name; + + public ButtonBase(String name) { + this.name = name; + } + + public abstract void onButtonClick(ButtonInteractionEvent event); + + @Override + public void onButtonInteraction(ButtonInteractionEvent event) { + String componentId = event.getComponentId(); + if (componentId.equalsIgnoreCase(this.name)) { + onButtonClick(event); + } + } +} diff --git a/src/main/java/net/turniptales/discord/buttons/GiveawayWinnerPublishButton.java b/src/main/java/net/turniptales/discord/buttons/GiveawayWinnerPublishButton.java new file mode 100644 index 0000000..8fa17dd --- /dev/null +++ b/src/main/java/net/turniptales/discord/buttons/GiveawayWinnerPublishButton.java @@ -0,0 +1,19 @@ +package net.turniptales.discord.buttons; + +import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; + +import static net.turniptales.discord.commands.GiveawayCommand.giveaways; +import static net.turniptales.discord.common.services.UtilService.sendSelfDeletingMessage; + +public class GiveawayWinnerPublishButton extends ButtonBase { + + public GiveawayWinnerPublishButton() { + super("btn_giveaway_winner_publish_button"); + } + + @Override + public void onButtonClick(ButtonInteractionEvent event) { + giveaways.get(event.getUser()).publishWinner(); + sendSelfDeletingMessage(event, "Gewinner veröffentlicht!"); + } +} diff --git a/src/main/java/net/turniptales/discord/buttons/SyncButton.java b/src/main/java/net/turniptales/discord/buttons/SyncButton.java new file mode 100644 index 0000000..08f7430 --- /dev/null +++ b/src/main/java/net/turniptales/discord/buttons/SyncButton.java @@ -0,0 +1,79 @@ +package net.turniptales.discord.buttons; + +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent; +import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; +import net.dv8tion.jda.api.interactions.components.ActionRow; +import net.dv8tion.jda.api.interactions.components.text.TextInput; +import net.dv8tion.jda.api.interactions.components.text.TextInputStyle; +import net.dv8tion.jda.api.interactions.modals.Modal; +import org.springframework.http.ResponseEntity; + +import java.util.HashMap; +import java.util.Map; + +import static java.lang.System.currentTimeMillis; +import static java.util.Objects.requireNonNull; +import static java.util.concurrent.TimeUnit.SECONDS; +import static net.dv8tion.jda.api.interactions.modals.Modal.create; +import static net.turniptales.discord.TurnipTalesDiscord.api; +import static net.turniptales.discord.common.services.UtilService.sendSelfDeletingMessage; +import static net.turniptales.discord.common.services.UtilService.synchronise; + +public class SyncButton extends ButtonBase { + + private final Map lastSync = new HashMap<>(); + + public SyncButton() { + super("btn_sync"); + } + + @Override + public void onButtonClick(ButtonInteractionEvent event) { + User user = event.getUser(); + if (currentTimeMillis() - this.lastSync.getOrDefault(user, 0L) <= SECONDS.toMillis(30)) { + sendSelfDeletingMessage(event, "Du hast bereits vor weniger als 30 Sekunden deine Berechtigungen synchronisiert!"); + return; + } + + if (api.getData(user.getId()).getStatusCode().is2xxSuccessful()) { + synchronise(event, requireNonNull(event.getMember())); + this.lastSync.put(user, currentTimeMillis()); + } else { + event.replyModal(getVerificationModal()).queue(); + } + } + + @Override + public void onModalInteraction(ModalInteractionEvent event) { + if (!event.getModalId().equalsIgnoreCase("mdl_verification")) { + return; + } + + String discordCode = requireNonNull(event.getValue("tip_discord_code")).getAsString(); + User user = event.getUser(); + String accountUserId = user.getId(); + + ResponseEntity response = api.connect(accountUserId, discordCode); + boolean success = response == null; + + if (success) { + synchronise(event, requireNonNull(event.getMember())); + this.lastSync.put(user, currentTimeMillis()); + } else { + sendSelfDeletingMessage(event, "Dein Discord Account konnte nicht mit deinem Minecraft Account verknüpft werden."); + } + } + + private Modal getVerificationModal() { + TextInput discordCodeInput = TextInput.create("tip_discord_code", "Discord Code", TextInputStyle.SHORT) + .setMinLength(8) + .setMaxLength(8) + .setRequired(true) + .build(); + + return create("mdl_verification", "Verifizierung") + .addComponents(ActionRow.of(discordCodeInput)) + .build(); + } +} diff --git a/src/main/java/net/turniptales/discord/buttons/TicketCloseAbortButton.java b/src/main/java/net/turniptales/discord/buttons/TicketCloseAbortButton.java new file mode 100644 index 0000000..d5ef62f --- /dev/null +++ b/src/main/java/net/turniptales/discord/buttons/TicketCloseAbortButton.java @@ -0,0 +1,15 @@ +package net.turniptales.discord.buttons; + +import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; + +public class TicketCloseAbortButton extends ButtonBase { + + public TicketCloseAbortButton() { + super("btn_ticket_close_abort"); + } + + @Override + public void onButtonClick(ButtonInteractionEvent event) { + event.getMessage().delete().queue(); + } +} diff --git a/src/main/java/net/turniptales/discord/buttons/TicketCloseButton.java b/src/main/java/net/turniptales/discord/buttons/TicketCloseButton.java new file mode 100644 index 0000000..75c0bb4 --- /dev/null +++ b/src/main/java/net/turniptales/discord/buttons/TicketCloseButton.java @@ -0,0 +1,27 @@ +package net.turniptales.discord.buttons; + +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; +import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; + +import java.util.Objects; + +import static net.dv8tion.jda.api.interactions.components.buttons.Button.danger; +import static net.dv8tion.jda.api.interactions.components.buttons.Button.secondary; +import static net.turniptales.discord.TurnipTalesDiscord.discordBotProperties; + +public class TicketCloseButton extends ButtonBase { + + public TicketCloseButton() { + super("btn_ticket_close"); + } + + @Override + public void onButtonClick(ButtonInteractionEvent event) { + TextChannel textChannel = event.getChannel().asTextChannel(); + if (Objects.equals(textChannel.getParentCategory(), discordBotProperties.getTicketCategory()) && textChannel.getName().startsWith("ticket-")) { + event.reply("Möchtest Du das Ticket wirklich schließen?") + .addActionRow(danger("btn_ticket_close_confirm", "Bestätigen"), secondary("btn_ticket_close_abort", "Abbrechen")) + .queue(); + } + } +} diff --git a/src/main/java/net/turniptales/discord/buttons/TicketCloseConfirmButton.java b/src/main/java/net/turniptales/discord/buttons/TicketCloseConfirmButton.java new file mode 100644 index 0000000..8b7a0b7 --- /dev/null +++ b/src/main/java/net/turniptales/discord/buttons/TicketCloseConfirmButton.java @@ -0,0 +1,23 @@ +package net.turniptales.discord.buttons; + +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; +import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; + +import java.util.Objects; + +import static net.turniptales.discord.TurnipTalesDiscord.discordBotProperties; + +public class TicketCloseConfirmButton extends ButtonBase { + + public TicketCloseConfirmButton() { + super("btn_ticket_close_confirm"); + } + + @Override + public void onButtonClick(ButtonInteractionEvent event) { + TextChannel textChannel = event.getChannel().asTextChannel(); + if (Objects.equals(textChannel.getParentCategory(), discordBotProperties.getTicketCategory()) && textChannel.getName().startsWith("ticket-")) { + textChannel.delete().queue(); + } + } +} diff --git a/src/main/java/net/turniptales/discord/buttons/TicketCreateButton.java b/src/main/java/net/turniptales/discord/buttons/TicketCreateButton.java new file mode 100644 index 0000000..9b11210 --- /dev/null +++ b/src/main/java/net/turniptales/discord/buttons/TicketCreateButton.java @@ -0,0 +1,98 @@ +package net.turniptales.discord.buttons; + +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.entities.channel.middleman.StandardGuildMessageChannel; +import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent; +import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; +import net.dv8tion.jda.api.interactions.components.ActionRow; +import net.dv8tion.jda.api.interactions.components.text.TextInput; +import net.dv8tion.jda.api.interactions.components.text.TextInputStyle; +import net.dv8tion.jda.api.interactions.modals.Modal; + +import java.util.EnumSet; +import java.util.Objects; + +import static java.util.Objects.requireNonNull; +import static net.dv8tion.jda.api.Permission.VIEW_CHANNEL; +import static net.dv8tion.jda.api.entities.emoji.Emoji.fromUnicode; +import static net.dv8tion.jda.api.interactions.components.buttons.Button.success; +import static net.dv8tion.jda.api.interactions.components.text.TextInputStyle.PARAGRAPH; +import static net.dv8tion.jda.api.interactions.modals.Modal.create; +import static net.turniptales.discord.TurnipTalesDiscord.discordBotProperties; + +public class TicketCreateButton extends ButtonBase { + + public TicketCreateButton() { + super("btn_ticket_create"); + } + + @Override + public void onButtonClick(ButtonInteractionEvent event) { + Member member = event.getMember(); + assert member != null; + String memberId = member.getId(); + + boolean hasTicketChannel = discordBotProperties.getTicketCategory().getChannels().stream() + .map(guildChannel -> discordBotProperties.getGuild().getTextChannelById(guildChannel.getId())) + .filter(Objects::nonNull) + .map(StandardGuildMessageChannel::getTopic) + .filter(Objects::nonNull) + .anyMatch(s -> s.contains(memberId)); + + if (hasTicketChannel) { + event.reply("Du hast bereits einen Ticket Channel!").setEphemeral(true).queue(); + return; + } + + event.replyModal(getTicketModal()).queue(); + } + + @Override + public void onModalInteraction(ModalInteractionEvent event) { + if (!event.getModalId().equalsIgnoreCase("mdl_ticket")) { + return; + } + + Member member = event.getMember(); + assert member != null; + String memberId = member.getId(); + String userName = member.getUser().getName(); + + String minecraftName = requireNonNull(event.getValue("tip_minecraft_name")).getAsString(); + String log = requireNonNull(event.getValue("tip_topic")).getAsString(); + + Role supporterRole = discordBotProperties.getSupporterRole(); + Role moderatorRole = discordBotProperties.getModeratorRole(); + discordBotProperties.getTicketCategory().createTextChannel("ticket-" + userName) + .setTopic("Ticket von " + userName + " (" + memberId + ")") + .addPermissionOverride(discordBotProperties.getGuild().getPublicRole(), null, EnumSet.of(VIEW_CHANNEL)) + .addPermissionOverride(member, EnumSet.of(VIEW_CHANNEL), null) + .addPermissionOverride(discordBotProperties.getSeniorModeratorRole(), EnumSet.of(VIEW_CHANNEL), null) + .addPermissionOverride(moderatorRole, EnumSet.of(VIEW_CHANNEL), null) + .addPermissionOverride(supporterRole, EnumSet.of(VIEW_CHANNEL), null) + .queue(textChannel -> textChannel + .sendMessage("Hey " + member.getAsMention() + "! Danke dass du ein Ticket erstellt hast. Die " + supporterRole.getAsMention() + " und " + moderatorRole.getAsMention() + " werden Dir schnellstmöglich deine Frage beantworten oder Dir helfen.\n" + + "Spieler: " + minecraftName + "\n" + + "Anliegen: " + log) + .addActionRow(success("closeTicket", "Ticket schließen").withEmoji(fromUnicode("U+1F512"))) + .queue(message -> event.reply("Du hast ein Ticket erstellt: " + message.getJumpUrl()).setEphemeral(true).queue())); + } + + private Modal getTicketModal() { + TextInput minecraftNameTextInput = TextInput.create("tip_minecraft_name", "Minecraft Name", TextInputStyle.SHORT) + .setMinLength(3) + .setMaxLength(16) + .setRequired(true) + .build(); + + TextInput logInput = TextInput.create("tip_topic", "Anliegen", PARAGRAPH) + .setRequired(true) + .setPlaceholder("Hey, wie kann ich mich im Bauteam bewerben?") + .build(); + + return create("mdl_ticket", "Neues Ticket") + .addComponents(ActionRow.of(minecraftNameTextInput), ActionRow.of(logInput)) + .build(); + } +} diff --git a/src/main/java/net/turniptales/discord/commands/CommandBase.java b/src/main/java/net/turniptales/discord/commands/CommandBase.java new file mode 100644 index 0000000..9165dbb --- /dev/null +++ b/src/main/java/net/turniptales/discord/commands/CommandBase.java @@ -0,0 +1,22 @@ +package net.turniptales.discord.commands; + +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; + +public abstract class CommandBase extends ListenerAdapter { + + private final String name; + + public CommandBase(String name) { + this.name = name; + } + + public abstract void onCommand(SlashCommandInteractionEvent event); + + @Override + public void onSlashCommandInteraction(SlashCommandInteractionEvent event) { + if (event.getName().equals(this.name)) { + onCommand(event); + } + } +} diff --git a/src/main/java/net/turniptales/discord/commands/GiveawayCommand.java b/src/main/java/net/turniptales/discord/commands/GiveawayCommand.java new file mode 100644 index 0000000..beae855 --- /dev/null +++ b/src/main/java/net/turniptales/discord/commands/GiveawayCommand.java @@ -0,0 +1,102 @@ +package net.turniptales.discord.commands; + +import lombok.extern.log4j.Log4j2; +import net.dv8tion.jda.api.entities.Message; +import net.dv8tion.jda.api.entities.MessageReaction; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.interactions.commands.OptionMapping; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Random; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import static java.util.Objects.nonNull; +import static net.dv8tion.jda.api.interactions.components.buttons.Button.success; +import static net.turniptales.discord.common.services.UtilService.sendSelfDeletingMessage; + +@Log4j2 +public class GiveawayCommand extends CommandBase { + + public static final Map giveaways = new HashMap<>(); + + public GiveawayCommand(String name) { + super(name); + } + + @Override + public void onCommand(SlashCommandInteractionEvent event) { + OptionMapping messageOptionMapping = event.getOption("message"); + + if (nonNull(messageOptionMapping)) { + event.deferReply().setEphemeral(true).queue(); + + Message message = event.getChannel().retrieveMessageById(messageOptionMapping.getAsString()).complete(); + List reactions = message.getReactions(); + List usersWhoReacted = getUsersWhoReacted(reactions); + + List uniqueUsers = usersWhoReacted.stream() + .distinct() + .toList(); + + User winner = uniqueUsers.stream() + .filter(user -> !user.isBot()) + .toList().get(new Random().nextInt(uniqueUsers.size())); + + Giveaway giveaway = new Giveaway(message, uniqueUsers, winner); + giveaways.put(event.getUser(), giveaway); + + event.getHook() + .sendMessage("Reaktionen: " + usersWhoReacted.size() + " (" + reactions.size() + ")\nNutzer: " + uniqueUsers.size() + "\n\nGewinner: " + winner.getAsMention()) + .addActionRow(success("publishWinner", "Gewinner veröffentlichen")) + .queue(); + } else { + sendSelfDeletingMessage(event, "Es muss eine Nachrichten-ID angegeben werden."); + } + } + + public List getUsersWhoReacted(List reactions) { + List>> messageReactionUsersFuture = new ArrayList<>(); + + reactions.forEach(reaction -> { + CompletableFuture> reactionUsersFuture = new CompletableFuture<>(); + reaction.retrieveUsers().queue(reactionUsersFuture::complete); + messageReactionUsersFuture.add(reactionUsersFuture); + }); + + return messageReactionUsersFuture.stream() + .map(future -> { + try { + return future.get(); + } catch (InterruptedException | ExecutionException e) { + log.error(e); + return null; + } + }) + .filter(Objects::nonNull) + .flatMap(List::stream) + .toList(); + } + + public static class Giveaway { + + private final Message message; + private final List users; + private final User winner; + + public Giveaway(Message message, List users, User winner) { + this.message = message; + this.users = users; + this.winner = winner; + } + + public void publishWinner() { + this.message.reply("@here\n:tada: **Ein Gewinner wurde gezogen!** :tada:\n\nAus `" + this.users.size() + "` Teilnehmern wurde " + this.winner.getAsMention() + " ausgelost. Herzlichen Glückwunsch!").queue(); + } + } +} diff --git a/src/main/java/net/turniptales/discord/commands/MessageCommand.java b/src/main/java/net/turniptales/discord/commands/MessageCommand.java new file mode 100644 index 0000000..ebb88be --- /dev/null +++ b/src/main/java/net/turniptales/discord/commands/MessageCommand.java @@ -0,0 +1,50 @@ +package net.turniptales.discord.commands; + +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; + +import java.awt.Color; + +import static java.util.Objects.requireNonNull; +import static net.dv8tion.jda.api.entities.emoji.Emoji.fromUnicode; +import static net.dv8tion.jda.api.interactions.components.buttons.Button.success; + +public class MessageCommand extends CommandBase { + + public MessageCommand(String name) { + super(name); + } + + @Override + public void onCommand(SlashCommandInteractionEvent event) { + event.deferReply(true).queue(); + + TextChannel textChannel = event.getChannel().asTextChannel(); + switch (requireNonNull(event.getSubcommandName())) { + case "sync" -> { + EmbedBuilder embedBuilder = new EmbedBuilder() + .setColor(new Color(0x609fee)) + .setTitle("Verifikation und Synchronisation") + .addField("🎡 **Du kannst Deinen Minecraft Account mit Deinem Discord Account verbinden! Dadurch hast Du unter anderem folgende Vorteile:**", "- Statistiken einsehen\n- Rechte synchronisieren\n- schnellerer und besserer Support", false); + + textChannel.sendMessageEmbeds(embedBuilder.build()) + .addActionRow(success("btn_sync", "Rechte synchronisieren").withEmoji(fromUnicode("U+1F504"))) + .queue(); + } + case "ticket" -> { + EmbedBuilder embedBuilder = new EmbedBuilder() + .setColor(new Color(0x609fee)) + .setTitle("Ticket") + .addField("🎫 **Hier kannst du ein Ticket erstellen um schnell Hilfe zu erhalten oder sonstige Fragen zu klären.**", "Bei der Erstellung eines Tickets wirst du nach deinem Minecraft Namen und Anliegen gefragt.", false); + + textChannel + .sendMessageEmbeds(embedBuilder.build()) + .addActionRow(success("btn_ticket_create", "Neues Ticket").withEmoji(fromUnicode("U+1F3AB"))) + .queue(); + } + } + + event.getHook().deleteOriginal().queue(); + } +} diff --git a/src/main/java/net/turniptales/discord/commands/RolesCommand.java b/src/main/java/net/turniptales/discord/commands/RolesCommand.java new file mode 100644 index 0000000..423701b --- /dev/null +++ b/src/main/java/net/turniptales/discord/commands/RolesCommand.java @@ -0,0 +1,43 @@ +package net.turniptales.discord.commands; + +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; + +import static net.turniptales.discord.TurnipTalesDiscord.discordBotProperties; + +public class RolesCommand extends CommandBase { + + public RolesCommand(String name) { + super(name); + } + + @Override + public void onCommand(SlashCommandInteractionEvent event) { + event.reply(""" + Die Standard Rolle für jedes Mitglied ist `%s`. + + Wenn man längere Zeit auf diesem Discord ist, wird einem automatisch eine Rolle zugewiesen. Je nachdem, wie lang man schon auf diesem Discord ist, erhält man eine höhere Rolle: + + `%s` ➜ direkt nach Serverbeitritt + `%s` ➜ nach einer Woche + `%s` ➜ nach zwei Wochen + `%s` ➜ nach einem Monat + `%s` ➜ nach drei Monaten + `%s` ➜ nach sechs Monaten + `%s` ➜ nach einem Jahr + `%s` ➜ nach zwei Jahren + `%s` ➜ nach drei Jahren + + So sieht man auch gut, wer schon lang dabei ist und sich schon gut auskennen könnte. Die Rollen werden durch den TurnipTales Bot automatisch vergeben und können dadurch nicht erstattet werden, wenn man den Server zwischenzeitlich verlässt. + """.formatted( + discordBotProperties.getPlayerRole().getName(), + discordBotProperties.getRole0().getName(), + discordBotProperties.getRole1Week().getName(), + discordBotProperties.getRole2Week().getName(), + discordBotProperties.getRole1Month().getName(), + discordBotProperties.getRole3Month().getName(), + discordBotProperties.getRole6Month().getName(), + discordBotProperties.getRole1Year().getName(), + discordBotProperties.getRole2Year().getName(), + discordBotProperties.getRole3Year().getName())).queue(); + } +} diff --git a/src/main/java/net/turniptales/discord/commands/StatsCommand.java b/src/main/java/net/turniptales/discord/commands/StatsCommand.java index b6bc6a2..5054f3a 100644 --- a/src/main/java/net/turniptales/discord/commands/StatsCommand.java +++ b/src/main/java/net/turniptales/discord/commands/StatsCommand.java @@ -3,40 +3,153 @@ import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.MessageEmbed; +import net.dv8tion.jda.api.entities.channel.Channel; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.interactions.commands.OptionMapping; -import net.turniptales.discord.api.API; -import net.turniptales.discord.api.schema.PlayerStats; +import net.turniptales.discord.common.api.model.ConnectionDataValue; +import net.turniptales.discord.common.api.model.PunishmentData; +import org.springframework.http.ResponseEntity; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Date; +import java.util.List; +import java.util.StringJoiner; + +import static java.awt.Color.CYAN; import static java.lang.String.valueOf; +import static java.util.Locale.US; import static java.util.Objects.nonNull; -import static java.util.Objects.requireNonNull; +import static net.turniptales.discord.TurnipTalesDiscord.api; +import static net.turniptales.discord.TurnipTalesDiscord.discordBot; +import static net.turniptales.discord.common.services.UtilService.sendSelfDeletingMessage; + +public class StatsCommand extends CommandBase { -public class StatsCommand extends ListenerAdapter { + public static final DecimalFormatSymbols US_SYMBOLS = DecimalFormatSymbols.getInstance(US); + public static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("###.##", US_SYMBOLS); + + public StatsCommand(String name) { + super(name); + } @Override - public void onSlashCommandInteraction(SlashCommandInteractionEvent e) { - if (!e.getName().equals("stats")) return; + public void onCommand(SlashCommandInteractionEvent event) { + OptionMapping playerOptionMapping = event.getOption("player"); - OptionMapping playerOptionMapping = e.getOption("player"); - if (!nonNull(playerOptionMapping)) { - e.reply("Gib einen Spielernamen an!").setEphemeral(true).queue(); + Member member = event.getMember(); + String userId = event.getUser().getId(); + + boolean notSelf = nonNull(playerOptionMapping); + String targetUserId = notSelf ? playerOptionMapping.getAsString() : userId; + ResponseEntity responseEntity = api.getData(targetUserId); + + boolean isConnected = responseEntity.getStatusCode().is2xxSuccessful(); + if (!isConnected) { + sendSelfDeletingMessage(event, (notSelf ? "Der Spieler hat seinen" : "Du hast deinen") + " Discord Account noch nicht mit dem Minecraft Account verknüpft."); return; } - PlayerStats playerStats = API.getPlayerStats(playerOptionMapping.getAsString()); - MessageEmbed messageEmbed = createPlayerStatsMessageEmbed(playerStats, requireNonNull(e.getMember())); - e.replyEmbeds(messageEmbed).queue(); + ConnectionDataValue targetConnectionDataValue = responseEntity.getBody(); + + if (notSelf) { + MessageEmbed publicPlayerStats = isTicketChannel(event.getChannel()) ? getPrivatePlayerStats(targetConnectionDataValue, member) : getPublicPlayerStats(targetConnectionDataValue, member); + event.replyEmbeds(publicPlayerStats).queue(); + } else { + MessageEmbed privatePlayerStats = getPrivatePlayerStats(targetConnectionDataValue, member); + event.replyEmbeds(privatePlayerStats).setEphemeral(true).queue(); + } } - private MessageEmbed createPlayerStatsMessageEmbed(PlayerStats playerStats, Member requestor) { - return new EmbedBuilder() - .setTitle("Statistiken von " + playerStats.getMinecraftName()) - .setDescription(playerStats.getMinecraftUuid().toString()) - .addField("Online", playerStats.isOnline() ? "Ja" : "Nein", true) - .addField("Level", valueOf(playerStats.getLevel()), true) - .setFooter("Angefordert von " + requestor.getUser().getAsMention(), requestor.getAvatarUrl()) + private boolean isTicketChannel(Channel channel) { + return channel instanceof TextChannel textChannel + && nonNull(textChannel.getTopic()) + && textChannel.getTopic().contains("Ticket von "); + } + + private MessageEmbed getPublicPlayerStats(ConnectionDataValue connectionDataValue, Member member) { + return getDefaultEmbedBuilder(connectionDataValue, member) + .addField("Level", valueOf(connectionDataValue.getLevel()), true) + .addField("Fraktion:", connectionDataValue.getGroup(), true) + .addField("Kennt Spieler", valueOf(connectionDataValue.getKnownPlayerCount()), true) + + .addField("Steckbrief", getCharacteristics(connectionDataValue), false) + .addBlankField(false) + .addField("Häuser:", getHouses(connectionDataValue.getHouses()), true) + .addField("Autos:", getCars(connectionDataValue.getCars()), true) .build(); } + + private MessageEmbed getPrivatePlayerStats(ConnectionDataValue connectionDataValue, Member member) { + return getDefaultEmbedBuilder(connectionDataValue, member) + .addField("Level", valueOf(connectionDataValue.getLevel()), true) + .addField("Fraktion:", connectionDataValue.getGroup(), true) + .addField("Kennt Spieler", valueOf(connectionDataValue.getKnownPlayerCount()), true) + + .addField("Steckbrief", getCharacteristics(connectionDataValue), false) + .addField("Finanzen", getBalances(connectionDataValue), true) + .addField("Bestrafung", getPunishments(connectionDataValue.getPunishmentData()), true) + .addBlankField(false) + .addField("Häuser:", getHouses(connectionDataValue.getHouses()), true) + .addField("Autos:", getCars(connectionDataValue.getCars()), true) + .build(); + } + + private EmbedBuilder getDefaultEmbedBuilder(ConnectionDataValue connectionDataValue, Member member) { + return new EmbedBuilder() + .setColor(CYAN) + .setThumbnail("https://minotar.net/helm/" + connectionDataValue.getMinecraftUuid() + "/300.png") + .setAuthor("TurnipTales", "https://turniptales.net/", discordBot.getSelfUser().getEffectiveAvatarUrl()) + .setTitle("Statistiken von " + connectionDataValue.getMinecraftName()) + .setDescription("**Role**: " + connectionDataValue.getRole()) + .setFooter(member.getEffectiveName(), member.getEffectiveAvatarUrl()) + .setTimestamp(new Date().toInstant()); + } + + private String getCharacteristics(ConnectionDataValue connectionDataValue) { + return """ + **Name**: %s + **Alter**: %s + **Geschlecht**: %s + """ + .formatted(connectionDataValue.getRoleplayName(), + connectionDataValue.getAge(), + connectionDataValue.getGender().equals("MAN") ? ":male_sign:" : ":female_sign:"); + } + + private String getBalances(ConnectionDataValue connectionDataValue) { + return """ + **Bank**: %s$ + **Bargeld**: %s$ + **PayPal**: %s$ + """ + .formatted(DECIMAL_FORMAT.format(connectionDataValue.getBankBalance()), DECIMAL_FORMAT.format(connectionDataValue.getCashBalance()), DECIMAL_FORMAT.format(connectionDataValue.getPalPayBalance())); + } + + private String getPunishments(PunishmentData punishmentData) { + return """ + **Waffensperre**: %s + **Fraktionssperre**: %s + **Skill-Sperre**: %s + **Ad-Sperre**: %s + **Auto-Sperre**: %s + **Checkpoints**: %s + """ + .formatted(!punishmentData.noWeaponBlockActive(), !punishmentData.noGroupBlockActive(), !punishmentData.noSkillBlockActive(), !punishmentData.noAdBlockActive(), !punishmentData.noCarBlockActive(), punishmentData.getCheckpointsLeft()); + } + + private String getHouses(List houses) { + StringJoiner houseJoiner = new StringJoiner("\n- ", "- ", ""); + houses.stream() + .map(Object::toString) + .forEach(houseJoiner::add); + return !houses.isEmpty() ? houseJoiner.toString() : "keine Häuser im Besitz oder zur Miete"; + } + + private String getCars(List cars) { + StringJoiner carJoiner = new StringJoiner("\n- ", "- ", ""); + cars.forEach(carJoiner::add); + return !cars.isEmpty() ? carJoiner.toString() : "keine Autos im Besitz"; + } } diff --git a/src/main/java/net/turniptales/discord/commands/SyncPermissionCommand.java b/src/main/java/net/turniptales/discord/commands/SyncPermissionCommand.java new file mode 100644 index 0000000..c3126bc --- /dev/null +++ b/src/main/java/net/turniptales/discord/commands/SyncPermissionCommand.java @@ -0,0 +1,22 @@ +package net.turniptales.discord.commands; + +import lombok.extern.log4j.Log4j2; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; + +import static java.util.Objects.requireNonNull; +import static net.turniptales.discord.common.services.UtilService.synchronise; + +@Log4j2 +public class SyncPermissionCommand extends CommandBase { + + public SyncPermissionCommand(String name) { + super(name); + } + + @Override + public void onCommand(SlashCommandInteractionEvent event) { + Member member = requireNonNull(event.getOption("member")).getAsMember(); + synchronise(event, requireNonNull(member)); + } +} diff --git a/src/main/java/net/turniptales/discord/commands/TicketCommand.java b/src/main/java/net/turniptales/discord/commands/TicketCommand.java deleted file mode 100644 index 74c07c0..0000000 --- a/src/main/java/net/turniptales/discord/commands/TicketCommand.java +++ /dev/null @@ -1,35 +0,0 @@ -package net.turniptales.discord.commands; - -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import net.turniptales.discord.Config; - -import java.awt.Color; -import java.util.Objects; - -import static net.dv8tion.jda.api.Permission.ADMINISTRATOR; -import static net.dv8tion.jda.api.entities.emoji.Emoji.fromUnicode; -import static net.dv8tion.jda.api.interactions.components.buttons.Button.success; - -public class TicketCommand extends ListenerAdapter { - - @Override - public void onSlashCommandInteraction(SlashCommandInteractionEvent e) { - if (!e.getName().equals("ticket") || !Objects.requireNonNull(e.getMember()).hasPermission(ADMINISTRATOR)) - return; - - e.deferReply(true).queue(); - EmbedBuilder embedBuilder = new EmbedBuilder() - .setColor(new Color(0x609fee)) - .setTitle("Ticket") - .addField("🎫 **Hier kannst du ein Ticket erstellen um schnell Hilfe zu erhalten oder sonstige Fragen zu klären.**", "Bei der Erstellung eines Tickets wirst du nach deinem Minecraft Namen und Anliegen gefragt.", false); - - assert Config.TICKET_TEXT_CHANNEL != null; - Config.TICKET_TEXT_CHANNEL - .sendMessageEmbeds(embedBuilder.build()) - .addActionRow(success("createTicketAddButton", "Neues Ticket").withEmoji(fromUnicode("U+1F3AB"))) - .queue(); - e.getHook().deleteOriginal().queue(); - } -} diff --git a/src/main/java/net/turniptales/discord/commands/VerifyCommand.java b/src/main/java/net/turniptales/discord/commands/VerifyCommand.java deleted file mode 100644 index ec041a5..0000000 --- a/src/main/java/net/turniptales/discord/commands/VerifyCommand.java +++ /dev/null @@ -1,30 +0,0 @@ -package net.turniptales.discord.commands; - -import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import net.dv8tion.jda.api.interactions.commands.OptionMapping; -import net.turniptales.discord.api.schema.Verification; - -import static java.util.Objects.nonNull; -import static java.util.Objects.requireNonNull; -import static java.util.concurrent.TimeUnit.SECONDS; -import static net.turniptales.discord.api.API.getVerification; - -public class VerifyCommand extends ListenerAdapter { - - @Override - public void onSlashCommandInteraction(SlashCommandInteractionEvent e) { - if (!e.getName().equals("verify")) return; - - OptionMapping codeOptionMapping = e.getOption("code"); - if (!nonNull(codeOptionMapping)) { - e.reply("Gib einen Verifizierungscode an!").setEphemeral(true).queue(); - return; - } - - Verification verification = getVerification(codeOptionMapping.getAsString(), requireNonNull(e.getMember()).getIdLong()); - - e.reply("Du hast deinen Discord Account mit dem Minecraft Account " + verification.getMinecraftName() + " verknüpft!\nDiese Nachricht zerstört sich gleich von selbst...").setEphemeral(true).queue(); - e.getHook().deleteOriginal().queueAfter(5, SECONDS); - } -} diff --git a/src/main/java/net/turniptales/discord/common/api/Api.java b/src/main/java/net/turniptales/discord/common/api/Api.java new file mode 100644 index 0000000..8cc5085 --- /dev/null +++ b/src/main/java/net/turniptales/discord/common/api/Api.java @@ -0,0 +1,84 @@ +package net.turniptales.discord.common.api; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializer; +import lombok.Data; +import lombok.extern.log4j.Log4j2; +import net.turniptales.discord.common.api.model.ConnectionDataValue; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatusCode; +import org.springframework.http.ResponseEntity; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.reactive.function.client.WebClientResponseException; +import reactor.core.publisher.Mono; + +import java.time.ZonedDateTime; + +import static com.google.gson.JsonParser.parseString; +import static java.lang.String.format; +import static java.time.ZonedDateTime.parse; +import static java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME; +import static org.springframework.http.HttpMethod.GET; +import static org.springframework.http.HttpMethod.POST; + +@Log4j2 +@Data +public class Api { + + /** + * {@link ConnectionDataValue} + */ + public ResponseEntity getData(String accountUserId) { + String url = format("/data?discordUserId=%s", accountUserId); + + ResponseEntity responseEntity = sendRequest(url, GET); + + return responseEntity.getStatusCode().is2xxSuccessful() + ? ResponseEntity.ok(getGson().fromJson(responseEntity.getBody(), ConnectionDataValue.class)) + : ResponseEntity.status(responseEntity.getStatusCode()).body(null); + } + + public ResponseEntity connect(String accountUserId, String code) { + String url = format("/connect?type=DISCORD&accountUserId=%s&code=%s", accountUserId, code); + return sendRequest(url, POST); + } + + /** + * Request + */ + private Gson getGson() { + return new GsonBuilder() + .registerTypeAdapter(ZonedDateTime.class, (JsonDeserializer) (json, type, jsonDeserializationContext) -> parse(json.getAsJsonPrimitive().getAsString())) + .registerTypeAdapter(ZonedDateTime.class, (JsonSerializer) (date, type, jsonSerializationContext) -> new JsonPrimitive(date.format(ISO_ZONED_DATE_TIME))) + .create(); + } + + private ResponseEntity sendRequest(String url, HttpMethod method) { + return getClient(url).method(method) + .retrieve() + .bodyToMono(String.class) + .map(ResponseEntity::ok) + .onErrorResume(WebClientResponseException.class, ex -> { + String responseBodyAsString = ex.getResponseBodyAsString(); + String info = parseString(responseBodyAsString).getAsJsonObject().get("info").getAsString(); + + HttpStatusCode statusCode = ex.getStatusCode(); + if (!statusCode.is4xxClientError()) { + log.error("Request failed with code {}: {}", statusCode, info); + } + + return Mono.just(ResponseEntity.status(statusCode).body(responseBodyAsString)); + }) + .block(); + } + + private WebClient getClient(String url) { + return WebClient.builder() + .baseUrl("https://turniptales.net:7200/turniptalesapi/v1/connection" + url) + .defaultHeader("Authorization", "Basic dHVybmlwdGFsZXMtYXBpdXNlcjoqYnp0OThjV3EvLCckOT41SEN7NlEtTycralZFZmprMQ==") + .build(); + } +} diff --git a/src/main/java/net/turniptales/discord/common/api/model/ConnectionDataValue.java b/src/main/java/net/turniptales/discord/common/api/model/ConnectionDataValue.java new file mode 100644 index 0000000..8bd574e --- /dev/null +++ b/src/main/java/net/turniptales/discord/common/api/model/ConnectionDataValue.java @@ -0,0 +1,38 @@ +package net.turniptales.discord.common.api.model; + +import lombok.Builder; +import lombok.Data; + +import java.util.List; +import java.util.UUID; + +@Data +@Builder +public class ConnectionDataValue { + + // data + private String citizenId; + private UUID minecraftUuid; + private String minecraftName; + private String role; + private String roleDisplayName; + private List teams; + private int level; + private int knownPlayerCount; + // group + private String group; + private int factionRank; + private boolean leaderRights; + // characteristics + private String roleplayName; + private int age; + private String gender; + // balances + private double bankBalance; + private double cashBalance; + private double palPayBalance; + // other + private PunishmentData punishmentData; + private List houses; + private List cars; +} diff --git a/src/main/java/net/turniptales/discord/common/api/model/PunishmentData.java b/src/main/java/net/turniptales/discord/common/api/model/PunishmentData.java new file mode 100644 index 0000000..d054aa2 --- /dev/null +++ b/src/main/java/net/turniptales/discord/common/api/model/PunishmentData.java @@ -0,0 +1,50 @@ +package net.turniptales.discord.common.api.model; + +import lombok.Builder; +import lombok.Data; +import org.jetbrains.annotations.Nullable; + +import java.time.ZonedDateTime; +import java.util.List; + +import static java.time.ZonedDateTime.now; +import static java.util.Objects.nonNull; +import static net.turniptales.discord.TurnipTalesDiscord.ZONE_ID; + +@Data +@Builder +public class PunishmentData { + + @Nullable + private ZonedDateTime weaponBlockUntilDateTime; + @Nullable + private ZonedDateTime groupBlockUntilDateTime; + @Nullable + private ZonedDateTime skillBlockUntilDateTime; + @Nullable + private ZonedDateTime adBlockUntilDateTime; + @Nullable + private ZonedDateTime carBlockUntilDateTime; + private int checkpointsLeft; + private List log; + + public boolean noWeaponBlockActive() { + return !nonNull(this.weaponBlockUntilDateTime) || this.weaponBlockUntilDateTime.isBefore(now(ZONE_ID)); + } + + public boolean noGroupBlockActive() { + return !nonNull(this.groupBlockUntilDateTime) || this.groupBlockUntilDateTime.isBefore(now(ZONE_ID)); + } + + public boolean noSkillBlockActive() { + return !nonNull(this.skillBlockUntilDateTime) || this.skillBlockUntilDateTime.isBefore(now(ZONE_ID)); + } + + public boolean noAdBlockActive() { + return !nonNull(this.adBlockUntilDateTime) || this.adBlockUntilDateTime.isBefore(now(ZONE_ID)); + } + + public boolean noCarBlockActive() { + return !nonNull(this.carBlockUntilDateTime) || this.carBlockUntilDateTime.isBefore(now(ZONE_ID)); + } +} diff --git a/src/main/java/net/turniptales/discord/common/configuration/DiscordBotProperties.java b/src/main/java/net/turniptales/discord/common/configuration/DiscordBotProperties.java new file mode 100644 index 0000000..b3b9a64 --- /dev/null +++ b/src/main/java/net/turniptales/discord/common/configuration/DiscordBotProperties.java @@ -0,0 +1,159 @@ +package net.turniptales.discord.common.configuration; + +import lombok.Getter; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.entities.channel.concrete.Category; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import static net.turniptales.discord.TurnipTalesDiscord.discordBot; + +@Getter +@Component +public class DiscordBotProperties { + + @Value("${discord.bot.token}") + private String token; + + @Value("${discord.guild.id}") + private String guildId; + + @Value("${discord.guild.channels.community-text-channel}") + private String communityTextChannel; + + @Value("${discord.guild.channels.ticket-text-channel}") + private String ticketTextChannel; + + @Value("${discord.guild.categories.ticket-category}") + private String ticketCategory; + + @Value("${discord.guild.roles.player-role}") + private String playerRole; + + @Value("${discord.guild.roles.senior-moderator-role}") + private String seniorModeratorRole; + + @Value("${discord.guild.roles.moderator-role}") + private String moderatorRole; + + @Value("${discord.guild.roles.supporter-role}") + private String supporterRole; + + @Value("${discord.guild.roles.team-builder-role}") + private String teamBuilderRole; + + @Value("${discord.guild.roles.team-content-role}") + private String teamContentRole; + + @Value("${discord.guild.roles.team-social-media-role}") + private String teamSocialMediaRole; + + @Value("${discord.guild.roles.role-0}") + private String role0; + + @Value("${discord.guild.roles.role-1-week}") + private String role1Week; + + @Value("${discord.guild.roles.role-2-week}") + private String role2Week; + + @Value("${discord.guild.roles.role-1-month}") + private String role1Month; + + @Value("${discord.guild.roles.role-3-month}") + private String role3Month; + + @Value("${discord.guild.roles.role-6-month}") + private String role6Month; + + @Value("${discord.guild.roles.role-1-year}") + private String role1Year; + + @Value("${discord.guild.roles.role-2-year}") + private String role2Year; + + @Value("${discord.guild.roles.role-3-year}") + private String role3Year; + + public Guild getGuild() { + return discordBot.getGuildById(this.guildId); + } + + public TextChannel getCommunityTextChannel() { + return getGuild().getTextChannelById(this.communityTextChannel); + } + + public TextChannel getTicketTextChannel() { + return getGuild().getTextChannelById(this.ticketTextChannel); + } + + public Category getTicketCategory() { + return getGuild().getCategoryById(this.ticketCategory); + } + + public Role getPlayerRole() { + return getGuild().getRoleById(this.playerRole); + } + + public Role getSeniorModeratorRole() { + return getGuild().getRoleById(this.seniorModeratorRole); + } + + public Role getModeratorRole() { + return getGuild().getRoleById(this.moderatorRole); + } + + public Role getSupporterRole() { + return getGuild().getRoleById(this.supporterRole); + } + + public Role getTeamBuilderRole() { + return getGuild().getRoleById(this.teamBuilderRole); + } + + public Role getTeamContentRole() { + return getGuild().getRoleById(this.teamContentRole); + } + + public Role getTeamSocialMediaRole() { + return getGuild().getRoleById(this.teamSocialMediaRole); + } + + public Role getRole0() { + return getGuild().getRoleById(this.role0); + } + + public Role getRole1Week() { + return getGuild().getRoleById(this.role1Week); + } + + public Role getRole2Week() { + return getGuild().getRoleById(this.role2Week); + } + + public Role getRole1Month() { + return getGuild().getRoleById(this.role1Month); + } + + public Role getRole3Month() { + return getGuild().getRoleById(this.role3Month); + } + + public Role getRole6Month() { + return getGuild().getRoleById(this.role6Month); + } + + public Role getRole1Year() { + return getGuild().getRoleById(this.role1Year); + } + + public Role getRole2Year() { + return getGuild().getRoleById(this.role2Year); + } + + public Role getRole3Year() { + return getGuild().getRoleById(this.role3Year); + } +} diff --git a/src/main/java/net/turniptales/discord/services/ActivitySyncService.java b/src/main/java/net/turniptales/discord/common/services/ActivitySyncService.java similarity index 76% rename from src/main/java/net/turniptales/discord/services/ActivitySyncService.java rename to src/main/java/net/turniptales/discord/common/services/ActivitySyncService.java index f28a9e0..cfe9b7b 100644 --- a/src/main/java/net/turniptales/discord/services/ActivitySyncService.java +++ b/src/main/java/net/turniptales/discord/common/services/ActivitySyncService.java @@ -1,23 +1,23 @@ -package net.turniptales.discord.services; +package net.turniptales.discord.common.services; import lombok.extern.log4j.Log4j2; import net.dv8tion.jda.api.entities.Activity; -import net.turniptales.discord.Application; import org.springframework.stereotype.Component; import java.util.Timer; import java.util.TimerTask; -import java.util.concurrent.TimeUnit; import static java.lang.System.currentTimeMillis; +import static java.util.concurrent.TimeUnit.MINUTES; import static net.dv8tion.jda.api.entities.Activity.playing; +import static net.turniptales.discord.TurnipTalesDiscord.discordBot; @Log4j2 @Component public class ActivitySyncService { public ActivitySyncService() { - long tenMinutesInMillis = TimeUnit.MINUTES.toMillis(10); + long tenMinutesInMillis = MINUTES.toMillis(10); new Timer().scheduleAtFixedRate(new TimerTask() { @Override @@ -26,7 +26,7 @@ public void run() { log.info("Activity synchronising: started"); Activity activity = playing("auf TurnipTales.net"); - Application.TURNIPTALES_BOT.getPresence().setActivity(activity); + discordBot.getPresence().setActivity(activity); log.info("Activity synchronising: finished in {}ms", currentTimeMillis() - startTime); } diff --git a/src/main/java/net/turniptales/discord/common/services/RoleSyncService.java b/src/main/java/net/turniptales/discord/common/services/RoleSyncService.java new file mode 100644 index 0000000..5687d2e --- /dev/null +++ b/src/main/java/net/turniptales/discord/common/services/RoleSyncService.java @@ -0,0 +1,111 @@ +package net.turniptales.discord.common.services; + +import lombok.extern.log4j.Log4j2; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Role; +import net.turniptales.discord.common.configuration.DiscordBotProperties; +import org.springframework.stereotype.Component; + +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Timer; +import java.util.TimerTask; + +import static java.lang.System.currentTimeMillis; +import static java.util.concurrent.TimeUnit.DAYS; +import static java.util.concurrent.TimeUnit.HOURS; +import static net.turniptales.discord.TurnipTalesDiscord.discordBotProperties; + +@Log4j2 +@Component +public class RoleSyncService { + + public RoleSyncService(DiscordBotProperties discordBotProperties) { + long sixHoursInMillis = HOURS.toMillis(6); + + new Timer().scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + long startTime = currentTimeMillis(); + log.info("Discord role synchronising: started"); + + Guild guild = discordBotProperties.getGuild(); + guild.loadMembers().get().forEach(member -> { + Role highestRoleUserShouldHave = getHighestTimeRole(member.getTimeJoined()); + getTimeRoles().stream() + .filter(role -> !role.equals(highestRoleUserShouldHave)) + .filter(role -> member.getRoles().contains(role)) + .forEach(role -> { + guild.removeRoleFromMember(member, role).queue(); + log.info("Discord role synchronising: Remove role {} from member {}", role.getName(), member.getEffectiveName()); + }); + + Role playerRole = discordBotProperties.getPlayerRole(); + if (!member.getRoles().contains(playerRole) || !member.getRoles().contains(highestRoleUserShouldHave)) { + guild.addRoleToMember(member, playerRole).queue(); + guild.addRoleToMember(member, highestRoleUserShouldHave).queue(); + log.info("Discord role synchronising: Add role {} to member {}", highestRoleUserShouldHave.getName(), member.getEffectiveName()); + } + }); + + log.info("Discord role synchronising: finished in {}ms", currentTimeMillis() - startTime); + } + }, (sixHoursInMillis - currentTimeMillis() % sixHoursInMillis) + HOURS.toMillis(2), sixHoursInMillis); // 4 10 16 22 + log.info("Discord role synchronising: scheduled"); + } + + public static List getTimeRoles() { + return List.of( + discordBotProperties.getRole0(), + discordBotProperties.getRole1Week(), + discordBotProperties.getRole2Week(), + discordBotProperties.getRole1Month(), + discordBotProperties.getRole3Month(), + discordBotProperties.getRole6Month(), + discordBotProperties.getRole1Year(), + discordBotProperties.getRole2Year(), + discordBotProperties.getRole3Year() + ); + } + + public static Role getHighestTimeRole(OffsetDateTime timeJoined) { + Role role = discordBotProperties.getRole0(); + + long joinTimeInMillis = timeJoined.toInstant().toEpochMilli(); + long currentTimeInMillis = currentTimeMillis(); + + if (joinTimeInMillis + DAYS.toMillis(7) <= currentTimeInMillis) { // 1 Woche + role = discordBotProperties.getRole1Week(); + } + + if (joinTimeInMillis + DAYS.toMillis(14) <= currentTimeInMillis) { // 2 Wochen + role = discordBotProperties.getRole2Week(); + } + + if (joinTimeInMillis + DAYS.toMillis(30) <= currentTimeInMillis) { // 1 Monat + role = discordBotProperties.getRole1Month(); + } + + if (joinTimeInMillis + DAYS.toMillis(90) <= currentTimeInMillis) { // 3 Monate + role = discordBotProperties.getRole3Month(); + } + + if (joinTimeInMillis + DAYS.toMillis(180) <= currentTimeInMillis) { // 6 Monate + role = discordBotProperties.getRole6Month(); + } + + if (joinTimeInMillis + DAYS.toMillis(365) <= currentTimeInMillis) { // 1 Jahr + role = discordBotProperties.getRole1Year(); + } + + if (joinTimeInMillis + DAYS.toMillis(730) <= currentTimeInMillis) { // 2 Jahre + role = discordBotProperties.getRole2Year(); + } + + if (joinTimeInMillis + DAYS.toMillis(1460) <= currentTimeInMillis) { // 3 Jahre + role = discordBotProperties.getRole3Year(); + } + + return role; + } +} diff --git a/src/main/java/net/turniptales/discord/common/services/UtilService.java b/src/main/java/net/turniptales/discord/common/services/UtilService.java new file mode 100644 index 0000000..28c0d96 --- /dev/null +++ b/src/main/java/net/turniptales/discord/common/services/UtilService.java @@ -0,0 +1,70 @@ +package net.turniptales.discord.common.services; + +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.events.Event; +import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback; +import net.turniptales.discord.common.api.model.ConnectionDataValue; +import org.springframework.http.ResponseEntity; + +import static java.lang.System.currentTimeMillis; +import static java.util.Objects.requireNonNull; +import static java.util.concurrent.TimeUnit.SECONDS; +import static net.turniptales.discord.TurnipTalesDiscord.api; +import static net.turniptales.discord.TurnipTalesDiscord.discordBotProperties; +import static net.turniptales.discord.common.services.RoleSyncService.getHighestTimeRole; +import static net.turniptales.discord.common.services.RoleSyncService.getTimeRoles; + +public class UtilService { + + public static void sendSelfDeletingMessage(Event event, String message) { + sendSelfDeletingMessage(event, message, 10); + } + + public static void sendSelfDeletingMessage(Event event, String message, int seconds) { + if (event instanceof IReplyCallback iReplyCallback) { + iReplyCallback.reply(message + "\n-# 🚮 ").setEphemeral(true).queue(); + iReplyCallback.getHook().deleteOriginal().queueAfter(seconds, SECONDS); + } + } + + public static void synchronise(Event event, Member member) { + ResponseEntity connectionDataValueResponseEntity = api.getData(member.getId()); + if (!connectionDataValueResponseEntity.getStatusCode().is2xxSuccessful()) { + return; + } + + ConnectionDataValue connectionDataValue = connectionDataValueResponseEntity.getBody(); + Guild guild = discordBotProperties.getGuild(); + + guild.removeRoleFromMember(member, discordBotProperties.getSeniorModeratorRole()).queue(); + guild.removeRoleFromMember(member, discordBotProperties.getModeratorRole()).queue(); + guild.removeRoleFromMember(member, discordBotProperties.getSupporterRole()).queue(); + guild.removeRoleFromMember(member, discordBotProperties.getTeamBuilderRole()).queue(); + guild.removeRoleFromMember(member, discordBotProperties.getTeamContentRole()).queue(); + guild.removeRoleFromMember(member, discordBotProperties.getTeamSocialMediaRole()).queue(); + getTimeRoles().forEach(role -> guild.removeRoleFromMember(member, role).queue()); + + guild.addRoleToMember(member, discordBotProperties.getPlayerRole()).queue(); + + // ignore ADMINISTRATOR and HEAD_OF_DEVELOPMENT due to no permission + // ignore DEVELOPER due to not overwrite support-roles + switch (requireNonNull(connectionDataValue).getRole()) { + case "SENIOR_MODERATOR" -> guild.addRoleToMember(member, discordBotProperties.getSeniorModeratorRole()).queue(); + case "MODERATOR" -> guild.addRoleToMember(member, discordBotProperties.getModeratorRole()).queue(); + case "SUPPORTER" -> guild.addRoleToMember(member, discordBotProperties.getSupporterRole()).queue(); + } + + connectionDataValue.getTeams().forEach(teamName -> { + switch (teamName) { + case "BUILDER" -> guild.addRoleToMember(member, discordBotProperties.getTeamBuilderRole()).queue(); + case "CONTENT" -> guild.addRoleToMember(member, discordBotProperties.getTeamContentRole()).queue(); + case "SOCIAL_MEDIA" -> guild.addRoleToMember(member, discordBotProperties.getTeamSocialMediaRole()).queue(); + } + }); + + guild.addRoleToMember(member, getHighestTimeRole(requireNonNull(member).getTimeJoined())).queue(); + + sendSelfDeletingMessage(event, "Rechte synchronisiert mit Minecraft Account `" + connectionDataValue.getMinecraftName() + "` für: " + member.getAsMention()); + } +} diff --git a/src/main/java/net/turniptales/discord/events/GuildAccessListener.java b/src/main/java/net/turniptales/discord/events/GuildAccessListener.java new file mode 100644 index 0000000..d7f14c6 --- /dev/null +++ b/src/main/java/net/turniptales/discord/events/GuildAccessListener.java @@ -0,0 +1,98 @@ +package net.turniptales.discord.events; + +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; +import net.dv8tion.jda.api.events.guild.GuildBanEvent; +import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent; +import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; + +import java.awt.Color; +import java.util.Date; + +import static java.awt.Color.CYAN; +import static java.util.Objects.nonNull; +import static net.turniptales.discord.TurnipTalesDiscord.discordBot; +import static net.turniptales.discord.TurnipTalesDiscord.discordBotProperties; + +public class GuildAccessListener extends ListenerAdapter { + + @Override + public void onGuildBan(GuildBanEvent e) { + Guild guild = e.getGuild(); + TextChannel communityTextChannel = discordBotProperties.getCommunityTextChannel(); + TextChannel missionControlTextChannel = guild.getSystemChannel(); + if (nonNull(communityTextChannel) && nonNull(missionControlTextChannel)) { + User user = e.getUser(); + Color color = new Color(255, 85, 85); + EmbedBuilder embedBuildercommunityTextChannel = new EmbedBuilder() + .setColor(color) + .setAuthor("TurnipTales", "https://turniptales.net/", discordBot.getSelfUser().getEffectiveAvatarUrl()) + .setTitle("Auf wiedersehen!") + .setDescription(user.getAsMention() + " nimmt sich eine Auszeit.") + .setFooter("Aktuelle Spieler: " + guild.getMemberCount(), user.getEffectiveAvatarUrl()) + .setTimestamp(new Date().toInstant()); + + EmbedBuilder embedBuildermissionControlTextChannel = new EmbedBuilder() + .setColor(color) + .setAuthor("TurnipTales", "https://turniptales.net/", discordBot.getSelfUser().getEffectiveAvatarUrl()) + .setDescription(user.getAsMention() + " wurde gebannt.") + .setFooter("Aktuelle Spieler: " + guild.getMemberCount(), user.getEffectiveAvatarUrl()) + .setTimestamp(new Date().toInstant()); + + communityTextChannel.sendMessageEmbeds(embedBuildercommunityTextChannel.build()).queue(); + missionControlTextChannel.sendMessageEmbeds(embedBuildermissionControlTextChannel.build()).queue(); + } + } + + @Override + public void onGuildMemberRemove(GuildMemberRemoveEvent e) { + Guild guild = e.getGuild(); + User user = e.getUser(); + TextChannel missionControlTextChannel = guild.getSystemChannel(); + if (nonNull(missionControlTextChannel)) { + EmbedBuilder embedBuilder = new EmbedBuilder() + .setColor(new Color(85, 85, 85)) + .setAuthor("TurnipTales", "https://turniptales.net/", discordBot.getSelfUser().getEffectiveAvatarUrl()) + .setDescription(user.getAsMention() + " hat den Server verlassen.") + .setFooter("Aktuelle Spieler: " + guild.getMemberCount(), user.getEffectiveAvatarUrl()) + .setTimestamp(new Date().toInstant()); + + missionControlTextChannel.sendMessageEmbeds(embedBuilder.build()).queue(); + } + } + + @Override + public void onGuildMemberJoin(GuildMemberJoinEvent e) { + Guild guild = e.getGuild(); + TextChannel communityTextChannel = discordBotProperties.getCommunityTextChannel(); + TextChannel missionControlTextChannel = guild.getSystemChannel(); + if (nonNull(communityTextChannel) && nonNull(missionControlTextChannel)) { + Member member = e.getMember(); + + EmbedBuilder embedBuildercommunityTextChannel = new EmbedBuilder() + .setColor(CYAN) + .setAuthor("TurnipTales", "https://turniptales.net/", discordBot.getSelfUser().getEffectiveAvatarUrl()) + .setTitle("Willkommen auf TurnipTales!") + .setDescription(member.getAsMention() + " hat den Server betreten.") + .setFooter("Aktuelle Spieler: " + guild.getMemberCount(), member.getEffectiveAvatarUrl()) + .setTimestamp(new Date().toInstant()); + + EmbedBuilder embedBuildermissionControlTextChannel = new EmbedBuilder() + .setColor(CYAN) + .setAuthor("TurnipTales", "https://turniptales.net/", discordBot.getSelfUser().getEffectiveAvatarUrl()) + .setDescription(member.getAsMention() + " hat den Server betreten.") + .setFooter("Aktuelle Spieler: " + guild.getMemberCount(), member.getEffectiveAvatarUrl()) + .setTimestamp(new Date().toInstant()); + + communityTextChannel.sendMessageEmbeds(embedBuildercommunityTextChannel.build()).queue(); + missionControlTextChannel.sendMessageEmbeds(embedBuildermissionControlTextChannel.build()).queue(); + + guild.addRoleToMember(e.getUser(), discordBotProperties.getPlayerRole()).queue(); + guild.addRoleToMember(e.getUser(), discordBotProperties.getRole0()).queue(); + } + } +} diff --git a/src/main/java/net/turniptales/discord/events/GuildBanEventHandler.java b/src/main/java/net/turniptales/discord/events/GuildBanEventHandler.java deleted file mode 100644 index 8dfe0bb..0000000 --- a/src/main/java/net/turniptales/discord/events/GuildBanEventHandler.java +++ /dev/null @@ -1,32 +0,0 @@ -package net.turniptales.discord.events; - -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.User; -import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; -import net.dv8tion.jda.api.events.guild.GuildBanEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; - -import static java.awt.Color.RED; - -public class GuildBanEventHandler extends ListenerAdapter { - - @Override - public void onGuildBan(GuildBanEvent e) { - Guild guild = e.getGuild(); - TextChannel systemChannel = guild.getSystemChannel(); - if (systemChannel == null) return; - - User user = e.getUser(); - int memberCount = guild.getMemberCount(); - - EmbedBuilder embedBuilder = new EmbedBuilder() - .setColor(RED) - .setTitle(user.getAsTag()) - .setThumbnail(user.getAvatarUrl()) - .setDescription("Wurde von **" + guild.getName() + "** gebannt!"); - - systemChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - systemChannel.getManager().setTopic("Aktuelle Spieler: " + memberCount).queue(); - } -} diff --git a/src/main/java/net/turniptales/discord/events/GuildMemberJoinEventHandler.java b/src/main/java/net/turniptales/discord/events/GuildMemberJoinEventHandler.java deleted file mode 100644 index 6349708..0000000 --- a/src/main/java/net/turniptales/discord/events/GuildMemberJoinEventHandler.java +++ /dev/null @@ -1,36 +0,0 @@ -package net.turniptales.discord.events; - -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.User; -import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; -import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import net.turniptales.discord.Config; - -import static java.awt.Color.GREEN; - -public class GuildMemberJoinEventHandler extends ListenerAdapter { - - @Override - public void onGuildMemberJoin(GuildMemberJoinEvent e) { - Guild guild = e.getGuild(); - TextChannel systemChannel = guild.getSystemChannel(); - if (systemChannel == null) return; - - User user = e.getUser(); - int memberCount = guild.getMemberCount(); - - EmbedBuilder embedBuilder = new EmbedBuilder() - .setColor(GREEN) - .setTitle(user.getAsTag()) - .setThumbnail(user.getAvatarUrl()) - .setDescription("Ist **" + guild.getName() + "** beigetreten!\nHier sind nun **" + memberCount + "** Spieler."); - - systemChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - systemChannel.getManager().setTopic("Aktuelle Spieler: " + memberCount).queue(); - - assert Config.ROLE_0 != null; - guild.addRoleToMember(user, Config.ROLE_0).queue(); - } -} diff --git a/src/main/java/net/turniptales/discord/events/GuildMemberRemoveEventHandler.java b/src/main/java/net/turniptales/discord/events/GuildMemberRemoveEventHandler.java deleted file mode 100644 index ae9cb77..0000000 --- a/src/main/java/net/turniptales/discord/events/GuildMemberRemoveEventHandler.java +++ /dev/null @@ -1,33 +0,0 @@ -package net.turniptales.discord.events; - -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.User; -import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; -import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import net.turniptales.discord.Config; - -import static java.awt.Color.ORANGE; - -public class GuildMemberRemoveEventHandler extends ListenerAdapter { - - @Override - public void onGuildMemberRemove(GuildMemberRemoveEvent e) { - Guild guild = e.getGuild(); - TextChannel systemChannel = Config.SYSTEM_TEXT_CHANNEL; - if (systemChannel == null) return; - - User user = e.getUser(); - int memberCount = guild.getMemberCount(); - - EmbedBuilder embedBuilder = new EmbedBuilder() - .setColor(ORANGE) - .setTitle(user.getAsTag()) - .setThumbnail(user.getAvatarUrl()) - .setDescription("Hat **" + guild.getName() + "** verlassen!\nHier sind nun **" + memberCount + "** Spieler."); - - systemChannel.sendMessageEmbeds(embedBuilder.build()).queue(); - systemChannel.getManager().setTopic("Aktuelle Spieler: " + memberCount).queue(); - } -} diff --git a/src/main/java/net/turniptales/discord/events/TicketEventHandler.java b/src/main/java/net/turniptales/discord/events/TicketEventHandler.java deleted file mode 100644 index 18526c0..0000000 --- a/src/main/java/net/turniptales/discord/events/TicketEventHandler.java +++ /dev/null @@ -1,124 +0,0 @@ -package net.turniptales.discord.events; - -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; -import net.dv8tion.jda.api.entities.channel.middleman.StandardGuildMessageChannel; -import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent; -import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import net.dv8tion.jda.api.interactions.components.ActionRow; -import net.dv8tion.jda.api.interactions.components.Modal; -import net.dv8tion.jda.api.interactions.components.text.TextInput; -import net.dv8tion.jda.api.interactions.components.text.TextInputStyle; - -import java.util.EnumSet; -import java.util.Objects; - -import static net.dv8tion.jda.api.Permission.VIEW_CHANNEL; -import static net.dv8tion.jda.api.entities.emoji.Emoji.fromUnicode; -import static net.dv8tion.jda.api.interactions.components.Modal.create; -import static net.dv8tion.jda.api.interactions.components.buttons.Button.danger; -import static net.dv8tion.jda.api.interactions.components.buttons.Button.secondary; -import static net.dv8tion.jda.api.interactions.components.buttons.Button.success; -import static net.dv8tion.jda.api.interactions.components.text.TextInputStyle.PARAGRAPH; -import static net.turniptales.discord.Config.GUILD; -import static net.turniptales.discord.Config.MODERATOR_ROLE; -import static net.turniptales.discord.Config.SUPPORTER_ROLE; -import static net.turniptales.discord.Config.TICKET_CATEGORY; - -public class TicketEventHandler extends ListenerAdapter { - - @Override - public void onModalInteraction(ModalInteractionEvent e) { - String modalId = e.getModalId(); - - switch (modalId) { - case "ticket_modal": - Member member = e.getMember(); - assert member != null; - String memberId = member.getId(); - String userName = member.getUser().getName(); - - String minecraftName = e.getValue("minecraft_name_input").getAsString(); - String log = e.getValue("topic_input").getAsString(); - - assert GUILD != null; - assert MODERATOR_ROLE != null; - assert SUPPORTER_ROLE != null; - TICKET_CATEGORY.createTextChannel("ticket-" + userName) - .setTopic("Ticket von " + userName + " (" + memberId + ")") - .addPermissionOverride(GUILD.getPublicRole(), null, EnumSet.of(VIEW_CHANNEL)) - .addPermissionOverride(member, EnumSet.of(VIEW_CHANNEL), null) - .addPermissionOverride(MODERATOR_ROLE, EnumSet.of(VIEW_CHANNEL), null) - .addPermissionOverride(SUPPORTER_ROLE, EnumSet.of(VIEW_CHANNEL), null) - .queue(textChannel -> textChannel - .sendMessage("Hey " + member.getAsMention() + "! Danke dass du ein Ticket erstellt hast. Die " + SUPPORTER_ROLE.getAsMention() + " und " + MODERATOR_ROLE.getAsMention() + " werden Dir schnellstmöglich deine Frage beantworten oder Dir helfen.\n" - + "Spieler: " + minecraftName + "\n" - + "Anliegen: " + log) - .addActionRow(success("closeTicket", "Ticket schließen").withEmoji(fromUnicode("U+1F512"))) - .queue(message -> e.reply("Du hast ein Ticket erstellt: " + message.getJumpUrl()).setEphemeral(true).queue())); - break; - } - } - - @Override - public void onButtonInteraction(ButtonInteractionEvent e) { - String componentId = e.getComponentId(); - - switch (componentId) { - case "createTicketAddButton" -> { - Member member = e.getMember(); - assert member != null; - String memberId = member.getId(); - - assert TICKET_CATEGORY != null; - boolean hasTicketChannel = TICKET_CATEGORY.getChannels().stream() - .map(guildChannel -> { - assert GUILD != null; - return GUILD.getTextChannelById(guildChannel.getId()); - }) - .filter(Objects::nonNull) - .map(StandardGuildMessageChannel::getTopic) - .filter(Objects::nonNull) - .anyMatch(s -> s.contains(memberId)); - - if (hasTicketChannel) { - e.reply("Du hast bereits einen Ticket Channel!").setEphemeral(true).queue(); - return; - } - - TextInput minecraftNameTextInput = TextInput.create("minecraft_name_input", "Minecraft Name", TextInputStyle.SHORT) - .setMinLength(3) - .setMaxLength(16) - .setRequired(true) - .build(); - - TextInput logInput = TextInput.create("topic_input", "Anliegen", PARAGRAPH) - .setRequired(true) - .setPlaceholder("Hey, wie kann ich mich im Bauteam bewerben?") - .build(); - - Modal ticketModal = create("ticket_modal", "Neues Ticket") - .addActionRows(ActionRow.of(minecraftNameTextInput), ActionRow.of(logInput)) - .build(); - - e.replyModal(ticketModal).queue(); - } - case "closeTicket" -> { - TextChannel textChannel = e.getChannel().asTextChannel(); - if (Objects.equals(textChannel.getParentCategory(), TICKET_CATEGORY) && textChannel.getName().startsWith("ticket-")) { - e.reply("Möchtest Du das Ticket wirklich schließen?") - .addActionRow(danger("closeTicketConfirm", "Bestätigen"), secondary("closeTicketAbort", "Abbrechen")) - .queue(); - } - } - case "closeTicketConfirm" -> { - TextChannel textChannel = e.getChannel().asTextChannel(); - if (Objects.equals(textChannel.getParentCategory(), TICKET_CATEGORY) && textChannel.getName().startsWith("ticket-")) { - textChannel.delete().queue(); - } - } - case "closeTicketAbort" -> e.getMessage().delete().queue(); - } - } -} diff --git a/src/main/java/net/turniptales/discord/services/RoleSyncService.java b/src/main/java/net/turniptales/discord/services/RoleSyncService.java deleted file mode 100644 index a80b172..0000000 --- a/src/main/java/net/turniptales/discord/services/RoleSyncService.java +++ /dev/null @@ -1,90 +0,0 @@ -package net.turniptales.discord.services; - -import lombok.extern.log4j.Log4j2; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Role; -import net.turniptales.discord.Config; -import org.springframework.stereotype.Component; - -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.TimeUnit; - -import static java.lang.System.currentTimeMillis; -import static java.util.concurrent.TimeUnit.HOURS; - -@Log4j2 -@Component -public class RoleSyncService { - - public RoleSyncService() { - long sixHoursInMillis = HOURS.toMillis(6); - - new Timer().scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - long startTime = currentTimeMillis(); - log.info("Discord role synchronising: started"); - - Guild guild = Config.GUILD; - - assert guild != null; - guild.loadMembers().get().forEach(member -> getRolesUserShouldHave(member.getTimeJoined()).stream() - .filter(role -> !member.getRoles().contains(role)) - .forEach(role -> { - guild.addRoleToMember(member, role).queue(); - log.info("Discord role synchronising: Add role {} to member {}", role.getName(), member.getEffectiveName()); - })); - - log.info("Discord role synchronising: finished in {}ms", currentTimeMillis() - startTime); - } - }, (sixHoursInMillis - currentTimeMillis() % sixHoursInMillis) + HOURS.toMillis(2), sixHoursInMillis); // 4 10 16 22 - log.info("Discord role synchronising: scheduled"); - } - - private Collection getRolesUserShouldHave(OffsetDateTime timeJoined) { - assert Config.ROLE_0 != null; - Collection roles = new ArrayList<>(List.of(Config.ROLE_0)); - - long joinTimeInMillis = timeJoined.toInstant().toEpochMilli(); - long currentTimeInMillis = currentTimeMillis(); - - if (joinTimeInMillis + TimeUnit.DAYS.toMillis(7) <= currentTimeInMillis) { // 1 Woche - roles.add(Config.ROLE_1_WEEK); - } - - if (joinTimeInMillis + TimeUnit.DAYS.toMillis(14) <= currentTimeInMillis) { // 2 Wochen - roles.add(Config.ROLE_2_WEEK); - } - - if (joinTimeInMillis + TimeUnit.DAYS.toMillis(30) <= currentTimeInMillis) { // 1 Monat - roles.add(Config.ROLE_1_MONTH); - } - - if (joinTimeInMillis + TimeUnit.DAYS.toMillis(90) <= currentTimeInMillis) { // 3 Monate - roles.add(Config.ROLE_3_MONTH); - } - - if (joinTimeInMillis + TimeUnit.DAYS.toMillis(180) <= currentTimeInMillis) { // 6 Monate - roles.add(Config.ROLE_6_MONTH); - } - - if (joinTimeInMillis + TimeUnit.DAYS.toMillis(365) <= currentTimeInMillis) { // 1 Jahr - roles.add(Config.ROLE_1_YEAR); - } - - if (joinTimeInMillis + TimeUnit.DAYS.toMillis(730) <= currentTimeInMillis) { // 2 Jahre - roles.add(Config.ROLE_2_YEAR); - } - - if (joinTimeInMillis + TimeUnit.DAYS.toMillis(1460) <= currentTimeInMillis) { // 3 Jahre - roles.add(Config.ROLE_3_YEAR); - } - - return roles; - } -} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 59a4293..694637b 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,14 +1,34 @@ server.port=9000 -server.ssl.enabled=true -# The format used for the keystore. It could be set to JKS in case it is a JKS file -server.ssl.key-store-type=PKCS12 -# The path to the keystore containing the certificate -server.ssl.key-store=classpath:keystore/unicacityaddon.p12 -# The password used to generate the certificate -server.ssl.key-store-password=d8d8ab09ac4c457d68489c1840567fa640befbed -# The alias mapped to the certificate -server.ssl.key-password=d8d8ab09ac4c457d68489c1840567fa640befbed + server.error.path=/error server.error.whitelabel.enabled=false + spring.main.banner-mode=off -spring.output.ansi.enabled=ALWAYS \ No newline at end of file +spring.output.ansi.enabled=ALWAYS + +discord.guild.id=1008928645185810463 + +discord.guild.channels.community-text-channel=1008929885764472952 +discord.guild.channels.ticket-text-channel=1009477703990267954 + +discord.guild.categories.ticket-category=1009478372847517727 + +discord.guild.roles.player-role=1190675464549847110 +discord.guild.roles.senior-moderator-role=1208149723547050004 +discord.guild.roles.moderator-role=1025864289346658355 +discord.guild.roles.supporter-role=1009477020427747408 +discord.guild.roles.team-builder-role=1169558449038831707 +discord.guild.roles.team-content-role=1234578921413148713 +discord.guild.roles.team-social-media-role=1191040099794833448 + +discord.guild.roles.role-0=1134487019058372649 +discord.guild.roles.role-1-week=1134487221349650462 +discord.guild.roles.role-2-week=1134487277205192744 +discord.guild.roles.role-1-month=1134487413125820477 +discord.guild.roles.role-3-month=1134487461452583043 +discord.guild.roles.role-6-month=1134487539588268094 +discord.guild.roles.role-1-year=1134487593585745920 +discord.guild.roles.role-2-year=1134487644110336010 +discord.guild.roles.role-3-year=1134487702864142356 + +# Discord Bot Token generated by GitHub Action