Compare commits

...

No commits in common. "master" and "old-js" have entirely different histories.

79 changed files with 5065 additions and 2381 deletions

View File

@ -1,9 +1,3 @@
.idea/
.vscode/
.fleet/
*.iml
.git
build/
.gradle/
node_modules/
dist/
.env

View File

@ -1,8 +1,13 @@
BOT_TOKEN=
GUILD_ID=
TOKEN="BOT_TOKEN"
GUILD_ID="1234567890"
DB_URL=jdbc:postgresql://localhost:5433/gachamelia
DB_USER=postgres
DB_PASSWORD=gachamelia
DB_DIALECT="postgres"
DB_HOST="localhost"
DB_NAME="gachamelia"
DB_USERNAME="postgres"
DB_PASSWORD="gachamelia"
DB_PORT=5433
WELCOME_CHANNEL=
WELCOME_CHANNEL=""
INIT_DB="true"

12
.gitattributes vendored
View File

@ -1,12 +0,0 @@
#
# 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

@ -21,3 +21,5 @@ jobs:
registry: git.crystalyx.net
tag: ${{ gitea.ref_name }}
tag_with_latest: true
cache: true
cache_registry: git.crystalyx.net/camelia-studio/gachamelia/cache

5
.gitignore vendored
View File

@ -1,9 +1,10 @@
.gradle
build
.idea/
.vscode/
.fleet/
node_modules/
dist/
*.iml
tsconfig.tsbuildinfo
.env
.env.*

View File

@ -1,11 +1,15 @@
FROM eclipse-temurin:21-alpine AS build
WORKDIR /src
COPY . .
FROM node:20-alpine
RUN ./gradlew clean shadowJar
FROM eclipse-temurin:21-alpine AS runner
RUN mkdir -p /app
# Create app directory
WORKDIR /app
COPY --from=build /src/build/libs/gachamelia.jar /app/gachamelia.jar
CMD ["java", "-jar", "gachamelia.jar"]
# Install app dependencies
COPY package.json /app
COPY package-lock.json /app
RUN npm install
# Bundle app source
COPY . /app
CMD [ "npm", "run", "start:clean" ]

View File

@ -1,42 +0,0 @@
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")
implementation("jakarta.annotation:jakarta.annotation-api:3.0.0")
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}

Binary file not shown.

View File

@ -1,7 +0,0 @@
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
View File

@ -1,252 +0,0 @@
#!/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
View File

@ -1,94 +0,0 @@
@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

528
old/index.js Normal file
View File

