Initialisation du projet + rattrapage de l'ancien code sur la nouvelle base

This commit is contained in:
Melaine Gérard 2024-11-16 12:56:41 +01:00
commit eca13f9a3a
35 changed files with 1524 additions and 0 deletions

9
.dockerignore Normal file
View File

@ -0,0 +1,9 @@
.idea/
.vscode/
.fleet/
*.iml
.git
build/
.gradle/

8
.env.example Normal file
View File

@ -0,0 +1,8 @@
BOT_TOKEN=
GUILD_ID=
DB_URL=jdbc:postgresql://localhost:5433/gachamelia
DB_USER=postgres
DB_PASSWORD=gachamelia
WELCOME_CHANNEL=

12
.gitattributes vendored Normal file
View File

@ -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

View File

@ -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/gachamelia
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_PASSWORD }}
registry: git.crystalyx.net
tag: ${{ gitea.ref_name }}
tag_with_latest: true

10
.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
.gradle
build
.idea/
.vscode/
.fleet/
*.iml
.env
.env.*
!.env.example

11
Dockerfile Normal file
View File

@ -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/gachamelia.jar /app/gachamelia.jar
CMD ["java", "-jar", "gachamelia.jar"]

15
README.md Normal file
View File

@ -0,0 +1,15 @@
# Gachamélia
Transforme ton serveur Discord en *gacha* géant !
**Gachamélia** est un bot Discord qui va transformer ton serveur en un véritable *gacha* ! 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

41
build.gradle.kts Normal file
View File

@ -0,0 +1,41 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
plugins {
id("java")
id("com.github.johnrengelman.shadow") version "8.1.1"
}
group = "org.camelia.studio.gachamelia"
version = "0.0.1"
repositories {
mavenCentral()
}
tasks.withType<JavaCompile> {
options.encoding = "UTF-8"
}
tasks.withType<ShadowJar> {
manifest {
attributes["Main-Class"] = "org.camelia.studio.gachamelia.Gachamelia"
}
archiveFileName.set("gachamelia.jar")
}
dependencies {
implementation("org.hibernate:hibernate-core:6.6.2.Final")
implementation("org.hibernate:hibernate-hikaricp:6.6.2.Final")
implementation("org.postgresql:postgresql:42.7.4")
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")
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}

13
docker-compose.yml Normal file
View File

@ -0,0 +1,13 @@
services:
postgres:
image: postgres:17
environment:
POSTGRES_PASSWORD: gachamelia
POSTGRES_DB: gachamelia
ports:
- "5433:5432"
volumes:
- postgres_gachamelia_data:/var/lib/postgresql/data
volumes:
postgres_gachamelia_data:

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

252
gradlew vendored Executable file
View File

@ -0,0 +1,252 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
gradlew.bat vendored Normal file
View File

@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

21
licence.txt Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright © 2024 Camélia Studio, https://camelia-studio.org <https://discord.gg/nBuZ9vJ>
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.

View File

@ -0,0 +1,79 @@
package org.camelia.studio.gachamelia;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.requests.GatewayIntent;
import org.camelia.studio.gachamelia.db.HibernateConfig;
import org.camelia.studio.gachamelia.listeners.ReadyListener;
import org.camelia.studio.gachamelia.managers.ListenerManager;
import org.camelia.studio.gachamelia.models.User;
import org.camelia.studio.gachamelia.repossitories.RankRepository;
import org.camelia.studio.gachamelia.services.RankService;
import org.camelia.studio.gachamelia.services.UserService;
import org.camelia.studio.gachamelia.utils.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class Gachamelia {
private static JDA jda;
private static final Logger logger = LoggerFactory.getLogger(Gachamelia.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);
// Initialisation de la base de données
initDatabase();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
HibernateConfig.shutdown();
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;
}
public static void initDatabase() {
if (!RankRepository.getInstance().findAll().isEmpty()) {
Guild guild = jda.getGuildById(Configuration.getInstance().getDotenv().get("GUILD_ID"));
if (guild != null) {
List<Member> members = guild.getMembers();
for (Member member : members) {
User user = UserService.getInstance().getOrCreateUser(member.getId());
if (user.getRank() == null) {
user.setRank(RankService.getInstance().getRandomRank());
UserService.getInstance().updateUser(user);
}
logger.info("Utilisateur {} initialisé", member.getUser().getAsTag());
}
}
} else {
logger.error("Aucun rang n'a été trouvé dans la base de données");
System.exit(1);
}
}
}

View File

