Separated the cmdManager logic like PotatOS and added the version to gradle.properties #10

Merged
Skydust merged 1 commits from f/separated-cmds into dev 2023-09-17 14:48:18 +00:00
8 changed files with 171 additions and 85 deletions

View File

@@ -9,7 +9,7 @@ WORKDIR /app
RUN apt update && apt install -y zabbix-sender && rm -rf /var/lib/apt/lists/* RUN apt update && apt install -y zabbix-sender && rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/build/libs/JdrBot-all.jar /app/JdrBot.jar COPY --from=builder /app/build/libs/JdrBot.jar /app/JdrBot.jar
COPY start.sh /app COPY start.sh /app
CMD ["/bin/bash","./start.sh"] CMD ["/bin/bash","./start.sh"]

View File

@@ -44,8 +44,12 @@ application {
mainClassName = 'fr.Skydust.JdrBot.JdrBot' mainClassName = 'fr.Skydust.JdrBot.JdrBot'
} }
shadowJar {
archiveFileName = "${project.name}.jar"
}
jar { jar {
manifest { manifest {
attributes 'Main-Class': 'fr.Skydust.JdrBot.JdrBot' attributes 'Main-Class': 'fr.Skydust.JdrBot.JdrBot', 'Implementation-Version': version
} }
} }

1
gradle.properties Normal file
View File

@@ -0,0 +1 @@
version=4.1

View File

@@ -1,54 +1,26 @@
package fr.Skydust.JdrBot; package fr.Skydust.JdrBot;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Timer; import java.util.Timer;
import fr.Skydust.JdrBot.bases.command.Command;
import fr.Skydust.JdrBot.bases.command.CommandSpec;
import fr.Skydust.JdrBot.tasks.HeartbeatTask; import fr.Skydust.JdrBot.tasks.HeartbeatTask;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity; import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.requests.GatewayIntent; import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.utils.cache.CacheFlag; import net.dv8tion.jda.api.utils.cache.CacheFlag;
import org.reflections.Reflections; import fr.Skydust.JdrBot.bases.CommandManager.CommandsManager;
public class JdrBot { public class JdrBot {
public static String Version = "4.0"; public static String Version = JdrBot.class.getPackage().getImplementationVersion();
public static JDA jda; public static JDA jda;
public static LocalDateTime basedate; public static LocalDateTime basedate;
public static List<Command> commandList;
public static String startcmdchar = "!|:";
public static boolean debugMode = false; public static boolean debugMode = false;
public static void main(String[] args) { public static void main(String[] args) {
for (int i=0;i<args.length;i++) { parseArgs(args);
if(args[i].equalsIgnoreCase("--heartbeat")) {
if(i == args.length-1) { // Check for an argument after heartbeat
System.out.println("USAGE: --heartbeat [Command({ping})]");
return; // Quits the program
}
//"zabbix_sender -z localhost -s \"Lustricru\" -k discordBots.potatos.ping -o {ping}"
String command = args[i+1];
//SkipCMD
i++;
new Timer().scheduleAtFixedRate(new HeartbeatTask(command),1000, 60000);
System.out.println("Registered Heartbeat Command: "+command);
} else if(args[i].equalsIgnoreCase("--debug")) {
debugMode = true;
System.out.println("Warning: the bot is in debug mode");
}
}
try { try {
basedate = LocalDateTime.now(); basedate = LocalDateTime.now();
@@ -65,7 +37,7 @@ public class JdrBot {
jda.awaitReady(); jda.awaitReady();
registerCommands(); CommandsManager.registerCommands(jda, "!");
jda.addEventListener(new JdrBotListener()); jda.addEventListener(new JdrBotListener());
} catch (Exception e) { } catch (Exception e) {
@@ -73,24 +45,30 @@ public class JdrBot {
} }
} }
/**
* Finds every class annotated with CommandSpec and registers them as a command.
*/
public static void registerCommands() {
commandList = new ArrayList<Command>();
Reflections reflections = new Reflections("fr.Skydust.JdrBot.cmds"); private static void parseArgs(String[] args) {
Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(CommandSpec.class); for (int i=0;i<args.length;i++) {
String currentArgument = args[i].toLowerCase();
for (Class<?> command: annotated) { switch (currentArgument) {
try { case "--heartbeat" -> {
Command cmd = (Command) command.getDeclaredConstructor().newInstance(); if (i == args.length - 1) { // Check for an argument after heartbeat
commandList.add(cmd); System.out.println("USAGE: --heartbeat [Command({ping})]");
return; // Quits the program
}
//Example: "zabbix_sender -z localhost -s \"Lustricru\" -k discordBots.potatos.ping -o {ping}"
String command = args[i + 1];
System.out.println("Registered command "+ cmd.cmdName); //Skip next arg
} catch (InstantiationException | NoSuchMethodException | InvocationTargetException | i++;
IllegalAccessException e) {
throw new RuntimeException(e); new Timer().scheduleAtFixedRate(new HeartbeatTask(command), 1000, 60000);
System.out.println("Registered Heartbeat Command: " + command);
}
case "--debug" -> {
debugMode = true;
System.out.println("Warning: the bot is in debug mode");
}
} }
} }
} }