@ -0,0 +1,528 @@
const Discord = require('discord.js');
const sqlite3 = require('sqlite3').verbose();
const client = new Discord.Client();
const db = new sqlite3.Database('./userdata.db');
// Messages de bienvenue avec leurs probabilités, les rôles associés et les images
const welcomeMessages = [
{ message: "{mention} vient d'être invoqué sur **Camélia Studio** ! Souhaitons-lui la bienvenue ! Il s'agit d'un personnage de rareté **B**. Dommage, nous aurons plus de chance la prochaine fois...", role: "Rang B", probability: 80, image: "https://concepts.esenjin.xyz/cyla/v2/file/11C108.png" },
{ message: "{mention} vient d'être invoqué sur **Camélia Studio** ! Souhaitons-lui la bienvenue ! Il s'agit d'un personnage de rareté **A**. C'est plutôt une bonne pioche !", role: "Rang A", probability: 15, image: "https://concepts.esenjin.xyz/cyla/v2/file/732316.png" },
{ message: "{mention} vient d'être invoqué sur **Camélia Studio** ! Souhaitons-lui la bienvenue ! Il s'agit d'un personnage de rareté **S**. On a vraiment de la chance aujourd'hui !!", role: "Rang S", probability: 4, image: "https://concepts.esenjin.xyz/cyla/v2/file/D6E3E1.png" },
{ message: "{mention} vient d'être invoqué sur **Camélia Studio** ! Souhaitons-lui la bienvenue ! Il s'agit d'un personnage de rareté **S+**. Incroyable ! On vient de tomber sur la perle rare !", role: "Rang S+", probability: 1, image: "https://concepts.esenjin.xyz/cyla/v2/file/6B6CE3.png" }
];
let welcomeChannel; // Canal où publier les messages de bienvenue
let farewellChannel; // Canal où publier les messages d'adieu
// Création de la table dans la base de données
db.serialize(() => {
db.run(`CREATE TABLE IF NOT EXISTS userdata (
userid TEXT PRIMARY KEY,
message TEXT,
role TEXT,
image TEXT
)`);
});
// Fonction pour choisir un message de bienvenue selon les probabilités
function chooseWelcomeMessage() {
const random = Math.random() * 100; // Random entre 0 et 100
let cumulativeProbability = 0;
for (const { message, role, image } of welcomeMessages) {
cumulativeProbability += probability;
if (random < cumulativeProbability) {
return { message, role, image };
}
}
}
// Commande "/gachaoptions"
client.on('message', message => {
if (message.member.hasPermission('ADMINISTRATOR') && message.content.startsWith('/gachaoptions')) {
const args = message.content.split(' ');
if (args.length === 1) {
// Afficher les options actuelles
message.channel.send(`Options actuelles :
- Canal de bienvenue : ${welcomeChannel ? welcomeChannel : "non défini"}
- Canal d'adieu : ${farewellChannel ? farewellChannel : "non défini"}
`);
} else if (args.length === 3 && args[1] === 'bienvenue') {
// Définir le canal de bienvenue
const channelID = args[2].replace(/<#|>/g, '');
welcomeChannel = message.guild.channels.cache.get(channelID);
message.channel.send(`Canal de bienvenue défini sur : ${welcomeChannel}`);
} else if (args.length === 3 && args[1] === 'adieu') {
// Définir le canal d'adieu
const channelID = args[2].replace(/<#|>/g, '');
farewellChannel = message.guild.channels.cache.get(channelID);
message.channel.send(`Canal d'adieu défini sur : ${farewellChannel}`);
} else if (args.length === 3 && args[1] === 'messageadieu') {
// Définir le message d'adieu
farewellMessage = args.slice(2).join(' ');
message.channel.send(`Message d'adieu défini sur : ${farewellMessage}`);
} else if (args.length === 3 && args[1] === 'imageadieu') {
// Définir l'image d'adieu
farewellImage = args[2];
message.channel.send(`Image d'adieu définie sur : ${farewellImage}`);
} else if (args.length === 3 && args[1] === 'bienvenueimage') {
// Définir l'image de bienvenue
welcomeImage = args[2];
message.channel.send(`Image de bienvenue définie sur : ${welcomeImage}`);
} else if (args.length === 3 && args[1] === 'rangauto') {
// Définir la commande pour le rang automatique
autorangCommand = args[2];
message.channel.send(`Commande pour le rang automatique définie sur : ${autorangCommand}`);
} else if (args.length === 3 && args[1] === 'rangs') {
// Afficher les rôles et leurs messages associés
message.channel.send(`Messages de bienvenue et rôles associés :
- Rang B : ${welcomeMessages.find(msg => msg.role === "Rang B").message}
- Rang A : ${welcomeMessages.find(msg => msg.role === "Rang A").message}
- Rang S : ${welcomeMessages.find(msg => msg.role === "Rang S").message}
- Rang S+ : ${welcomeMessages.find(msg => msg.role === "Rang S+").message}
`);
} else if (args.length === 5 && args[1] === 'ajoutermessage') {
// Ajouter un nouveau message de bienvenue
const newRole = args[2];
const newProbability = parseInt(args[3]);
const newMessage = args.slice(4).join(' ');
welcomeMessages.push({ message: newMessage, role: newRole, probability: newProbability });
message.channel.send(`Nouveau message de bienvenue ajouté pour le rôle ${newRole} avec une probabilité de ${newProbability}%.`);
} else if (args.length === 4 && args[1] === 'modifierprobabilite') {
// Modifier la probabilité d'un message de bienvenue existant
const roleName = args[2];
const newProbability = parseInt(args[3]);
const index = welcomeMessages.findIndex(msg => msg.role === roleName);
if (index !== -1) {
// Calculer la somme des probabilités actuelles
let currentTotal = welcomeMessages.reduce((total, msg) => total + msg.probability, 0);
// Calculer la différence entre la nouvelle probabilité et l'ancienne
let difference = newProbability - welcomeMessages[index].probability;
// Mettre à jour la probabilité
welcomeMessages[index].probability = newProbability;
// Vérifier si le total est égal à 100%
if (currentTotal + difference !== 100) {
message.channel.send(`La somme des probabilités n'est pas égale à 100%. Veuillez modifier une autre probabilité pour ajuster.`);
} else {
message.channel.send(`Probabilité du message de bienvenue pour le rôle ${roleName} modifiée à ${newProbability}%.`);
}
} else {
message.channel.send(`Le rôle ${roleName} n'existe pas.`);
}
} else if (args.length === 4 && args[1] === 'changerrole') {
// Changer le rôle associé à un message de bienvenue existant
const roleName = args[2];
const newRoleName = args[3];
const index = welcomeMessages.findIndex(msg => msg.role === roleName);
if (index !== -1) {
welcomeMessages[index].role = newRoleName;
message.channel.send(`Rôle associé au message de bienvenue pour le rôle ${roleName} changé en ${newRoleName}.`);
} else {
message.channel.send(`Le rôle ${roleName} n'existe pas.`);
}
} else {
message.channel.send("Options disponibles : \n- `/gachaoptions bienvenue <nom_du_canal>` pour définir le canal de bienvenue\n- `/gachaoptions adieu <nom_du_canal>` pour définir le canal d'adieu\n- `/gachaoptions messageadieu <message>` pour définir le message d'adieu\n- `/gachaoptions imageadieu <lien_de_l'image>` pour définir l'image d'adieu\n- `/gachaoptions bienvenueimage <lien_de_l'image>` pour définir l'image de bienvenue\n- `/gachaoptions rangauto <commande>` pour définir la commande pour le rang automatique\n- `/gachaoptions rangs` pour afficher les rôles et leurs messages associés\n- `/gachaoptions ajoutermessage <role> <probabilité> <message>` pour ajouter un nouveau message de bienvenue\n- `/gachaoptions modifierprobabilite <role> <probabilité>` pour modifier la probabilité d'un message de bienvenue\n- `/gachaoptions changerrole <role> <nouveau_role>` pour changer le rôle associé à un message de bienvenue");
}
}
});
client.on('guildMemberAdd', member => {
// Vérifier si l'utilisateur est déjà dans la base de données
db.get(`SELECT * FROM userdata WHERE userid = ?`, member.id, (err, row) => {
if (err) {
console.error(err);
return;
}
if (row) {
// Utiliser les données stockées
const { message, role, image } = row;
// Envoi du message de bienvenue dans le canal approprié
const welcomeMessage = message.replace("{mention}", member.user);
const embed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setDescription(welcomeMessage)
.setImage(image);
if (welcomeChannel) {
welcomeChannel.send(embed);
}
// Attribution automatique du rôle
const guildRole = member.guild.roles.cache.find(guildRole => guildRole.name === role);
if (guildRole) {
member.roles.add(guildRole);
}
} else {
// Choix du message de bienvenue, du rôle associé et de l'image
const { message, role, image } = chooseWelcomeMessage();
// Envoi du message de bienvenue dans le canal approprié
const welcomeMessage = message.replace("{mention}", member.user);
const embed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setDescription(welcomeMessage)
.setImage(image);
if (welcomeChannel) {
welcomeChannel.send(embed);
}
// Attribution automatique du rôle
const guildRole = member.guild.roles.cache.find(guildRole => guildRole.name === role);
if (guildRole) {
member.roles.add(guildRole);
}
// Stocker les données de bienvenue dans la base de données
db.run(`INSERT INTO userdata (userid, message, role, image) VALUES (?, ?, ?, ?)`, [member.id, message, role, image], err => {
if (err) {
console.error(err);
}
});
}
});
});
client.on('guildMemberRemove', member => {
// Message d'adieu
const farewellMessage = `Oh non ! ${member.user} n'est plus utile dans la méta actuelle et quitte notre équipe. Espérons qu'une prochaine mise à jour lui soit favorable !`;
const embed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setDescription(farewellMessage)
.setImage("https://concepts.esenjin.xyz/cyla/v2/file/EDF7B4.gif");
if (farewellChannel) {
farewellChannel.send(embed);
}
// Supprimer les données de bienvenue de la base de données
db.run(`DELETE FROM userdata WHERE userid = ?`, member.id, err => {
if (err) {
console.error(err);
}
});
});
// Connexion du bot à Discord
client.login('TOKEN_DU_BOT');
const sqlite3 = require('sqlite3').verbose();
// Connexion à la base de données SQLite
const db = new sqlite3.Database('./userXP.db', (err) => {
if (err) {
console.error('Erreur lors de la connexion à la base de données :', err.message);
} else {
console.log('Connexion à la base de données réussie.');
// Créer une table pour stocker l'XP des utilisateurs si elle n'existe pas déjà
db.run(`CREATE TABLE IF NOT EXISTS userXP (
userId TEXT PRIMARY KEY,
xp INTEGER DEFAULT 0,
dailyXP INTEGER DEFAULT 0
)`);
}
});
// Fonction pour récupérer l'XP d'un utilisateur depuis la base de données
function getUserXP(user) {
return new Promise((resolve, reject) => {
db.get('SELECT xp FROM userXP WHERE userId = ?', [user.id], (err, row) => {
if (err) {
reject(err);
} else {
resolve(row ? row.xp : 0);
}
});
});
}
// Fonction pour mettre à jour l'XP d'un utilisateur dans la base de données
function setUserXP(user, xp) {
db.run('INSERT OR REPLACE INTO userXP (userId, xp) VALUES (?, ?)', [user.id, xp], (err) => {
if (err) {
console.error('Erreur lors de la mise à jour de l\'XP de l\'utilisateur :', err.message);
}
});
}
// Fonction pour récupérer l'XP quotidien d'un utilisateur depuis la base de données
function getUserDailyXP(user) {
return new Promise((resolve, reject) => {
db.get('SELECT dailyXP FROM userXP WHERE userId = ?', [user.id], (err, row) => {
if (err) {
reject(err);
} else {
resolve(row ? row.dailyXP : 0);
}
});
});
}
// Fonction pour mettre à jour l'XP quotidien d'un utilisateur dans la base de données
function updateUserDailyXP(user, amount) {
db.run('INSERT OR REPLACE INTO userXP (userId, dailyXP) VALUES (?, ?)', [user.id, amount], (err) => {
if (err) {
console.error('Erreur lors de la mise à jour de l\'XP quotidienne de l\'utilisateur :', err.message);
}
});
}
// Supprimer l'utilisateur de la base de données lorsque celui-ci quitte le serveur
client.on('guildMemberRemove', member => {
db.run('DELETE FROM userXP WHERE userId = ?', [member.id], (err) => {
if (err) {
console.error('Erreur lors de la suppression de l\'utilisateur de la base de données :', err.message);
}
});
});
// Variables globales pour stocker les paramètres XP et les canaux exclus
let excludedChannels = [];
let xpMultiplierChannels = [];
let xpCooldowns = {};
client.on('message', message => {
// Vérifier si le message est dans un salon exclu ou provenant du bot lui-même
if (excludedChannels.includes(message.channel.id) || message.author.bot) return;
// Vérifier si l'utilisateur est un booster
let xpMultiplier = 1;
if (message.member.roles.cache.some(role => role.name === 'Booster')) {
xpMultiplier = 2;
}
// Vérifier si le salon a un multiplicateur d'XP
if (xpMultiplierChannels.includes(message.channel.id)) {
xpMultiplier *= 2;
}
// Vérifier si l'utilisateur est déjà en cooldown
if (xpCooldowns[message.author.id]) return;
// Ajouter l'XP à l'utilisateur
addXP(message.author, 1 * xpMultiplier);
// Mettre l'utilisateur en cooldown pour 2 minutes
xpCooldowns[message.author.id] = true;
setTimeout(() => {
delete xpCooldowns[message.author.id];
}, 120000);
});
// Fonction pour ajouter de l'XP à un utilisateur
function addXP(user, amount) {
// Récupérer l'XP actuelle de l'utilisateur depuis la base de données
getUserXP(user)
.then(currentXP => {
// Ajouter la quantité spécifiée à l'XP actuelle
const newXP = currentXP + amount;
// Mettre à jour l'XP de l'utilisateur dans la base de données
setUserXP(user, newXP);
// Vérifier si l'utilisateur a atteint un nouveau rang
checkAndUpdateUserRank(user, newXP);
})
.catch(err => {
console.error('Erreur lors de l\'ajout de l\'XP à l\'utilisateur :', err);
});
// Vérifier si l'utilisateur a atteint un nouveau rang
const currentXP = getUserXP(user);
const newRank = calculateRank(currentXP + amount);
if (newRank !== getUserRank(user)) {
const newRole = getRoleFromRank(newRank);
const notificationMessage = `Héhé ! C'est que tu as bien xp dit donc, tu peux désormais évoluer au ${newRole} ! Pour cela, rien de plus simple, utilise la commande /gachajaiunegrosseépée.`;
user.send(notificationMessage);
}
}
// Fonction pour calculer le nouveau rang à partir de l'XP
function calculateRank(xp) {
if (xp >= 66666) return "Rang S++";
if (xp >= 10000) return "Rang S+";
if (xp >= 1000) return "Rang S";
if (xp >= 100) return "Rang A";
return "Rang B";
}
// Fonction pour obtenir le rang d'un utilisateur
function getUserRank(user) {
const xp = getUserXP(user);
return calculateRank(xp);
}
// Fonction pour obtenir l'XP d'un utilisateur
function getUserXP(user) {
return new Promise((resolve, reject) => {
db.get('SELECT xp FROM userXP WHERE userId = ?', [user.id], (err, row) => {
if (err) {
reject(err);
} else {
resolve(row ? row.xp : 0);
}
});
});
}
// Fonction pour obtenir le rôle associé à un rang
function getRoleFromRank(rank) {
// Tableau associant les rangs aux noms de rôles
const rankRoles = {
'Rang B': 'Role B',
'Rang A': 'Role A',
'Rang S': 'Role S',
'Rang S+': 'Role S+'
// Ajouter d'autres rangs et rôles au besoin
};
// Renvoyer le nom du rôle associé au rang spécifié
return rankRoles[rank];
}
// Commande pour obtenir le nouveau rang
client.on('message', message => {
if (message.content === '/gachajaiunegrosseépée') {
const user = message.author;
const currentXP = getUserXP(user);
const newRank = calculateRank(currentXP);
const roles = ['Rang B', 'Rang A', 'Rang S', 'Rang S+', 'Rang S++'];
const index = roles.indexOf(newRank);
if (index !== -1) {
const newRole = roles[index + 1];
const guildRole = message.guild.roles.cache.find(role => role.name === newRole);
if (guildRole) {
const currentRole = message.guild.roles.cache.find(role => role.name === getUserRank(user));
if (currentRole) {
message.member.roles.remove(currentRole);
}
message.member.roles.add(guildRole);
message.reply(`Félicitations ! Vous avez maintenant atteint le ${newRole}.`);
}
}
}
});
// Commande pour exclure des salons du décompte de l'XP
client.on('message', message => {
if (message.member.hasPermission('ADMINISTRATOR') && message.content.startsWith('/excludesalon')) {
const channelID = message.content.split(' ')[1];
excludedChannels.push(channelID);
message.channel.send(`Le salon avec l'ID ${channelID} a été exclu du décompte de l'XP.`);
}
});
// Commande pour multiplier l'XP dans certains salons
client.on('message', message => {
if (message.member.hasPermission('ADMINISTRATOR') && message.content.startsWith('/multiplierxp')) {
const channelID = message.content.split(' ')[1];
xpMultiplierChannels.push(channelID);
message.channel.send(`Le salon avec l'ID ${channelID} a maintenant un multiplicateur d'XP.`);
}
});
// Variable globale pour stocker le rôle déclenchant le Rang ULTRA
let ultraRole = null;
// Fonction pour vérifier si l'utilisateur a le rôle déclenchant le Rang ULTRA
function hasUltraRole(user) {
return user.roles.cache.some(role => role === ultraRole);
}
// Fonction pour obtenir le rôle "Rang ULTRA" et l'assigner à la variable globale
function setUltraRole(roleName) {
ultraRole = message.guild.roles.cache.find(role => role.name === roleName);
}
// Commande pour définir le rôle déclenchant le Rang ULTRA
client.on('message', message => {
if (message.member.hasPermission('ADMINISTRATOR') && message.content.startsWith('/gachaoptions ultrarole')) {
const roleName = message.content.split(' ')[1];
setUltraRole(roleName);
message.channel.send(`Le rôle déclenchant le Rang ULTRA a été défini sur "${roleName}".`);
}
});
// Variable globale pour stocker les temps de connexion des membres des salons vocaux
const voiceChannelConnections = {};
// Variable globale pour stocker les temps de connexion des membres des salons vocaux en cooldown
const xpCooldowns = {};
// Variable globale pour stocker les XP quotidiennes des utilisateurs
const userDailyXP = {};
// Fonction pour surveiller la connexion des membres aux salons vocaux
client.on('voiceStateUpdate', (oldState, newState) => {
const user = newState.member;
// Vérifier si l'utilisateur existe et n'est pas un bot
if (!user || user.user.bot) return;
const oldChannel = oldState.channel;
const newChannel = newState.channel;
// L'utilisateur est entré dans un salon vocal
if (!oldChannel && newChannel) {
voiceChannelConnections[user.id] = Date.now(); // Enregistrer le moment de la connexion
}
// L'utilisateur est sorti d'un salon vocal
else if (oldChannel && !newChannel) {
// Vérifier si l'utilisateur est enregistré comme étant connecté à un salon vocal
if (voiceChannelConnections[user.id]) {
const timeSpentInVoiceChannel = Math.floor((Date.now() - voiceChannelConnections[user.id]) / 1000); // Calculer la durée en secondes
const xpGained = calculateXPFromTime(timeSpentInVoiceChannel, user); // Convertir la durée en XP
addXP(user, xpGained); // Ajouter l'XP à l'utilisateur
delete voiceChannelConnections[user.id]; // Supprimer l'enregistrement de la connexion
}
}
});
// Fonction pour calculer l'XP à partir du temps passé dans un salon vocal
function calculateXPFromTime(timeSpentInVoiceChannel, user) {
// Déterminer le multiplicateur d'XP en fonction du boost Nitro
let xpMultiplier = 1;
if (user.roles.cache.some(role => role.name === 'Booster')) {
xpMultiplier = 2;
}
// Vérifier si l'utilisateur est en cooldown pour le salon vocal
if (!xpCooldowns[user.id]) {
// Appliquer le multiplicateur d'XP
const xpPerMinute = 1 * xpMultiplier;
const xpGained = Math.floor(timeSpentInVoiceChannel / 120) * xpPerMinute; // 1 XP pour 2 minutes
// Appliquer le plafond d'XP quotidien
if (xpGained > 0) {
if (xpMultiplier === 1 && getUserDailyXP(user) + xpGained > 200) {
xpGained = 200 - getUserDailyXP(user);
} else if (xpMultiplier === 2 && getUserDailyXP(user) + xpGained > 500) {
xpGained = 500 - getUserDailyXP(user);
}
updateUserDailyXP(user, xpGained);
}
return xpGained;
} else {
return 0; // Aucune XP gagnée pendant le cooldown
}
}
// Fonction pour ajouter de l'XP à un utilisateur
function addXP(user, amount) {
// Récupérer l'XP actuelle de l'utilisateur
let currentXP = getUserXP(user);
// Ajouter la quantité spécifiée à l'XP actuelle
currentXP += amount;
// Mettre à jour l'XP de l'utilisateur
setUserXP(user, currentXP);
}
// Fonction pour récupérer l'XP quotidien d'un utilisateur
function getUserDailyXP(user) {
// Récupérer l'XP quotidien de l'utilisateur depuis le stockage approprié
return userDailyXP[user.id] || 0; // Si l'XP quotidien n'est pas défini, retourner 0
}
// Fonction pour mettre à jour l'XP quotidien d'un utilisateur
function updateUserDailyXP(user, amount) {
// Mettre à jour l'XP quotidien de l'utilisateur dans le stockage approprié
userDailyXP[user.id] = amount;
}
// Fonction pour exclure des salons vocaux du décompte de l'XP
client.on('message', message => {
if (message.member.hasPermission('ADMINISTRATOR') && message.content.startsWith('/gachaoptions excludevoice')) {
const channelID = message.content.split(' ')[1];
// Ajouter le salon vocal à la liste des exclusions
excludedVoiceChannels.push(channelID);
message.channel.send(`Le salon vocal avec l'ID ${channelID} a été exclu du décompte de l'XP.`);
}
});

3585
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

30
package.json Normal file
View File

@ -0,0 +1,30 @@
{
"name": "gachamelia",
"version": "1.0.0",
"description": "Transforme ton serveur Discord en *gacha* géant !",
"main": "old/index.js",
"scripts": {
"clean": "rm -rf dist",
"build": "tsc --build",
"start": "npm run build && node dist/index.js",
"start:clean": "npm run clean && npm run build && node dist/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@types/node": "^22.8.5",
"discord.js": "^14.16.2",
"dotenv": "^16.4.5",
"glob": "^11.0.0",
"mariadb": "^3.4.0",
"mysql2": "^3.11.3",
"pg": "^8.13.1",
"pg-hstore": "^2.3.4",
"sequelize": "^6.37.5",
"sequelize-typescript": "^2.1.6",
"sqlite3": "^5.1.7",
"tedious": "^18.6.1",
"typescript": "^5.6.2"
}
}

View File

@ -0,0 +1,32 @@
import { ChatInputCommandInteraction, AutocompleteInteraction } from "discord.js";
import { Category } from "../enums/Category";
import {ICommand} from "../interfaces/ICommand";
import {CustomClient} from "./CustomClient";
import {ICommandOptions} from "../interfaces/ICommandOptions";
export class Command implements ICommand {
client: CustomClient;
name: string;
description: string;
category: Category;
options: object;
default_member_permissions: bigint;
dm_permission: boolean;
cooldown: number;
constructor(client: CustomClient, options: ICommandOptions) {
this.client = client;
this.name = options.name;
this.description = options.description;
this.category = options.category;
this.options = options.options;
this.default_member_permissions = options.default_member_permissions;
this.dm_permission = options.dm_permission;
this.cooldown = options.cooldown;
}
execute(interaction: ChatInputCommandInteraction): void {
}
autocomplete(interaction: AutocompleteInteraction): void {
}
}

View File

@ -0,0 +1,77 @@
import {IConfig} from "../interfaces/IConfig";
import {ICustomClient} from "../interfaces/ICustomClient";
import {Client, Collection, GatewayIntentBits} from "discord.js";
import {Handler} from "./Handler";
import {Command} from "./Command";
import {SubCommand} from "./SubCommand";
import {Config} from "./LoadConfig";
import {Database} from "./Database";
import {IDatabaseConfig} from "../interfaces/IDatabaseConfig";
import {Dialect} from "sequelize";
import {User} from "../models/User";
import {Rank} from "../models/Rank";
export class CustomClient extends Client implements ICustomClient {
config: IConfig;
handler: Handler;
commands: Collection<string, Command>;
subCommands: Collection<string, SubCommand>;
cooldowns: Collection<string, Collection<string, number>>;
database: Database;
constructor() {
super({
intents: Object.keys(GatewayIntentBits).map((a: string) => {
return GatewayIntentBits[a as keyof typeof GatewayIntentBits];
}),
})
// On ajoute le support de dotenv pour la config plutôt qu'un fichier JSON
require('dotenv').config();
// On charge dynamiquement la config
this.config = Config.load();
const dbConfig: IDatabaseConfig = {
dialect: this.config.dbDialect as Dialect,
host: this.config.dbHost,
port: this.config.dbPort,
username: this.config.dbUsername,
password: this.config.dbPassword,
database: this.config.dbName
};
this.database = new Database(dbConfig);
this.handler = new Handler(this);
this.commands = new Collection();
this.subCommands = new Collection();
this.cooldowns = new Collection();
}
async init(): Promise<void> {
await this.database.connect();
Rank.initModel(this.database.getSequelize());
User.initModel(this.database.getSequelize());
Rank.hasMany(User, {
foreignKey: 'rankId',
as: 'users'
});
User.belongsTo(Rank, {
foreignKey: 'rankId',
as: 'rank'
});
await this.database.sync({
alter: true
});
await this.LoadHandlers();
this.login(this.config.token).catch(console.error);
}
async LoadHandlers(): Promise<void> {
await this.handler.loadEvents();
await this.handler.loadCommands();
}
}

View File

@ -0,0 +1,55 @@
import {Sequelize} from "sequelize-typescript";
import {Options} from "sequelize";
import {IDatabaseConfig} from "../interfaces/IDatabaseConfig";
export class Database {
private readonly sequelize: Sequelize;
constructor(config: IDatabaseConfig) {
const options: Options = {
dialect: config.dialect,
host: config.host,
port: config.port,
username: config.username,
password: config.password,
database: config.database,
logging: false,
pool: {
max: config.poolOptions?.max ?? 5,
min: config.poolOptions?.min ?? 0,
acquire: config.poolOptions?.acquire ?? 30000,
idle: config.poolOptions?.idle ?? 10000
}
};
this.sequelize = new Sequelize(options);
}
public getSequelize(): Sequelize {
return this.sequelize;
}
public async connect(): Promise<void> {
try {
await this.sequelize.authenticate();
console.log('Connexion à la base de données établie avec succès.');
} catch (error) {
console.error('Impossible de se connecter à la base de données:', error);
throw error;
}
}
public async close(): Promise<void> {
try {
await this.sequelize.close();
console.log('Connexion à la base de données fermée avec succès.');
} catch (error) {
console.error('Erreur lors de la fermeture de la connexion:', error);
throw error;
}
}
public async sync(options?: { force?: boolean; alter?: boolean }): Promise<void> {
await this.sequelize.sync(options);
}
}

21
src/base/classes/Event.ts Normal file
View File

@ -0,0 +1,21 @@
import {ClientEvents} from "discord.js";
import {IEvent} from "../interfaces/IEvent";
import {CustomClient} from "./CustomClient";
import {IEventOptions} from "../interfaces/IEventOptions";
export class Event implements IEvent {
client: CustomClient;
name: keyof ClientEvents;
description: string;
once: boolean;
constructor(client: CustomClient, options: IEventOptions) {
this.client = client;
this.name = options.name;
this.description = options.description;
this.once = options.once;
}
execute(...args: any[]): void {};
}

View File

@ -0,0 +1,84 @@
import {IHandler} from "../interfaces/IHandler";
import path from "node:path";
import {glob} from "glob";
import {CustomClient} from "./CustomClient";
import {Event} from "./Event";
import {Command} from "./Command";
import {SubCommand} from "./SubCommand";
export class Handler implements IHandler {
client: CustomClient;
constructor(client: CustomClient) {
this.client = client;
}
async loadEvents(): Promise<void> {
const files = (await glob(`dist/events/**/*.js`)).map(filePath => path.resolve(filePath));
files.map(async (file: string) => {
let evt = await import(file);
let EventClass: any;
for (const key in evt) {
if (typeof evt[key] === 'function') {
EventClass = evt[key];
break;
}
}
if (!EventClass) {
return delete require.cache[require.resolve(file)] && console.log(`Event ${file.split('/').pop()} n'a pas de classe`);
}
const event : Event = new EventClass(this.client);
if (!event.name)
return delete require.cache[require.resolve(file)] && console.log(`Event ${file.split('/').pop()} n'a pas de nom`);
const execute = (...args: any[]) => event.execute(...args);
if (event.once) {
this.client.once(event.name, execute);
} else {
this.client.on(event.name, execute);
}
console.log(`Event ${file.split('/').pop()} chargé`);
return delete require.cache[require.resolve(file)];
});
}
async loadCommands(): Promise<void> {
const files = (await glob(`dist/commands/**/*.js`)).map(filePath => path.resolve(filePath));
files.map(async (file: string) => {
let evt = await import(file);
let EventClass: any;
for (const key in evt) {
if (typeof evt[key] === 'function') {
EventClass = evt[key];
break;
}
}
if (!EventClass) {
return delete require.cache[require.resolve(file)] && console.log(`Event ${file.split('/').pop()} n'a pas de classe`);
}
const command : Command|SubCommand = new EventClass(this.client);
if (!command.name)
return delete require.cache[require.resolve(file)] && console.log(`Event ${file.split('/').pop()} n'a pas de nom`);
if (file.split('/').pop()?.split(".")[2]) {
console.log(`Sous Commande ${file.split('/').pop()} chargé`);
this.client.subCommands.set(command.name, command as SubCommand);
} else {
console.log(`Commande ${file.split('/').pop()} chargé`);
this.client.commands.set(command.name, command as Command);
}
return delete require.cache[require.resolve(file)];
});
}
}

View File

@ -0,0 +1,12 @@
import dotenv from 'dotenv';
import type { IConfig } from '../interfaces/IConfig';
export class Config {
public static load(): IConfig {
dotenv.config();
return new Proxy<IConfig>({} as IConfig, {
get: (_, prop: string): string | undefined =>
process.env[prop.split(/(?=[A-Z])/).join('_').toUpperCase()]
});
}
}

View File

@ -0,0 +1,18 @@
import { ChatInputCommandInteraction } from "discord.js";
import {ISubCommand} from "../interfaces/ISubCommand";
import {CustomClient} from "./CustomClient";
import {ISubCommandOptions} from "../interfaces/ISubCommandOptions";
export class SubCommand implements ISubCommand {
client: CustomClient;
name: string;
constructor(client: CustomClient,options: ISubCommandOptions) {
this.client = client;
this.name = options.name;
}
execute(interaction: ChatInputCommandInteraction): void {
}
}

View File

@ -0,0 +1,4 @@
export enum Category {
UTILITIES = 'Utilitaires',
}

View File

@ -0,0 +1,17 @@
import {CustomClient} from "../classes/CustomClient";
import {AutocompleteInteraction, ChatInputCommandInteraction} from "discord.js";
import {Category} from "../enums/Category";
export interface ICommand {
client: CustomClient;
name: string;
description: string;
category: Category;
options: object;
default_member_permissions: bigint;
dm_permission: boolean;
cooldown: number;
execute(interaction: ChatInputCommandInteraction): void;
autocomplete(interaction: AutocompleteInteraction): void;
}

View File

@ -0,0 +1,11 @@
import {Category} from "../enums/Category";
export interface ICommandOptions {
name: string;
description: string;
category: Category;
options: object;
default_member_permissions: bigint;
dm_permission: boolean;
cooldown: number;
}

View File

@ -0,0 +1,14 @@
export interface IConfig {
token: string;
guildId: string;
dbDialect: string;
dbHost: string;
dbPort: number;
dbUsername: string;
dbPassword: string;
dbName: string;
ssrRole: string;
srRole: string;
rRole: string;
welcomeChannel: string;
}

View File

@ -0,0 +1,14 @@
import {IConfig} from "./IConfig";
import {Command} from "../classes/Command";
import {Collection} from "discord.js";
import {SubCommand} from "../classes/SubCommand";
export interface ICustomClient {
config: IConfig;
commands: Collection<string, Command>;
subCommands: Collection<string, SubCommand>;
cooldowns: Collection<string, Collection<string, number>>;
init(): void;
LoadHandlers(): void;
}

View File

@ -0,0 +1,18 @@
import {Dialect} from "sequelize";
export interface IDatabaseConfig {
dialect: Dialect;
host: string;
port: number;
username: string;
password: string;
database: string;
logging?: boolean | ((sql: string, timing?: number) => void);
poolOptions?: {
max?: number;
min?: number;
acquire?: number;
idle?: number;
};
}

View File

@ -0,0 +1,11 @@
import {CustomClient} from "../classes/CustomClient";
import {ClientEvents} from "discord.js";
export interface IEvent {
client: CustomClient;
name: keyof ClientEvents;
description: string;
once: boolean;
execute(...args: any[]): void;
}

View File

@ -0,0 +1,7 @@
import {ClientEvents} from "discord.js";
export interface IEventOptions {
name: keyof ClientEvents;
description: string;
once: boolean;
}

View File

@ -0,0 +1,4 @@
export interface IHandler {
loadEvents(): void;
loadCommands(): void;
}

View File

@ -0,0 +1,9 @@
import {CustomClient} from "../classes/CustomClient";
import {ChatInputCommandInteraction} from "discord.js";
export interface ISubCommand {
client: CustomClient;
name: string;
execute(interaction: ChatInputCommandInteraction): void;
}

View File

@ -0,0 +1,3 @@
export interface ISubCommandOptions {
name: string;
}

40
src/base/models/Rank.ts Normal file
View File

@ -0,0 +1,40 @@
import { Model, DataTypes, Sequelize } from 'sequelize';
import {User} from "./User";
export class Rank extends Model {
declare id: number;
declare name: string;
declare discordId: string;
declare percentage: number;
declare createdAt: Date;
declare updatedAt: Date;
declare users: User[];
public static initModel(sequelize: Sequelize): void {
Rank.init({
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
discordId: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
percentage: {
type: DataTypes.INTEGER,
allowNull: false
},
createdAt: DataTypes.DATE,
updatedAt: DataTypes.DATE,
}, {
sequelize,
tableName: 'ranks'
});
}
}

54
src/base/models/User.ts Normal file
View File

@ -0,0 +1,54 @@
import {
Model,
DataTypes,
Sequelize,
ForeignKey,
NonAttribute,
InferAttributes, InferCreationAttributes, CreationOptional, Association
} from 'sequelize';
import {Rank} from "./Rank";
export class User extends Model<
InferAttributes<User>,
InferCreationAttributes<User>> {
declare id: CreationOptional<number>;
declare discordId: string;
declare rankId: ForeignKey<number>;
declare rank: NonAttribute<Rank>;
declare createdAt: CreationOptional<Date>;
declare updatedAt: CreationOptional<Date>;
public static initModel(sequelize: Sequelize): void {
User.init({
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
discordId: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
rankId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: Rank,
key: 'id'
}
},
createdAt: DataTypes.DATE,
updatedAt: DataTypes.DATE
}, {
sequelize,
tableName: 'users'
});
}
declare static associations: {
rank: Association<User, Rank>;
};
}