@ -0,0 +1,20 @@
package org.camelia.studio.gachamelia.commands.utils;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import org.camelia.studio.gachamelia.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.getHook().editOriginal("Pong !").queue();
}
}

View File

@ -0,0 +1,85 @@
package org.camelia.studio.gachamelia.db;
import io.github.cdimascio.dotenv.Dotenv;
import org.camelia.studio.gachamelia.interfaces.IEntity;
import org.camelia.studio.gachamelia.utils.ReflectionUtils;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Properties;
public class HibernateConfig {
private static final Logger logger = LoggerFactory.getLogger(HibernateConfig.class);
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
logger.info("Initializing Hibernate SessionFactory");
Dotenv dotenv = Dotenv.load();
Properties props = new Properties();
// Configuration Hibernate
props.put(Environment.HBM2DDL_AUTO, "update"); // On utilise validate au lieu de update
props.put(Environment.GLOBALLY_QUOTED_IDENTIFIERS, "true");
// Configuration HikariCP
props.put("hibernate.connection.provider_class",
"org.hibernate.hikaricp.internal.HikariCPConnectionProvider");
props.put("hibernate.hikari.minimumIdle", "5");
props.put("hibernate.hikari.maximumPoolSize", "10");
props.put("hibernate.hikari.idleTimeout", "300000");
props.put("hibernate.hikari.dataSourceClassName",
"org.postgresql.ds.PGSimpleDataSource");
props.put("hibernate.hikari.dataSource.url", dotenv.get("DB_URL"));
props.put("hibernate.hikari.dataSource.user", dotenv.get("DB_USER"));
props.put("hibernate.hikari.dataSource.password", dotenv.get("DB_PASSWORD"));
Configuration configuration = new Configuration();
configuration.setProperties(props);
List<IEntity> entities = ReflectionUtils.loadClasses(
"org.camelia.studio.gachamelia.models",
IEntity.class
);
for (IEntity entity : entities) {
configuration.addAnnotatedClass(entity.getClass());
}
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
logger.info("Hibernate SessionFactory initialized successfully");
} catch (Exception e) {
logger.error("Failed to initialize Hibernate SessionFactory", e);
throw new RuntimeException("Failed to initialize Hibernate SessionFactory", e);
}
}
return sessionFactory;
}
public static void shutdown() {
logger.info("Shutting down database connections");
if (sessionFactory != null && !sessionFactory.isClosed()) {
try {
sessionFactory.close();
logger.info("SessionFactory closed successfully");
} catch (Exception e) {
logger.error("Error closing SessionFactory", e);
}
}
}
}

View File

@ -0,0 +1,4 @@
package org.camelia.studio.gachamelia.interfaces;
public interface IEntity {
}

View File

@ -0,0 +1,16 @@
package org.camelia.studio.gachamelia.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<OptionData> getOptions() {
return List.of();
}
}

View File

@ -0,0 +1,58 @@
package org.camelia.studio.gachamelia.listeners;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Role;
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 org.camelia.studio.gachamelia.models.User;
import org.camelia.studio.gachamelia.models.WelcomeMessage;
import org.camelia.studio.gachamelia.services.RankService;
import org.camelia.studio.gachamelia.services.UserService;
import org.camelia.studio.gachamelia.utils.Configuration;
import org.camelia.studio.gachamelia.utils.MessageUtils;
import java.awt.*;
import java.util.Map;
public class GuildMemberJoinListener extends ListenerAdapter {
@Override
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
Member member = event.getMember();
User user = UserService.getInstance().getOrCreateUser(member.getId());
WelcomeMessage welcomeMessage = RankService.getInstance().getRandomWelcomeMessage(user.getRank());
TextChannel channel = event.getGuild().getTextChannelById(Configuration.getInstance().getDotenv().get("WELCOME_CHANNEL", "0"));
String description = MessageUtils.insertPlaceholders(welcomeMessage.getMessage(), Map.of(
"username", member.getEffectiveName(),
"rank", user.getRank().getName()
));
Role role = event.getGuild().getRoleById(user.getRank().getDiscordId());
Color color = new Color(0, 0, 0);
if (role != null) {
event.getGuild().addRoleToMember(member, role).queue();
color = role.getColor();
}
// TODO: Récupérer la couleur du rank discord et l'appliquer à l'embed
EmbedBuilder embedBuilder = new EmbedBuilder()
.setTitle("Bienvenue sur le serveur " + event.getGuild().getName() + " !")
.setDescription(description)
.setThumbnail(member.getUser().getAvatarUrl())
.setTimestamp(event.getMember().getTimeJoined())
.setColor(color)
;
if (channel != null) {
channel.sendMessageEmbeds(embedBuilder.build()).queue();
}
}
}