View File

@@ -1,45 +1,22 @@
package fr.Skydust.JdrBot; package fr.Skydust.JdrBot;
import fr.Skydust.JdrBot.bases.command.Command;
import fr.Skydust.JdrBot.cmds.LastTimeOnline; import fr.Skydust.JdrBot.cmds.LastTimeOnline;
import fr.Skydust.JdrBot.cmds.playmusic.StopMusic; import fr.Skydust.JdrBot.cmds.playmusic.StopMusic;
import fr.Skydust.JdrBot.menu.MenuSystem; import fr.Skydust.JdrBot.menu.MenuSystem;
import fr.Skydust.JdrBot.tasks.HeartbeatTask; import fr.Skydust.JdrBot.tasks.HeartbeatTask;
import net.dv8tion.jda.api.events.GatewayPingEvent; import net.dv8tion.jda.api.events.GatewayPingEvent;
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceUpdateEvent; import net.dv8tion.jda.api.events.guild.voice.GuildVoiceUpdateEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent; import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent;
import net.dv8tion.jda.api.events.user.update.UserUpdateOnlineStatusEvent; import net.dv8tion.jda.api.events.user.update.UserUpdateOnlineStatusEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class JdrBotListener extends ListenerAdapter { public class JdrBotListener extends ListenerAdapter {
@Override
public void onMessageReceived(MessageReceivedEvent e) {
// IF it doesn't start with the startcmdchar, ignore for optimization
if (!e.getMessage().getContentRaw().matches("^("+ JdrBot.startcmdchar+").*$") || e.getMessage().getAuthor().isBot())
return;
// Go through all cmds and call the one corresponding
for (Command cmd : JdrBot.commandList) {
if (isACommand(e.getMessage().getContentRaw(), cmd.cmdName)) {
cmd.call(e);
return;
}
}
if (isACommand(e.getMessage().getContentRaw(), "yay"))
{
e.getChannel().sendMessage("Bien joue! Tu as su surpasse toutes les epreuves pour en arriver la! Woo !").queue();
}
}
/* LastTimeOnline listener */ /* LastTimeOnline listener */
@Override @Override
public void onUserUpdateOnlineStatus(@NotNull UserUpdateOnlineStatusEvent e) { public void onUserUpdateOnlineStatus(@NotNull UserUpdateOnlineStatusEvent e) {
LastTimeOnline.onUserUpdateOnlineStatus(e); LastTimeOnline.onUserUpdateOnlineStatus(e);
} }
/* Empty voice channel listener */ /* Empty voice channel listener */
@Override @Override
public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent e) { public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent e) {
@@ -51,8 +28,4 @@ public class JdrBotListener extends ListenerAdapter {
/* Heartbeat command listener */ /* Heartbeat command listener */
@Override @Override
public void onGatewayPing(@NotNull GatewayPingEvent e) { HeartbeatTask.HeartbeatUpdateEvent(e); } public void onGatewayPing(@NotNull GatewayPingEvent e) { HeartbeatTask.HeartbeatUpdateEvent(e); }
public boolean isACommand(String message, String cmd) {
return message.matches("^("+ JdrBot.startcmdchar +")("+ cmd +")( .*|)$");
}
} }

View File

@@ -0,0 +1,113 @@
package fr.Skydust.JdrBot.bases.CommandManager;
import fr.Skydust.JdrBot.bases.command.Command;
import fr.Skydust.JdrBot.bases.command.CommandSpec;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.reflections.Reflections;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class CommandsManager {
private static List<Command> commandList;
private static String startCmdChar = "";
/**
* Retrieves the main package name from the stacktrace.
* @return The application's root package name.
*/
public static String getMainClassPackageName()
{
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
if (trace.length > 0) {
String mainClassName = trace[trace.length - 1].getClassName();
return mainClassName.split("\\.")[0];
}
return null;
}
/**
* Finds every class annotated with CommandSpec and registers them as a command.
* @param jda The instance to register commands for.
* @param startChar The regex to use for the start character.
*/
public static void registerCommands(JDA jda, String startChar) {
if(commandList != null)
throw new RuntimeException("Tried to call registerCommands twice !");
if(startChar == null || startChar.isEmpty())
throw new RuntimeException("The starting character of the bot cannot be empty !");
String packageName = getMainClassPackageName();
if(packageName == null || packageName.isEmpty())
throw new RuntimeException("Could not determine the main package name.");
commandList = new ArrayList<Command>();
startCmdChar = startChar;
Reflections reflections = new Reflections(packageName);
Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(CommandSpec.class);
for (Class<?> command: annotated) {
try {
Command cmd = (Command) command.getDeclaredConstructor().newInstance();
commandList.add(cmd);
System.out.println("Registered command "+ cmd.cmdName);
} catch (InstantiationException | NoSuchMethodException | InvocationTargetException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
}
jda.addEventListener(new CommandsManagerListener());
}
/**
* Retrieve the command list.
* @return A list of commands.
*/
public static List<Command> getCommandList() {
return commandList;
}
/**
* Get the start character of commands.
* @return A regex containing every cmd chars.
*/
public static String getCmdChar() {
return startCmdChar;
}
/**
* Goes through the command list and runs it if it exists.
* @param e The message received event from JDA.
*/
public static void runCmd(MessageReceivedEvent e) {
// IF it doesn't start with the startcmdchar, ignore for optimization
if (!e.getMessage().getContentRaw().matches("^("+startCmdChar+").*$"))
return;
// Go through all cmds and call the one corresponding
for (Command cmd : CommandsManager.getCommandList()) {
if (isACommand(e.getMessage().getContentRaw(), cmd.cmdName)) {
cmd.call(e);
return;
}
}
}
/**
* Returns if a message is a valid command.
* @param message The original raw message to test.
* @param cmd A specific command to check.
* @return A boolean if the command is valid.
*/
public static boolean isACommand(String message, String cmd) {
return message.matches("^("+ startCmdChar +")("+ cmd +")( .*|)$");
}
}

View File

@@ -0,0 +1,14 @@
package fr.Skydust.JdrBot.bases.CommandManager;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class CommandsManagerListener extends ListenerAdapter {
@Override
public void onMessageReceived(MessageReceivedEvent e) {
if (e.getMessage().getAuthor().isBot())
return;
CommandsManager.runCmd(e);
}
}

View File

@@ -1,6 +1,6 @@
package fr.Skydust.JdrBot.cmds; package fr.Skydust.JdrBot.cmds;
import fr.Skydust.JdrBot.JdrBot; import fr.Skydust.JdrBot.bases.CommandManager.CommandsManager;
import fr.Skydust.JdrBot.bases.command.Command; import fr.Skydust.JdrBot.bases.command.Command;
import fr.Skydust.JdrBot.bases.command.CommandSpec; import fr.Skydust.JdrBot.bases.command.CommandSpec;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
@@ -12,7 +12,7 @@ import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
@CommandSpec( @CommandSpec(
name = "aide", name = "aide|help",
description = "Pour avoir de l'aide !" description = "Pour avoir de l'aide !"
) )
public class Aide extends Command { public class Aide extends Command {
@@ -20,14 +20,17 @@ public class Aide extends Command {
public void call(MessageReceivedEvent e) { public void call(MessageReceivedEvent e) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (int i = 0; i < JdrBot.commandList.size(); i++) for (int currentCommandCount = 0; currentCommandCount < CommandsManager.getCommandList().size(); currentCommandCount++)
{ {
Command cmd = JdrBot.commandList.get(i); Command cmd = CommandsManager.getCommandList().get(currentCommandCount);
if(!cmd.hidden) { if(!cmd.hidden) {
sb.append("`"+cmd.cmdName sb.append("`")
+ ((cmd.cmdUsage.isEmpty()) ? "" : " "+cmd.cmdUsage) .append(cmd.cmdName)
+"` - *"+cmd.cmdDesc+"*" .append((cmd.cmdUsage.isEmpty()) ? "" : " " + cmd.cmdUsage)
+ ((i != JdrBot.commandList.size()-1) ? "\n" : "")); .append("` - *")
.append(cmd.cmdDesc)
.append("*")
.append((currentCommandCount != CommandsManager.getCommandList().size() - 1) ? "\n" : "");
} }
} }