View File

@ -0,0 +1,66 @@
import {CustomClient} from "../classes/CustomClient";
import {User} from "../models/User";
import {getRandomRank} from "./RandomUtils";
import {GuildMember} from "discord.js";
import {Rank} from "../models/Rank";
export async function addRole(member: GuildMember, user: User): Promise<void> {
try {
let userRank = await Rank.findOne({
where: {
id: user.rankId
}
});
if (!userRank) {
return;
}
const discordRank = await member.guild.roles.fetch(userRank.discordId);
if (discordRank) {
await member.roles.add(userRank.discordId);
}
} catch (e: Error | any) {
console.log(`Impossible d'ajouter les rôles à ${member.displayName}`);
console.error(e.message);
}
}
export async function createAllUsers(client: CustomClient): Promise<void> {
let count = 0;
const guild = await client.guilds.fetch(client.config.guildId)
const members = await guild.members.fetch();
for (const member of members.values()) {
let user = await User.findOne({
where: {
discordId: member.id
},
include: {
model: Rank,
as: 'rank'
}
})
if (!user) {
user = await User.create({
discordId: member.id,
rankId: (await getRandomRank()).id
}, {
include: [{
model: Rank,
as: 'rank'
}]
});
await addRole(member, user);
count++;
}
}
if (count > 0) {
console.log(`Création de ${count} nouveaux utilisateurs`);
} else {
console.log('Aucun nouvel utilisateur créé');
}
}