View File

@ -0,0 +1,16 @@
package org.camelia.studio.gachamelia.listeners;
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());
}
}

View File

@ -0,0 +1,22 @@
package org.camelia.studio.gachamelia.listeners;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.camelia.studio.gachamelia.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) {
event.deferReply().setEphemeral(true).queue();
commandManager.handleCommand(event.getName(), event);
}
}

View File

@ -0,0 +1,68 @@
package org.camelia.studio.gachamelia.managers;
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.camelia.studio.gachamelia.Gachamelia;
import org.camelia.studio.gachamelia.interfaces.ISlashCommand;
import org.camelia.studio.gachamelia.utils.Configuration;
import org.camelia.studio.gachamelia.utils.ReflectionUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class CommandManager {
private final List<ISlashCommand> slashCommands;
private final Logger logger = LoggerFactory.getLogger(CommandManager.class);
public CommandManager() {
slashCommands = ReflectionUtils.loadClasses(
"org.camelia.studio.gachamelia.commands",
ISlashCommand.class
);
}
public void registerCommands() {
Guild guild = Gachamelia
.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.getHook().editOriginal("Commande inconnue").queue();
}
}

View File

@ -0,0 +1,33 @@
package org.camelia.studio.gachamelia.managers;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.camelia.studio.gachamelia.listeners.GuildMemberJoinListener;
import org.camelia.studio.gachamelia.listeners.SlashCommandListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public class ListenerManager {
private final List<ListenerAdapter> 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);
}
}

View File

