commit d89ddafcccf6197e4b2ce4a745640716e8016fb8 Author: Melaine Gérard Date: Thu Nov 21 20:28:34 2024 +0100 :sparkles: Ajout Commande pour envoyer des messages dans un channel + Ajout role par défaut à tout le monde diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..b6db56c --- /dev/null +++ b/.env.example @@ -0,0 +1,4 @@ +BOT_TOKEN= +GUILD_ID= +DEFAULT_ROLE_ID= +ROLE_ID= \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f91f646 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,12 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + +# Binary files should be left untouched +*.jar binary + diff --git a/.gitea/workflows/build-docker.yml b/.gitea/workflows/build-docker.yml new file mode 100644 index 0000000..0d12b3b --- /dev/null +++ b/.gitea/workflows/build-docker.yml @@ -0,0 +1,23 @@ +name: Build and Push Docker Image + +on: + push: + tags: + - '*' + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + - name: Build and Push with Kaniko + uses: aevea/action-kaniko@master + with: + image: camelia-studio/Kiss-Shot_Acerola-Orion_Heart-Under-Blade + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + registry: git.crystalyx.net + tag: ${{ gitea.ref_name }} + tag_with_latest: true \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..30c6cd5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +.gradle +build +.idea/ +.vscode/ +.fleet/ +*.iml + +.env +.env.* +!.env.example \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..b34b824 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,11 @@ +FROM eclipse-temurin:21-alpine AS build +WORKDIR /src +COPY . . + +RUN ./gradlew clean shadowJar +FROM eclipse-temurin:21-alpine AS runner +RUN mkdir -p /app +WORKDIR /app +COPY --from=build /src/build/libs/kiss-shot-acerola.jar /app/kiss-shot-acerola.jar + +CMD ["java", "-jar", "kiss-shot-acerola.jar"] \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..b1b94a8 --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +# Kiss-Shot Acerola-Orion Heart-Under-Blade + +**Kiss-Shot Acerola-Orion Heart-Under-Blade** est un bot Discord qui a pour but de faciliter la gestion de serveurs Discord. Cet outil est développé par la branche **CILA** de l'association **Camélia Studio**. + + +Liens utiles : + + +- Site web Camélia Studio : https://camelia-studio.org +- Site web CILA : https://cila.camelia-studio.org +- Notre serveur Discord : https://discord.gg/nBuZ9vJ \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..f2c04b0 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,38 @@ +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar + +plugins { + id("java") + id("com.github.johnrengelman.shadow") version "8.1.1" +} + +group = "fr.melaine.gerard.kiss.shot.acerola" +version = "1.0-SNAPSHOT" + +repositories { + mavenCentral() +} + +dependencies { + implementation("io.github.cdimascio:dotenv-kotlin:6.4.2") + implementation("net.dv8tion:JDA:5.2.1") + implementation("ch.qos.logback:logback-classic:1.5.12") +} + + +tasks.withType { + options.encoding = "UTF-8" +} + +tasks.withType { + manifest { + attributes["Main-Class"] = "org.camelia.studio.kiss.shot.acerola.KissShotAcerola" + } + + archiveFileName.set("kiss-shot-acerola.jar") +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9d7b357 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Thu Nov 21 19:29:52 CET 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/licence.txt b/licence.txt new file mode 100644 index 0000000..456b86f --- /dev/null +++ b/licence.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright © 2024 Camélia Studio, https://camelia-studio.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..4dd8dd3 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,2 @@ +rootProject.name = "Kiss-Shot-Acerola" + diff --git a/src/main/java/org/camelia/studio/kiss/shot/acerola/KissShotAcerola.java b/src/main/java/org/camelia/studio/kiss/shot/acerola/KissShotAcerola.java new file mode 100644 index 0000000..3fcafd7 --- /dev/null +++ b/src/main/java/org/camelia/studio/kiss/shot/acerola/KissShotAcerola.java @@ -0,0 +1,42 @@ +package org.camelia.studio.kiss.shot.acerola; + +import org.camelia.studio.kiss.shot.acerola.listeners.ReadyListener; +import org.camelia.studio.kiss.shot.acerola.managers.ListenerManager; +import org.camelia.studio.kiss.shot.acerola.utils.Configuration; +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.JDABuilder; +import net.dv8tion.jda.api.requests.GatewayIntent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class KissShotAcerola { + private static JDA jda; + private static final Logger logger = LoggerFactory.getLogger(KissShotAcerola.class); + + public static void main(String[] args) { + try { + Configuration.getInstance(); + + jda = JDABuilder.createDefault(Configuration.getInstance().getDotenv().get("BOT_TOKEN")) + .addEventListeners(new ReadyListener()) + .enableIntents(GatewayIntent.getIntents(GatewayIntent.ALL_INTENTS)) + .build() + .awaitReady() + ; + + new ListenerManager().registerListeners(jda); + + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + jda.shutdown(); + })); + } catch (Exception e) { + logger.error("Une erreur est survenue lors de l'exécution du bot : {}", e.getMessage()); + System.exit(1); + } + } + + public static JDA getJda() { + return jda; + } + +} \ No newline at end of file diff --git a/src/main/java/org/camelia/studio/kiss/shot/acerola/commands/utils/MsgSendCommand.java b/src/main/java/org/camelia/studio/kiss/shot/acerola/commands/utils/MsgSendCommand.java new file mode 100644 index 0000000..37bd3bd --- /dev/null +++ b/src/main/java/org/camelia/studio/kiss/shot/acerola/commands/utils/MsgSendCommand.java @@ -0,0 +1,90 @@ + +package org.camelia.studio.kiss.shot.acerola.commands.utils; + +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.Message; +import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.entities.channel.ChannelType; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.interactions.commands.OptionMapping; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.OptionData; +import net.dv8tion.jda.api.utils.data.DataObject; +import org.camelia.studio.kiss.shot.acerola.interfaces.ISlashCommand; +import org.camelia.studio.kiss.shot.acerola.utils.Configuration; +import org.camelia.studio.kiss.shot.acerola.utils.URLFileReader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.Objects; + +public class MsgSendCommand implements ISlashCommand { + private final Logger logger = LoggerFactory.getLogger(MsgSendCommand.class); + @Override + public String getName() { + return "msgsend"; + } + + @Override + public String getDescription() { + return "Permet d'envoyer un message en tant que le bot"; + } + + @Override + public List getOptions() { + return List.of( + new OptionData(OptionType.CHANNEL, "channel", "Le salon où envoyer le message", true).setChannelTypes(ChannelType.TEXT), + new OptionData(OptionType.STRING, "message", "Le message à envoyer", false), + new OptionData(OptionType.ATTACHMENT, "attachment", "L'embed à envoyer", false) + + ); + } + + @Override + public void execute(SlashCommandInteractionEvent event) { + + if (!event.isFromGuild()) { + event.reply("Cette commande ne peut être utilisée que sur un serveur !").queue(); + return; + } + Role roleNeeded = Objects.requireNonNull(event.getGuild()).getRoleById(Configuration.getInstance().getDotenv().get("ROLE_ID")); + if (roleNeeded == null) { + event.reply("Impossible de trouver le rôle nécessaire pour utiliser cette commande !").queue(); + return; + } + + if (event.getMember() == null || !event.getMember().getRoles().contains(roleNeeded)) { + event.reply("Vous n'avez pas la permission d'utiliser cette commande !").queue(); + return; + } + + TextChannel channel = Objects.requireNonNull(event.getOption("channel")).getAsChannel().asTextChannel(); + + OptionMapping message = event.getOption("message"); + OptionMapping attachment = event.getOption("attachment"); + + if (message == null && attachment == null) { + event.reply("Vous devez spécifier un message ou un embed à envoyer !").queue(); + return; + } + try { + if (message != null) { + channel.sendMessage(message.getAsString()).queue(); + } + + if (attachment != null) { + Message.Attachment file = attachment.getAsAttachment(); + String content = URLFileReader.readFileFromURL(file.getUrl()); + + channel.sendMessageEmbeds(EmbedBuilder.fromData(DataObject.fromJson(content)).build()).queue(); + } + + event.reply("Message envoyé !").queue(); + } catch (Exception e) { + event.reply("Message envoyé !").queue(); + logger.error("Erreur lors de l'envoi du message", e); + } + } +} diff --git a/src/main/java/org/camelia/studio/kiss/shot/acerola/commands/utils/PingCommand.java b/src/main/java/org/camelia/studio/kiss/shot/acerola/commands/utils/PingCommand.java new file mode 100644 index 0000000..e85fbff --- /dev/null +++ b/src/main/java/org/camelia/studio/kiss/shot/acerola/commands/utils/PingCommand.java @@ -0,0 +1,21 @@ +package org.camelia.studio.kiss.shot.acerola.commands.utils; + +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import org.camelia.studio.kiss.shot.acerola.interfaces.ISlashCommand; + +public class PingCommand implements ISlashCommand { + @Override + public String getName() { + return "ping"; + } + + @Override + public String getDescription() { + return "Envoie pong !"; + } + + @Override + public void execute(SlashCommandInteractionEvent event) { + event.reply("Pong !").queue(); + } +} diff --git a/src/main/java/org/camelia/studio/kiss/shot/acerola/interfaces/ISlashCommand.java b/src/main/java/org/camelia/studio/kiss/shot/acerola/interfaces/ISlashCommand.java new file mode 100644 index 0000000..da9b3ce --- /dev/null +++ b/src/main/java/org/camelia/studio/kiss/shot/acerola/interfaces/ISlashCommand.java @@ -0,0 +1,16 @@ +package org.camelia.studio.kiss.shot.acerola.interfaces; + +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.interactions.commands.build.OptionData; + +import java.util.List; + +public interface ISlashCommand { + String getName(); + String getDescription(); + void execute(SlashCommandInteractionEvent event); + default List getOptions() { + return List.of(); + } +} + diff --git a/src/main/java/org/camelia/studio/kiss/shot/acerola/listeners/GuildMemberJoinListener.java b/src/main/java/org/camelia/studio/kiss/shot/acerola/listeners/GuildMemberJoinListener.java new file mode 100644 index 0000000..3c421b1 --- /dev/null +++ b/src/main/java/org/camelia/studio/kiss/shot/acerola/listeners/GuildMemberJoinListener.java @@ -0,0 +1,23 @@ +package org.camelia.studio.kiss.shot.acerola.listeners; + +import org.camelia.studio.kiss.shot.acerola.utils.Configuration; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; + +import java.awt.*; + + +public class GuildMemberJoinListener extends ListenerAdapter { + @Override + public void onGuildMemberJoin(GuildMemberJoinEvent event) { + Member member = event.getMember(); + + Role role = event.getGuild().getRoleById(Configuration.getInstance().getDotenv().get("DEFAULT_ROLE_ID")); + + if (role != null) { + event.getGuild().addRoleToMember(member, role).queue(); + } + } +} diff --git a/src/main/java/org/camelia/studio/kiss/shot/acerola/listeners/ReadyListener.java b/src/main/java/org/camelia/studio/kiss/shot/acerola/listeners/ReadyListener.java new file mode 100644 index 0000000..4096075 --- /dev/null +++ b/src/main/java/org/camelia/studio/kiss/shot/acerola/listeners/ReadyListener.java @@ -0,0 +1,44 @@ +package org.camelia.studio.kiss.shot.acerola.listeners; + +import org.camelia.studio.kiss.shot.acerola.utils.Configuration; +import net.dv8tion.jda.api.JDA; +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.events.session.ReadyEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ReadyListener extends ListenerAdapter { + private static final Logger logger = LoggerFactory.getLogger(ReadyListener.class); + + @Override + public void onReady(ReadyEvent event) { + logger.info("Connecté en tant que {}", event.getJDA().getSelfUser().getAsTag()); + initRole(event.getJDA()); + } + + private void initRole(JDA jda) { + Guild guild = jda.getGuildById(Configuration.getInstance().getDotenv().get("GUILD_ID")); + if (guild != null) { + Role role = guild.getRoleById(Configuration.getInstance().getDotenv().get("DEFAULT_ROLE_ID")); + + if (role == null) { + logger.error("Impossible de trouver le rôle par défaut"); + return; + } + guild.loadMembers().onSuccess(members -> { + for (Member member : members) { + if (member.getRoles().contains(role)) { + continue; + } + + guild.addRoleToMember(member, role).queue(); + + logger.info("Rôle ajouté à {}", member.getUser().getAsTag()); + } + }); + } + } +} diff --git a/src/main/java/org/camelia/studio/kiss/shot/acerola/listeners/SlashCommandListener.java b/src/main/java/org/camelia/studio/kiss/shot/acerola/listeners/SlashCommandListener.java new file mode 100644 index 0000000..3618e70 --- /dev/null +++ b/src/main/java/org/camelia/studio/kiss/shot/acerola/listeners/SlashCommandListener.java @@ -0,0 +1,21 @@ +package org.camelia.studio.kiss.shot.acerola.listeners; + +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import org.camelia.studio.kiss.shot.acerola.managers.CommandManager; +import org.jetbrains.annotations.NotNull; + +public class SlashCommandListener extends ListenerAdapter { + private final CommandManager commandManager; + + public SlashCommandListener() { + commandManager = new CommandManager(); + commandManager.registerCommands(); + } + + + @Override + public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) { + commandManager.handleCommand(event.getName(), event); + } +} diff --git a/src/main/java/org/camelia/studio/kiss/shot/acerola/managers/CommandManager.java b/src/main/java/org/camelia/studio/kiss/shot/acerola/managers/CommandManager.java new file mode 100644 index 0000000..d637bef --- /dev/null +++ b/src/main/java/org/camelia/studio/kiss/shot/acerola/managers/CommandManager.java @@ -0,0 +1,64 @@ +package org.camelia.studio.kiss.shot.acerola.managers; + + +import org.camelia.studio.kiss.shot.acerola.KissShotAcerola; +import org.camelia.studio.kiss.shot.acerola.interfaces.ISlashCommand; +import org.camelia.studio.kiss.shot.acerola.utils.Configuration; +import org.camelia.studio.kiss.shot.acerola.utils.ReflectionUtils; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.interactions.commands.build.Commands; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +public class CommandManager { + private final List slashCommands; + private final Logger logger = LoggerFactory.getLogger(CommandManager.class); + + public CommandManager() { + slashCommands = ReflectionUtils.loadClasses( + "org.camelia.studio.kiss.shot.acerola.commands", + ISlashCommand.class + ); + } + + public void registerCommands() { + Guild guild = KissShotAcerola + .getJda() + .getGuildById(Configuration.getInstance().getDotenv().get("GUILD_ID")); + + if (guild == null) { + logger.error("Impossible de trouver le serveur Discord"); + return; + } + + guild + .updateCommands() + .addCommands( + slashCommands + .stream() + .map( + (cmd) -> Commands.slash(cmd.getName(), cmd.getDescription()).addOptions(cmd.getOptions()) + ) + .toList() + ) + .queue(); + + + logger.info("Enregistrement de {} commandes", slashCommands.size()); + } + + public void handleCommand(String commandName, SlashCommandInteractionEvent event) { + + for (ISlashCommand command : slashCommands) { + if (command.getName().equals(commandName)) { + command.execute(event); + return; + } + } + event.reply("Commande inconnue !").setEphemeral(true).queue(); + } +} + diff --git a/src/main/java/org/camelia/studio/kiss/shot/acerola/managers/ListenerManager.java b/src/main/java/org/camelia/studio/kiss/shot/acerola/managers/ListenerManager.java new file mode 100644 index 0000000..19cdb16 --- /dev/null +++ b/src/main/java/org/camelia/studio/kiss/shot/acerola/managers/ListenerManager.java @@ -0,0 +1,34 @@ +package org.camelia.studio.kiss.shot.acerola.managers; + +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.hooks.ListenerAdapter; +import org.camelia.studio.kiss.shot.acerola.listeners.GuildMemberJoinListener; +import org.camelia.studio.kiss.shot.acerola.listeners.SlashCommandListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +public class ListenerManager { + private final List listener; + private final Logger logger = LoggerFactory.getLogger(ListenerManager.class.getName()); + public ListenerManager() { + listener = new ArrayList<>(); + + addListener(new SlashCommandListener()); + addListener(new GuildMemberJoinListener()); + } + + public void registerListeners(JDA jda) { + for (ListenerAdapter listenerAdapter : listener) { + jda.addEventListener(listenerAdapter); + + logger.info("Listener {} enregistré !", listenerAdapter.getClass().getSimpleName()); + } + } + + private void addListener(ListenerAdapter listenerAdapter) { + this.listener.add(listenerAdapter); + } +} diff --git a/src/main/java/org/camelia/studio/kiss/shot/acerola/utils/Configuration.java b/src/main/java/org/camelia/studio/kiss/shot/acerola/utils/Configuration.java new file mode 100644 index 0000000..4d413a7 --- /dev/null +++ b/src/main/java/org/camelia/studio/kiss/shot/acerola/utils/Configuration.java @@ -0,0 +1,23 @@ +package org.camelia.studio.kiss.shot.acerola.utils; + +import io.github.cdimascio.dotenv.Dotenv; + +public class Configuration { + private static Configuration instance; + private final Dotenv dotenv; + + public Configuration() { + this.dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load(); + } + + public static Configuration getInstance() { + if (instance == null) { + instance = new Configuration(); + } + return instance; + } + + public Dotenv getDotenv() { + return dotenv; + } +} diff --git a/src/main/java/org/camelia/studio/kiss/shot/acerola/utils/ReflectionUtils.java b/src/main/java/org/camelia/studio/kiss/shot/acerola/utils/ReflectionUtils.java new file mode 100644 index 0000000..94a7635 --- /dev/null +++ b/src/main/java/org/camelia/studio/kiss/shot/acerola/utils/ReflectionUtils.java @@ -0,0 +1,101 @@ +package org.camelia.studio.kiss.shot.acerola.utils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +public class ReflectionUtils { + private static final Logger logger = LoggerFactory.getLogger(ReflectionUtils.class); + + public static List loadClasses(String packageName, Class targetType) { + List instances = new ArrayList<>(); + String path = packageName.replace('.', '/'); + + try { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + Enumeration resources = classLoader.getResources(path); + + while (resources.hasMoreElements()) { + URL resource = resources.nextElement(); + + if (resource.getProtocol().equals("jar")) { + processJarFile(resource, path, packageName, targetType, instances); + } else { + processDirectory(new File(resource.toURI()), packageName, targetType, instances); + } + } + } catch (Exception e) { + logger.error("Erreur lors du scan du package {} : {}", packageName, e.getMessage()); + } + + return instances; + } + + private static void processJarFile(URL resource, String path, String packageName, + Class targetType, List instances) throws IOException { + String jarPath = resource.getPath().substring(5, resource.getPath().indexOf("!")); + jarPath = URLDecoder.decode(jarPath, StandardCharsets.UTF_8); + + try (JarFile jar = new JarFile(jarPath)) { + Enumeration entries = jar.entries(); + + while (entries.hasMoreElements()) { + JarEntry entry = entries.nextElement(); + String entryName = entry.getName(); + + if (entryName.startsWith(path) && entryName.endsWith(".class")) { + String className = entryName.substring(0, entryName.length() - 6) + .replace('/', '.'); + loadClass(className, targetType, instances); + } + } + } + } + + private static void processDirectory(File directory, String packageName, + Class targetType, List instances) { + if (!directory.exists()) { + return; + } + + File[] files = directory.listFiles(); + if (files != null) { + for (File file : files) { + if (file.isDirectory()) { + processDirectory(file, packageName + "." + file.getName(), + targetType, instances); + } else if (file.getName().endsWith(".class")) { + String className = packageName + '.' + + file.getName().substring(0, file.getName().length() - 6); + loadClass(className, targetType, instances); + } + } + } + } + + @SuppressWarnings("unchecked") + private static void loadClass(String className, Class targetType, List instances) { + try { + Class clazz = Class.forName(className); + + if (targetType.isAssignableFrom(clazz) && !clazz.isInterface() && + !java.lang.reflect.Modifier.isAbstract(clazz.getModifiers())) { + instances.add((T) clazz.getDeclaredConstructor().newInstance()); + logger.debug("Classe chargée : {}", className); + } + } catch (Exception e) { + logger.error("Erreur lors du chargement de la classe {} : {}", + className, e.getMessage()); + } + } +} \ No newline at end of file diff --git a/src/main/java/org/camelia/studio/kiss/shot/acerola/utils/URLFileReader.java b/src/main/java/org/camelia/studio/kiss/shot/acerola/utils/URLFileReader.java new file mode 100644 index 0000000..9b760ad --- /dev/null +++ b/src/main/java/org/camelia/studio/kiss/shot/acerola/utils/URLFileReader.java @@ -0,0 +1,26 @@ +package org.camelia.studio.kiss.shot.acerola.utils; +import java.net.URI; +import java.net.URL; +import java.net.HttpURLConnection; +import java.io.BufferedReader; +import java.io.InputStreamReader; + +public class URLFileReader { + public static String readFileFromURL(String fileUrl) throws Exception { + URL url = new URI(fileUrl).toURL(); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + StringBuilder content = new StringBuilder(); + + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(conn.getInputStream()))) { + String line; + while ((line = reader.readLine()) != null) { + content.append(line).append("\n"); + } + } finally { + conn.disconnect(); + } + + return content.toString(); + } +} \ No newline at end of file diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000..c9155dc --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,14 @@ + + + + + %d{HH:mm:ss.SSS} %boldCyan(%-34.-34thread) %red(%10.10X{jda.shard}) %boldGreen(%-15.-15logger{0}) %highlight(%-6level) %msg%n + + + + + + + + + \ No newline at end of file