View File

@ -0,0 +1,20 @@
import {Rank} from "../models/Rank";
export async function getRandomRank(): Promise<Rank> {
const rand = Math.random() * 100;
let cumulativeChance = 0;
const ranks = await Rank.findAll();
if (ranks.length === 0) {
throw new Error('No ranks found');
}
for (const rank of ranks) {
cumulativeChance += rank.percentage;
if (rand <= cumulativeChance) {
return rank as Rank;
}
}
return ranks[0] as Rank;
}

View File

@ -0,0 +1,25 @@
import {Command} from "../base/classes/Command";
import {CustomClient} from "../base/classes/CustomClient";
import {Category} from "../base/enums/Category";
import {PermissionsBitField} from "discord.js";
export class PingCommand extends Command {
constructor(client: CustomClient) {
super(client, {
name: 'ping',
description: ' Pong!',
category: Category.UTILITIES,
options: [],
default_member_permissions: PermissionsBitField.Flags.UseApplicationCommands,
dm_permission: true,
cooldown: 5
});
}
execute(interaction: any): void {
interaction.reply({
content: `Pong!`,
ephemeral: true
});
}
}

View File

@ -0,0 +1,60 @@
import {Command} from "../base/classes/Command";
import {CustomClient} from "../base/classes/CustomClient";
import {Category} from "../base/enums/Category";
import {EmbedBuilder, GuildMember, PermissionsBitField, SlashCommandUserOption} from "discord.js";
import {User} from "../base/models/User";
import {Rank} from "../base/models/Rank";
import {getRandomRank} from "../base/utils/RandomUtils";
export class PingCommand extends Command {
constructor(client: CustomClient) {
super(client, {
name: 'rank',
description: 'Permet de voir son rang',
category: Category.UTILITIES,
options: [
new SlashCommandUserOption()
.setName('user')
.setDescription('L\'utilisateur dont vous voulez voir le rang')
.setRequired(false)
],
default_member_permissions: PermissionsBitField.Flags.UseApplicationCommands,
dm_permission: false,
cooldown: 1
});
}
async execute(interaction: any): Promise<void> {
let discordUser = (interaction.options.getMember('user') || interaction.member) as GuildMember;
let user = await User.findOne(
{
where: {
discordId: discordUser.id
},
include: [{
model: Rank,
as: 'rank'
}],
}
);
if (!user) {
user = await User.create({
discordId: discordUser.id,
rankId: (await getRandomRank()).id
});
}
// TODO: Remplacer la description par une image générée par le bot
let embed = new EmbedBuilder()
.setTitle(`Rang de ${discordUser.displayName}`)
.setThumbnail(discordUser.displayAvatarURL())
.setDescription(`Cet utilisateur est de rang : ${user.rank.name}`)
.setTimestamp(new Date())
.setColor('#0078DE')
;
await interaction.reply({embeds: [embed]});
}
}