@ -0,0 +1,94 @@
package org.camelia.studio.gachamelia.models;
import jakarta.persistence.*;
import org.camelia.studio.gachamelia.interfaces.IEntity;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import java.time.LocalDateTime;
import java.util.List;
@Entity
@Table(name = "ranks")
public class Rank implements IEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "discordId", nullable = false, length = 255, unique = true)
private String discordId;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private int percentage;
@OneToMany(mappedBy = "rank")
private List<User> users;
@OneToMany(mappedBy = "rank")
private List<WelcomeMessage> welcomeMessages;
@CreationTimestamp
@Column(name = "createdAt")
private LocalDateTime createdAt;
@UpdateTimestamp
@Column(name = "updatedAt")
private LocalDateTime updatedAt;
public Rank(String discordId, String name, int percentage) {
this.discordId = discordId;
this.name = name;
this.percentage = percentage;
}
public Rank() {
}
public Long getId() {
return id;
}
public String getDiscordId() {
return discordId;
}
public void setDiscordId(String discordId) {
this.discordId = discordId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPercentage() {
return percentage;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public List<User> getUsers() {
return users;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public List<WelcomeMessage> getWelcomeMessages() {
return welcomeMessages;
}
}

View File

@ -0,0 +1,68 @@
package org.camelia.studio.gachamelia.models;
import jakarta.persistence.*;
import org.camelia.studio.gachamelia.interfaces.IEntity;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import java.time.LocalDateTime;
@Entity
@Table(name = "users")
public class User implements IEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "discordId", nullable = false, unique = true)
private String discordId;
@ManyToOne(fetch = FetchType.EAGER)
private Rank rank;
@CreationTimestamp
@Column(name = "createdAt")
private LocalDateTime createdAt;
@UpdateTimestamp
@Column(name = "updatedAt")
private LocalDateTime updatedAt;
public User() {
}
public User(String discordId, Rank rank) {
this.discordId = discordId;
this.rank = rank;
}
public Long getId() {
return id;
}
public String getDiscordId() {
return discordId;
}
public void setDiscordId(String discordId) {
this.discordId = discordId;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public Rank getRank() {
return rank;
}
public void setRank(Rank rank) {
this.rank = rank;
}
}

View File

@ -0,0 +1,46 @@
package org.camelia.studio.gachamelia.models;
import jakarta.persistence.*;
import org.camelia.studio.gachamelia.interfaces.IEntity;
@Entity
@Table(name = "welcome_messages")
public class WelcomeMessage implements IEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
private Rank rank;
@Column(nullable = false)
private String message;
public WelcomeMessage() {
}
public WelcomeMessage(Rank rank, String message) {
this.rank = rank;
this.message = message;
}
public Long getId() {
return id;
}
public Rank getRank() {
return rank;
}
public void setRank(Rank rank) {
this.rank = rank;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@ -0,0 +1,91 @@
package org.camelia.studio.gachamelia.repossitories;
import org.camelia.studio.gachamelia.db.HibernateConfig;
import org.camelia.studio.gachamelia.models.Rank;
import org.camelia.studio.gachamelia.models.WelcomeMessage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class RankRepository {
private final SessionFactory sessionFactory;
private static RankRepository instance;
public static RankRepository getInstance() {
if (instance == null) {
instance = new RankRepository();
}
return instance;
}
public RankRepository() {
this.sessionFactory = HibernateConfig.getSessionFactory();
}
public List<Rank> findAll() {
try (Session session = sessionFactory.openSession()) {
return session.createQuery("FROM Rank", Rank.class).list();
}
}
public Rank findByName(String name) {
try (Session session = sessionFactory.openSession()) {
return session.createQuery("FROM User WHERE name = :name", Rank.class)
.setParameter("discordId", name)
.uniqueResult();
}
}
public Rank getRandomRank() {
try (Session session = sessionFactory.openSession()) {
return session.createQuery("FROM Rank ORDER BY RAND() LIMIT 1", Rank.class)
.uniqueResult();
}
}
public Rank save(Rank rank) {
try (Session session = sessionFactory.openSession()) {
session.beginTransaction();
session.persist(rank);
session.getTransaction().commit();
return rank;
}
}
public void update(Rank rank) {
try (Session session = sessionFactory.openSession()) {
session.beginTransaction();
session.merge(rank);
session.getTransaction().commit();
}
}
public WelcomeMessage getRandomWelcomeMessage(Rank rank) {
try (Session session = sessionFactory.openSession()) {
session.beginTransaction();
try {
// Recharger le rank avec ses messages
Rank refreshedRank = session.get(Rank.class, rank.getId());
List<WelcomeMessage> welcomeMessages = refreshedRank.getWelcomeMessages();
if (welcomeMessages.isEmpty()) {
return null;
}
WelcomeMessage message = welcomeMessages.get(
ThreadLocalRandom.current().nextInt(welcomeMessages.size())
);
session.getTransaction().commit();
return message;
} catch (Exception e) {
session.getTransaction().rollback();
throw e;
}
}
}
}

View File

@ -0,0 +1,57 @@
package org.camelia.studio.gachamelia.repossitories;
import org.camelia.studio.gachamelia.db.HibernateConfig;
import org.camelia.studio.gachamelia.models.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.util.List;
public class UserRepository {
private final SessionFactory sessionFactory;
private static UserRepository instance;
public static UserRepository getInstance() {
if (instance == null) {
instance = new UserRepository();
}
return instance;
}
public UserRepository() {
this.sessionFactory = HibernateConfig.getSessionFactory();
}
public List<User> findAll() {
try (Session session = sessionFactory.openSession()) {
return session.createQuery("FROM User", User.class).list();
}
}
public User findByDiscordId(String discordId) {
try (Session session = sessionFactory.openSession()) {
return session.createQuery("FROM User WHERE discordId = :discordId", User.class)
.setParameter("discordId", discordId)
.uniqueResult();
}
}
public User save(User user) {
try (Session session = sessionFactory.openSession()) {
session.beginTransaction();
session.persist(user);
session.getTransaction().commit();
return user;
}
}
public void update(User user) {
try (Session session = sessionFactory.openSession()) {
session.beginTransaction();
session.merge(user);
session.getTransaction().commit();
}
}
}

View File

@ -0,0 +1,56 @@
package org.camelia.studio.gachamelia.services;
import org.camelia.studio.gachamelia.models.Rank;
import org.camelia.studio.gachamelia.models.WelcomeMessage;
import org.camelia.studio.gachamelia.repossitories.RankRepository;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class RankService {
private static RankService instance;
public static RankService getInstance() {
if (instance == null) {
instance = new RankService();
}
return instance;
}
public Rank getOrCreateRank(String name, String discordId, int percentage) {
Rank rank = RankRepository.getInstance().findByName(name);
if (rank == null) {
rank = new Rank(discordId, name, percentage);
RankRepository.getInstance().save(rank);
}
return rank;
}
public List<Rank> getAllRanks() {
return RankRepository.getInstance().findAll();
}
public Rank getRandomRank() {
List<Rank> ranks = RankRepository.getInstance().findAll();
int percentage = ThreadLocalRandom.current().nextInt(100);
int cumulativePercentage = 0;
for (Rank rank : ranks) {
cumulativePercentage += rank.getPercentage();
if (percentage <= cumulativePercentage) {
return rank;
}
}
// Ne devrait jamais arriver
return null;
}
public WelcomeMessage getRandomWelcomeMessage(Rank rank) {
return RankRepository.getInstance().getRandomWelcomeMessage(rank);
}
}

View File

@ -0,0 +1,39 @@
package org.camelia.studio.gachamelia.services;
import org.camelia.studio.gachamelia.models.Rank;
import org.camelia.studio.gachamelia.models.User;
import org.camelia.studio.gachamelia.repossitories.UserRepository;
import java.util.List;
public class UserService {
private static UserService instance;
public static UserService getInstance() {
if (instance == null) {
instance = new UserService();
}
return instance;
}
public User getOrCreateUser(String discordId) {
User user = UserRepository.getInstance().findByDiscordId(discordId);
if (user == null) {
Rank rank = RankService.getInstance().getRandomRank();
user = new User(discordId, rank);
UserRepository.getInstance().save(user);
}
return user;
}
public List<User> getAllUsers() {
return UserRepository.getInstance().findAll();
}
public void updateUser(User user) {
UserRepository.getInstance().update(user);
}
}

View File

@ -0,0 +1,23 @@
package org.camelia.studio.gachamelia.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;
}
}