View File

@ -0,0 +1,89 @@
import {Event} from '../../base/classes/Event';
import {CustomClient} from "../../base/classes/CustomClient";
import {Collection, Events, REST, Routes} from "discord.js";
import {Command} from "../../base/classes/Command";
import {createAllUsers} from "../../base/utils/GachaUtils";
import {Rank} from "../../base/models/Rank";
export class Ready extends Event {
constructor(client: CustomClient) {
super(client, {
name: Events.ClientReady,
once: true,
description: 'Event se déclenchant lorsque le bot est prêt'
});
}
async execute(...args: any[]): Promise<void> {
console.log(`Connecté en tant que ${this.client.user?.tag}!`);
const commands: object[] = this.getJson(this.client.commands);
const rest = new REST({version: '10'}).setToken(this.client.config.token);
const guildId = this.client.config.guildId;
const setCommands: any = await rest.put(
Routes.applicationGuildCommands(this.client.user?.id!, guildId),
{
body: commands
}
);
console.log(`${setCommands.length} Commandes mises à jours avec succès !`);
if (process.env.INIT_DB === 'true') {
await this.initDb();
} else {
await createAllUsers(this.client);
}
}
private getJson(commands: Collection<string, Command>): object[] {
const data: object[] = [];
commands.forEach((command: Command) => {
data.push({
name: command.name,
description: command.description,
options: command.options,
default_member_permissions: command.default_member_permissions.toString(),
dm_permission: command.dm_permission,
})
});
return data;
}
private async initDb() {
// On commence par vérifier si les rangs existent déjà
const ranks = await Rank.findAll();
if (ranks.length > 0) {
return;
}
await Rank.create({
name: '1★',
discordId: '1234567890',
percentage: 1,
});
await Rank.create({
name: '2★',
discordId: '2345678901',
percentage: 48,
});
await Rank.create({
name: '3★',
discordId: '3456789012',
percentage: 41,
});
await Rank.create({
name: '4★',
discordId: '4567890123',
percentage: 2,
});
await Rank.create({
name: '5★',
discordId: '5678901234',
percentage: 3,
});
}
}

View File

@ -0,0 +1,56 @@
import {ChatInputCommandInteraction, Collection, Events} from "discord.js";
import {CustomClient} from "../../base/classes/CustomClient";
import {Event} from "../../base/classes/Event";
import {Command} from "../../base/classes/Command";
export class CommandHandler extends Event {
constructor(client: CustomClient) {
super(client, {
name: Events.InteractionCreate,
once: false,
description: 'Event se déclenchant lorsqu\'une interaction est créée'
});
}
async execute(interaction: ChatInputCommandInteraction): Promise<void> {
if (!interaction.isChatInputCommand()) return;
const command: Command = this.client.commands.get(interaction.commandName) as Command;
if (!command) {
await interaction.reply({content: 'Commande inconnue', ephemeral: true})
this.client.commands.delete(interaction.commandName);
return;
}
const {cooldowns} = this.client;
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name)!;
const cooldownAmount = (command.cooldown || 3) * 1000;
if (timestamps.has(interaction.user.id) && now < (timestamps.get(interaction.user.id) || 0) + cooldownAmount) {
const timeLeft = (((timestamps.get(interaction.user.id) || 0) + cooldownAmount - now) / 1000).toFixed(1);
await interaction.reply({
content: `Veuillez patienter ${timeLeft} secondes avant de réutiliser la commande \`${command.name}\``,
ephemeral: true
});
return;
}
timestamps.set(interaction.user.id, now);
setTimeout(() => timestamps.delete(interaction.user.id), cooldownAmount);
try {
const subCommandGroup = interaction.options.getSubcommandGroup(false);
const subCommand = `${interaction.commandName}${subCommandGroup ? `.${subCommandGroup}` : ''}.${interaction.options.getSubcommand(false)}` || '';
this.client.subCommands.get(subCommand)?.execute(interaction) || command.execute(interaction);
} catch (error) {
console.error(error);
}
}
}

View File

@ -0,0 +1,55 @@
import {EmbedBuilder, Events, GuildMember} from "discord.js";
import {CustomClient} from "../../base/classes/CustomClient";
import {Event} from "../../base/classes/Event";
import {User} from "../../base/models/User";
import {getRandomRank} from "../../base/utils/RandomUtils";
import {addRole} from "../../base/utils/GachaUtils";
import {Rank} from "../../base/models/Rank";
export class GuildMemberJoin extends Event {
constructor(client: CustomClient) {
super(client, {
name: Events.GuildMemberAdd,
once: false,
description: 'Event se déclenchant lorsqu\'un utilisateur rejoint le serveur'
});
}
async execute(member: GuildMember): Promise<void> {
let user = await User.findOne({
where: {
discordId: member.id
}
});
if (!user) {
user = await User.create({
discordId: member.id,
rankId: (await getRandomRank()).id
}, {
include: [{
model: Rank,
as: 'rank'
}]
});
}
await addRole(member, user);
const channel = await member.guild.channels.fetch(this.client.config.welcomeChannel);
if (channel && channel.isTextBased()) {
// TODO : Remplacer la description par une image générée par le bot
let embed = new EmbedBuilder()
.setTitle(`Bienvenue sur le serveur ${member.displayName} !`)
.setThumbnail(member.displayAvatarURL())
.setDescription(`Bien joué ! Tu as obtenu le rang : ${user.rank.name}`)
.setTimestamp(new Date())
.setColor('#0078DE')
;
await channel.send({embeds: [embed]});
}
}
}

2
src/index.ts Normal file
View File

@ -0,0 +1,2 @@
import {CustomClient} from "./base/classes/CustomClient";
(async () => await new CustomClient().init())();

View File

@ -1,47 +0,0 @@
package org.camelia.studio.gachamelia;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
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.utils.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
HibernateConfig.shutdown();
jda.shutdown();
}));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.error("Le thread a été interrompu : {}", e.getMessage());
System.exit(1);
} 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;
}
}

View File

@ -1,94 +0,0 @@
package org.camelia.studio.gachamelia.commands.personnage;
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.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 org.camelia.studio.gachamelia.interfaces.ISlashCommand;
import org.camelia.studio.gachamelia.models.User;
import org.camelia.studio.gachamelia.models.UserStat;
import org.camelia.studio.gachamelia.repositories.StatRepository;
import org.camelia.studio.gachamelia.services.UserService;
import java.awt.*;
import java.util.List;
public class FichePersoCommand implements ISlashCommand {
@Override
public String getName() {
return "ficheperso";
}
@Override
public String getDescription() {
return "Permet d'afficher la fiche de personnage de l'utilisateur";
}
@Override
public List<OptionData> getOptions() {
return List.of(
new OptionData(OptionType.USER, "utilisateur", "L'utilisateur dont vous souhaitez afficher la fiche de personnage").setRequired(false)
);
}
@Override
public void execute(SlashCommandInteractionEvent event) {
OptionMapping utilisateur = event.getOption("utilisateur");
Member member = utilisateur != null ? utilisateur.getAsMember() : event.getMember();
if (member == null) {
event.getHook().editOriginal("L'utilisateur n'a pas été trouvé").queue();
return;
}
if (event.getGuild() == null) {
event.getHook().editOriginal("Le serveur n'a pas été trouvé").queue();
return;
}
EmbedBuilder embedGeneralite = new EmbedBuilder();
User user = UserService.getInstance().getOrCreateUser(member.getId());
Role role = event.getGuild().getRoleById(user.getRank().getDiscordId());
Color color = role != null ? role.getColor() : Color.WHITE;
List<UserStat> stats = StatRepository.getInstance().getUserStats(user);
StringBuilder description = new StringBuilder("""
__Caractéristiques principales__ :
- Nom : **%s**
- Rareté : **%s**
- Rôle : **%s**
- Éléments : *%s*
- Xp : **%d**
- Emblème : **%s**
__Statistiques de combat__ :
""".formatted(
member.getEffectiveName(),
user.getRank().getName(),
user.getRole().getName(),
String.join(", ", user.getElement().getName()),
0,
"Ø"
));
for (UserStat stat : stats) {
int userStat = stat.getValue();
int equipmentStat = 0;
description.append("- %s : **%d** (%d + %d)\n".formatted(stat.getStat().getName(), userStat + equipmentStat, userStat, equipmentStat));
}
embedGeneralite.setAuthor(member.getEffectiveName(), null, user.getRole().getImageUrl());
embedGeneralite.setTitle("Fiche de personnage");
embedGeneralite.setColor(color);
embedGeneralite.setThumbnail(member.getUser().getEffectiveAvatarUrl());
embedGeneralite.setDescription(description.toString());
event.getChannel().sendMessageEmbeds(List.of(
embedGeneralite.build()
)).queue();
event.getHook().editOriginal("Fiche de personnage de %s".formatted(member.getEffectiveName())).queue();
}
}

View File

@ -1,20 +0,0 @@
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

@ -1,85 +0,0 @@
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

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

View File

@ -1,16 +0,0 @@
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

@ -1,70 +0,0 @@
package org.camelia.studio.gachamelia.listeners;
import jakarta.annotation.Nonnull;
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 java.awt.*;
public class GuildMemberJoinListener extends ListenerAdapter {
@Override
public void onGuildMemberJoin(@Nonnull 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"));
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();
}
StringBuilder description = new StringBuilder();
description.append("Bravo ! Vous venez d'invoquer ")
.append(member.getAsMention()).append(" !\n")
.append("Il s'agit d'un personnage de rareté ")
.append(user.getRank().getName()).append(" ! ")
.append(welcomeMessage.getMessage());
description.append("\n\n")
.append("__Caractéristiques principales__ :\n")
.append("• Rôle « ").append(user.getRole().getName()).append(" ».").append("\n")
.append("• Élément « ").append(user.getElement().getName()).append(" ».").append("\n")
;
EmbedBuilder embedBuilder = new EmbedBuilder()
.setTitle(event.getMember().getEffectiveName() + " vient d'être invoqué !")
.setDescription(description)
.setThumbnail(member.getUser().getEffectiveAvatarUrl())
.setTimestamp(event.getMember().getTimeJoined())
.setFooter(
"Gachamélia v%s « %s »".formatted(
Configuration.getInstance().getDotenv().get("APP_VERSION", "0.0.1"),
Configuration.getInstance().getDotenv().get("APP_DESCRIPTION", "J'ai posé un pied à terre.")
),
event.getJDA().getSelfUser().getAvatarUrl())
.setColor(color);
if (channel != null) {
channel.sendMessageEmbeds(embedBuilder.build()).queue();
}
}
}

View File