View File

@ -0,0 +1,14 @@
package org.camelia.studio.gachamelia.utils;
import java.util.Map;
public class MessageUtils {
public static String insertPlaceholders(String message, Map<String, String> placeholders) {
for (Map.Entry<String, String> entry : placeholders.entrySet()) {
message = message.replace("%" + entry.getKey() + "%", entry.getValue());
}
return message;
}
}

View File

@ -0,0 +1,105 @@
package org.camelia.studio.gachamelia.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class ReflectionUtils {
private static final Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);
/**
* Charge toutes les classes d'un type spécifique depuis un package
*
* @param packageName Le package à scanner
* @param targetType Le type de classe à charger
* @return Liste des instances des classes trouvées
*/
public static <T> List<T> loadClasses(String packageName, Class<T> targetType) {
List<T> instances = new ArrayList<>();
try {
// Convertit le nom du package en chemin
String path = packageName.replace('.', '/');
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Récupère toutes les ressources du package
var resources = classLoader.getResources(path);
// Parcourt toutes les ressources trouvées
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
File directory = new File(resource.toURI());
// Charge les classes du répertoire et ses sous-répertoires
scanDirectory(directory, packageName, targetType, instances);
}
} catch (Exception e) {
logger.error("Erreur lors du scan du package {} : {}", packageName, e.getMessage());
}
return instances;
}
/**
* Scanne récursivement un répertoire pour trouver les classes
*/
private static <T> void scanDirectory(File directory, String packageName, Class<T> targetType, List<T> instances) {
// Vérifie si le répertoire existe
if (!directory.exists()) {
return;
}
// Récupère tous les fichiers du répertoire
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
// Si c'est un répertoire, on le scanne récursivement
if (file.isDirectory()) {
scanDirectory(
file,
packageName + "." + file.getName(),
targetType,
instances
);
}
// Si c'est un fichier .class, on essaie de le charger
else if (file.getName().endsWith(".class")) {
loadClass(packageName, file.getName(), targetType, instances);
}
}
}
}
/**
* Charge une classe spécifique
*/
@SuppressWarnings("unchecked")
private static <T> void loadClass(String packageName, String fileName, Class<T> targetType, List<T> instances) {
try {
// Convertit le nom de fichier en nom de classe
String className = packageName + '.' + fileName.substring(0, fileName.length() - 6);
Class<?> clazz = Class.forName(className);
// Vérifie si la classe correspond au type recherché
if (targetType.isAssignableFrom(clazz) &&
!clazz.isInterface() &&
!Modifier.isAbstract(clazz.getModifiers())) {
// Crée une instance de la classe
T instance = (T) clazz.getDeclaredConstructor().newInstance();
instances.add(instance);
logger.debug("Classe chargée : {}", className);
}
} catch (Exception e) {
logger.error("Erreur lors du chargement d'une classe : {}", e.getMessage());
}
}
}

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %boldCyan(%-34.-34thread) %red(%10.10X{jda.shard}) %boldGreen(%-15.-15logger{0}) %highlight(%-6level) %msg%n</pattern>
</encoder>
</appender>
<root level="${APP_LEVEL:-info}">
<appender-ref ref="STDOUT" />
</root>
<!-- If debug is enabled, set the level to debug -->
</configuration>