@ -1,60 +0,0 @@
package org.camelia.studio.gachamelia.listeners;
import jakarta.annotation.Nonnull;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Role;
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 org.camelia.studio.gachamelia.models.ByeMessage;
import org.camelia.studio.gachamelia.models.User;
import org.camelia.studio.gachamelia.services.RankService;
import org.camelia.studio.gachamelia.services.UserService;
import org.camelia.studio.gachamelia.utils.Configuration;
import java.awt.*;
import java.time.Instant;
public class GuildMemberLeaveListener extends ListenerAdapter {
@Override
public void onGuildMemberRemove(@Nonnull GuildMemberRemoveEvent event) {
net.dv8tion.jda.api.entities.User discordUser = event.getUser();
User user = UserService.getInstance().getOrCreateUser(discordUser.getId());
ByeMessage byeMessage = RankService.getInstance().getRandomByeMessage(user.getRank());
TextChannel channel = event.getGuild().getTextChannelById(Configuration.getInstance().getDotenv().get("WELCOME_CHANNEL", "0"));
Role role = event.getGuild().getRoleById(user.getRank().getDiscordId());
Color color = new Color(0, 0, 0);
if (role != null) {
color = role.getColor();
}
StringBuilder description = new StringBuilder();
description.append(byeMessage.getMessage().replace("%username%", "**" + discordUser.getEffectiveName() + "**"));
EmbedBuilder embedBuilder = new EmbedBuilder()
.setTitle(user.getRank().getByeTitle() != null ? user.getRank().getByeTitle() : "Au revoir, %s !".formatted(discordUser.getEffectiveName()))
.setDescription(description)
.setThumbnail(discordUser.getEffectiveAvatarUrl())
.setTimestamp(Instant.now())
.setFooter(
"Gachamélia v%s « %s »".formatted(
Configuration.getInstance().getDotenv().get("APP_VERSION", "0.0.1"),
Configuration.getInstance().getDotenv().get("APP_DESCRIPTION", "J'ai posé un pied à terre.")
),
event.getJDA().getSelfUser().getAvatarUrl())
.setColor(color);
if (channel != null) {
channel.sendMessageEmbeds(embedBuilder.build()).queue();
}
}
}

View File

@ -1,81 +0,0 @@
package org.camelia.studio.gachamelia.listeners;
import jakarta.annotation.Nonnull;
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.events.session.ReadyEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.camelia.studio.gachamelia.models.Stat;
import org.camelia.studio.gachamelia.models.User;
import org.camelia.studio.gachamelia.models.UserStat;
import org.camelia.studio.gachamelia.repositories.ElementRepository;
import org.camelia.studio.gachamelia.repositories.RankRepository;
import org.camelia.studio.gachamelia.repositories.RoleRepository;
import org.camelia.studio.gachamelia.repositories.StatRepository;
import org.camelia.studio.gachamelia.services.ElementService;
import org.camelia.studio.gachamelia.services.RankService;
import org.camelia.studio.gachamelia.services.RoleService;
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 ReadyListener extends ListenerAdapter {
private static final Logger logger = LoggerFactory.getLogger(ReadyListener.class);
@Override
public void onReady(@Nonnull ReadyEvent event) {
logger.info("Connecté en tant que {}", event.getJDA().getSelfUser().getAsTag());
initDatabase(event.getJDA());
}
private void initDatabase(JDA jda) {
if (!RankRepository.getInstance().findAll().isEmpty() || !RoleRepository.getInstance().findAll().isEmpty() || !ElementRepository.getInstance().findAll().isEmpty() || !StatRepository.getInstance().findAll().isEmpty()) {
Guild guild = jda.getGuildById(Configuration.getInstance().getDotenv().get("GUILD_ID"));
if (guild != null) {
guild.loadMembers().onSuccess(members -> {
for (Member member : members) {
User user = UserService.getInstance().getOrCreateUser(member.getId());
if (user.getRank() == null) {
user.setRank(RankService.getInstance().getRandomRank());
UserService.getInstance().updateUser(user);
}
if (user.getRole() == null) {
user.setRole(RoleService.getInstance().getRandomRole());
UserService.getInstance().updateUser(user);
}
if (user.getElement() == null) {
user.setElement(ElementService.getInstance().getRandomElement());
UserService.getInstance().updateUser(user);
}
List<UserStat> stats = StatRepository.getInstance().getUserStats(user);
if (stats.isEmpty()) {
List<Stat> statsList = StatRepository.getInstance().findAll();
for (Stat stat : statsList) {
UserStat userStat = new UserStat();
userStat.setUser(user);
userStat.setStat(stat);
userStat.setValue(0);
StatRepository.getInstance().saveUserStat(userStat);
}
}
logger.info("Utilisateur {} initialisé", member.getUser().getAsTag());
}
});
}
} else {
logger.error("Aucun rang ou rôle n'a été trouvé dans la base de données");
System.exit(1);
}
}
}

View File

@ -1,22 +0,0 @@
package org.camelia.studio.gachamelia.listeners;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import jakarta.annotation.Nonnull;
import org.camelia.studio.gachamelia.managers.CommandManager;
public class SlashCommandListener extends ListenerAdapter {
private final CommandManager commandManager;
public SlashCommandListener() {
commandManager = new CommandManager();
commandManager.registerCommands();
}
@Override
public void onSlashCommandInteraction(@Nonnull SlashCommandInteractionEvent event) {
event.deferReply().setEphemeral(true).queue();
commandManager.handleCommand(event.getName(), event);
}
}

View File

@ -1,63 +0,0 @@
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
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

@ -1,35 +0,0 @@
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.GuildMemberLeaveListener;
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());
addListener(new GuildMemberLeaveListener());
}
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

@ -1,46 +0,0 @@
package org.camelia.studio.gachamelia.models;
import jakarta.persistence.*;
import org.camelia.studio.gachamelia.interfaces.IEntity;
@Entity
@Table(name = "bye_messages")
public class ByeMessage implements IEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
private Rank rank;
@Column(nullable = false)
private String message;
public ByeMessage() {
}
public ByeMessage(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

@ -1,43 +0,0 @@
package org.camelia.studio.gachamelia.models;
import jakarta.persistence.*;
import org.camelia.studio.gachamelia.interfaces.IEntity;
import java.util.List;
@Entity
@Table(name = "elements")
public class Element implements IEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@OneToMany(mappedBy = "element")
private List<User> users;
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public Element() {
}
public Element(String name) {
this.name = name;
}
}

View File

@ -1,128 +0,0 @@
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.ArrayList;
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, 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;
@OneToMany(mappedBy = "rank")
private List<ByeMessage> byeMessages;
@CreationTimestamp
@Column(name = "createdAt")
private LocalDateTime createdAt;
@UpdateTimestamp
@Column(name = "updatedAt")
private LocalDateTime updatedAt;
@Column(name = "byeTitle")
private String byeTitle;
@OneToMany(mappedBy = "id.rank", fetch = FetchType.LAZY)
private final List<RankStat> rankStats = new ArrayList<>();
public List<RankStat> getRankStats() {
return rankStats;
}
public Rank(String discordId, String name, int percentage) {
this.discordId = discordId;
this.name = name;
this.percentage = percentage;
}
public Rank(String discordId, String name, int percentage, String byeTitle) {
this.discordId = discordId;
this.name = name;
this.percentage = percentage;
this.byeTitle = byeTitle;
}
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;
}
public List<ByeMessage> getByeMessages() {
return byeMessages;
}
public String getByeTitle() {
return byeTitle;
}
public void setByeTitle(String byeTitle) {
this.byeTitle = byeTitle;
}
}

View File

@ -1,73 +0,0 @@
package org.camelia.studio.gachamelia.models;
import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import org.camelia.studio.gachamelia.interfaces.IEntity;
import java.util.Objects;
@Entity
@Table(name = "rank_stats")
public class RankStat implements IEntity {
@EmbeddedId
private RankStatId id;
@Column(nullable = false)
private int percentage;
public RankStat() {
}
public RankStat(Rank rank, Stat stat, int percentage) {
this.id = new RankStatId(rank, stat);
this.percentage = percentage;
}
public RankStatId getId() {
return id;
}
public Rank getRank() {
return id.getRank();
}
public Stat getStat() {
return id.getStat();
}
public int getPercentage() {
return percentage;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public void setRank(Rank rank) {
if (this.id == null) {
this.id = new RankStatId();
}
this.id.setRank(rank);
}
public void setStat(Stat stat) {
if (this.id == null) {
this.id = new RankStatId();
}
this.id.setStat(stat);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RankStat rankStat)) return false;
return Objects.equals(id, rankStat.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}

View File

@ -1,53 +0,0 @@
package org.camelia.studio.gachamelia.models;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import java.io.Serializable;
import java.util.Objects;
public class RankStatId implements Serializable {
@ManyToOne
@JoinColumn(name = "rank_id", nullable = false)
private Rank rank;
@ManyToOne
@JoinColumn(name = "stat_id", nullable = false)
private Stat stat;
public RankStatId() {
}
public RankStatId(Rank rank, Stat stat) {
this.rank = rank;
this.stat = stat;
}
public Rank getRank() {
return rank;
}
public Stat getStat() {
return stat;
}
public void setRank(Rank rank) {
this.rank = rank;
}
public void setStat(Stat stat) {
this.stat = stat;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RankStatId that)) return false;
return rank.equals(that.rank) && stat.equals(that.stat);
}
@Override
public int hashCode() {
return Objects.hash(rank, stat);
}
}

View File

@ -1,68 +0,0 @@
package org.camelia.studio.gachamelia.models;
import jakarta.persistence.*;
import org.camelia.studio.gachamelia.interfaces.IEntity;
import org.hibernate.annotations.ColumnDefault;
import java.util.List;
@Entity
@Table(name = "roles")
public class Role implements IEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private int percentage;
@Column(nullable = false, name = "image_url")
@ColumnDefault(value = "'https://placehold.co/400'")
private String imageUrl;
@OneToMany(mappedBy = "role")
private List<User> users;
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public List<User> getUsers() {
return users;
}
public Long getId() {
return id;
}
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 Role() {
}
public Role(String name, int percentage) {
this.name = name;
this.percentage = percentage;
}
}

View File

@ -1,45 +0,0 @@
package org.camelia.studio.gachamelia.models;
import jakarta.persistence.*;
import org.camelia.studio.gachamelia.interfaces.IEntity;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "stats")
public class Stat implements IEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@OneToMany(mappedBy = "id.stat", fetch = FetchType.LAZY)
private final List<RankStat> rankStats = new ArrayList<>();
public List<RankStat> getRankStats() {
return rankStats;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Stat() {
}
public Stat(String name) {
this.name = name;
}
}

View File

@ -1,89 +0,0 @@
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;
@ManyToOne(fetch = FetchType.EAGER)
private Element element;
@ManyToOne(fetch = FetchType.EAGER)
private Role role;
public Element getElement() {
return element;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public void setElement(Element element) {
this.element = element;
}
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

@ -1,73 +0,0 @@
package org.camelia.studio.gachamelia.models;
import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import org.camelia.studio.gachamelia.interfaces.IEntity;
import java.util.Objects;
@Entity
@Table(name = "user_stats")
public class UserStat implements IEntity {
@EmbeddedId
private UserStatId id;
@Column(nullable = false)
private int value;
public UserStat() {
}
public UserStat(User user, Stat stat, int value) {
this.id = new UserStatId(user, stat);
this.value = value;
}
public UserStatId getId() {
return id;
}
public User getUser() {
return id.getUser();
}
public void setUser(User user) {
if (this.id == null) {
this.id = new UserStatId();
}
this.id.setUser(user);
}
public Stat getStat() {
return id.getStat();
}
public void setStat(Stat stat) {
if (this.id == null) {
this.id = new UserStatId();
}
this.id.setStat(stat);
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UserStat userStat)) return false;
return Objects.equals(id, userStat.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}

View File

@ -1,54 +0,0 @@
package org.camelia.studio.gachamelia.models;
import jakarta.persistence.FetchType;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import java.io.Serializable;
import java.util.Objects;
public class UserStatId implements Serializable {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "stat_id", nullable = false)
private Stat stat;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id", nullable = false)
private User user;
public UserStatId() {
}
public UserStatId(User user, Stat stat) {
this.stat = stat;
this.user = user;
}
public Stat getStat() {
return stat;
}
public void setStat(Stat stat) {
this.stat = stat;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UserStatId that)) return false;
return stat.equals(that.stat) && user.equals(that.user);
}
@Override
public int hashCode() {
return Objects.hash(stat, user);
}
}

View File

@ -1,46 +0,0 @@
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

@ -1,31 +0,0 @@
package org.camelia.studio.gachamelia.repositories;
import org.camelia.studio.gachamelia.db.HibernateConfig;
import org.camelia.studio.gachamelia.models.Element;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.util.List;
public class ElementRepository {
private static ElementRepository instance;
private final SessionFactory sessionFactory;
public ElementRepository() {
this.sessionFactory = HibernateConfig.getSessionFactory();
}
public static ElementRepository getInstance() {
if (instance == null) {
instance = new ElementRepository();
}
return instance;
}
public List<Element> findAll() {
try (Session session = sessionFactory.openSession()) {
return session.createQuery("FROM Element", Element.class).list();
}
}
}

View File

@ -1,109 +0,0 @@
package org.camelia.studio.gachamelia.repositories;
import org.camelia.studio.gachamelia.db.HibernateConfig;
import org.camelia.studio.gachamelia.models.ByeMessage;
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 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;
}
}
}
public ByeMessage getRandomByeMessage(Rank rank) {
try (Session session = sessionFactory.openSession()) {
session.beginTransaction();
try {
Rank refreshedRank = session.get(Rank.class, rank.getId());
List<ByeMessage> byeMessages = refreshedRank.getByeMessages();
if (byeMessages.isEmpty()) {
return null;
}
ByeMessage message = byeMessages.get(
ThreadLocalRandom.current().nextInt(byeMessages.size())
);
session.getTransaction().commit();
return message;
} catch (Exception e) {
session.getTransaction().rollback();
throw e;
}
}
}
}

View File

@ -1,31 +0,0 @@
package org.camelia.studio.gachamelia.repositories;
import org.camelia.studio.gachamelia.db.HibernateConfig;
import org.camelia.studio.gachamelia.models.Role;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.util.List;
public class RoleRepository {
private static RoleRepository instance;
private final SessionFactory sessionFactory;
public RoleRepository() {
this.sessionFactory = HibernateConfig.getSessionFactory();
}
public static RoleRepository getInstance() {
if (instance == null) {
instance = new RoleRepository();
}
return instance;
}
public List<Role> findAll() {
try (Session session = sessionFactory.openSession()) {
return session.createQuery("FROM Role", Role.class).list();
}
}
}

View File

@ -1,50 +0,0 @@
package org.camelia.studio.gachamelia.repositories;
import org.camelia.studio.gachamelia.db.HibernateConfig;
import org.camelia.studio.gachamelia.models.Stat;
import org.camelia.studio.gachamelia.models.User;
import org.camelia.studio.gachamelia.models.UserStat;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.util.List;
public class StatRepository {
private static StatRepository instance;
private final SessionFactory sessionFactory;
public StatRepository() {
this.sessionFactory = HibernateConfig.getSessionFactory();
}
public static StatRepository getInstance() {
if (instance == null) {
instance = new StatRepository();
}
return instance;
}
public List<Stat> findAll() {
try (Session session = sessionFactory.openSession()) {
return session.createQuery("FROM Stat", Stat.class).list();
}
}
public List<UserStat> getUserStats(User user) {
try (Session session = sessionFactory.openSession()) {
return session.createQuery("FROM UserStat us WHERE us.id.user.id = :userId", UserStat.class)
.setParameter("userId", user.getId())
.getResultList();
}
}
public void saveUserStat(UserStat userStat) {
try (Session session = sessionFactory.openSession()) {
session.beginTransaction();
session.persist(userStat);
session.getTransaction().commit();
}
}
}

View File

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

@ -1,36 +0,0 @@
package org.camelia.studio.gachamelia.services;
import org.camelia.studio.gachamelia.models.Element;
import org.camelia.studio.gachamelia.repositories.ElementRepository;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class ElementService {
private static ElementService instance;
public static ElementService getInstance() {
if (instance == null) {
instance = new ElementService();
}
return instance;
}
public Element getRandomElement() {
List<Element> elements = ElementRepository.getInstance().findAll();
int percentage = ThreadLocalRandom.current().nextInt(elements.size()) + 1;
int cumulativePercentage = 0;
for (Element element : elements) {
cumulativePercentage++;
if (percentage <= cumulativePercentage) {
return element;
}
}
// Ne devrait jamais arriver
return null;
}
}

View File

@ -1,72 +0,0 @@
package org.camelia.studio.gachamelia.services;
import org.camelia.studio.gachamelia.models.ByeMessage;
import org.camelia.studio.gachamelia.models.Rank;
import org.camelia.studio.gachamelia.models.WelcomeMessage;
import org.camelia.studio.gachamelia.repositories.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 Rank getOrCreateRank(String name, String discordId, int percentage, String byeTitle) {
Rank rank = RankRepository.getInstance().findByName(name);
if (rank == null) {
rank = new Rank(discordId, name, percentage, byeTitle);
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);
}
public ByeMessage getRandomByeMessage(Rank rank) {
return RankRepository.getInstance().getRandomByeMessage(rank);
}
}

View File

@ -1,36 +0,0 @@
package org.camelia.studio.gachamelia.services;
import org.camelia.studio.gachamelia.models.Role;
import org.camelia.studio.gachamelia.repositories.RoleRepository;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class RoleService {
private static RoleService instance;
public static RoleService getInstance() {
if (instance == null) {
instance = new RoleService();
}
return instance;
}
public Role getRandomRole() {
List<Role> roles = RoleRepository.getInstance().findAll();
int percentage = ThreadLocalRandom.current().nextInt(100);
int cumulativePercentage = 0;
for (Role role : roles) {
cumulativePercentage += role.getPercentage();
if (percentage <= cumulativePercentage) {
return role;
}
}
// Ne devrait jamais arriver
return null;
}
}

View File

@ -1,55 +0,0 @@
package org.camelia.studio.gachamelia.services;
import org.camelia.studio.gachamelia.models.*;
import org.camelia.studio.gachamelia.repositories.StatRepository;
import org.camelia.studio.gachamelia.repositories.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);
Role role = RoleService.getInstance().getRandomRole();
user.setRole(role);
Element element = ElementService.getInstance().getRandomElement();
user.setElement(element);
List<Stat> stats = StatRepository.getInstance().findAll();
for (Stat stat : stats) {
UserStat userStat = new UserStat();
userStat.setUser(user);
userStat.setStat(stat);
userStat.setValue(0);
StatRepository.getInstance().saveUserStat(userStat);
}
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

@ -1,23 +0,0 @@
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

@ -1,14 +0,0 @@
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

@ -1,105 +0,0 @@
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

@ -1,14 +0,0 @@
<?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>

12
tsconfig.json Normal file
View File

@ -0,0 +1,12 @@
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"rootDir": "./src",
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}