* Added an argument parsing system

* Added an heartbeat argument that send a command every 60 seconds if it's online
This commit is contained in:
2022-03-03 19:08:26 +01:00
parent f318614e96
commit baa0a7f47a
9 changed files with 110 additions and 51 deletions

View File

@@ -26,5 +26,10 @@
<option name="name" value="maven" /> <option name="name" value="maven" />
<option name="url" value="https://m2.dv8tion.net/releases" /> <option name="url" value="https://m2.dv8tion.net/releases" />
</remote-repository> </remote-repository>
<remote-repository>
<option name="id" value="maven2" />
<option name="name" value="maven2" />
<option name="url" value="https://jitpack.io" />
</remote-repository>
</component> </component>
</project> </project>

View File

@@ -23,24 +23,25 @@ repositories {
maven { maven {
url 'https://m2.dv8tion.net/releases' url 'https://m2.dv8tion.net/releases'
} }
maven {
url 'https://jitpack.io'
}
} }
dependencies { dependencies {
// This dependency is used by the application.// // This dependency is used by the application.//
implementation 'com.google.guava:guava:28.0-jre' implementation 'com.google.guava:guava:31.0.1-jre'
//implementation 'org.slf4j:slf4j-log4j12:2.0.0-alpha0' //implementation 'org.slf4j:slf4j-log4j12:2.0.0-alpha0'
implementation 'org.slf4j:slf4j-simple:2.0.0-alpha0' implementation 'org.slf4j:slf4j-simple:2.0.0-alpha0'
implementation 'net.lingala.zip4j:zip4j:2.5.2' implementation 'net.lingala.zip4j:zip4j:2.9.1'
implementation 'club.minnced:opus-java:1.0.4' implementation 'club.minnced:opus-java:1.1.1'
implementation 'ws.schild:jave-all-deps:2.7.3' implementation 'ws.schild:jave-all-deps:3.1.1'
implementation 'org.apache.commons:commons-lang3:3.0' implementation 'org.apache.commons:commons-lang3:3.12.0'
implementation 'com.sedmelluq:lavaplayer:1.3.75' implementation 'com.sedmelluq:lavaplayer:1.3.78'
implementation 'net.dv8tion:JDA:4.2.1_253' implementation 'com.github.DV8FromTheWorld:JDA:4.4.0'
// Use JUnit test framework
testImplementation 'junit:junit:4.12'
} }
application { application {
@@ -50,6 +51,6 @@ application {
jar { jar {
manifest { manifest {
attributes('Manifest-Version': '1.0', 'Main-Class': 'fr.Skydust.JdrBot.JdrBot'); attributes 'Main-Class': 'fr.Skydust.JdrBot.JdrBot'
} }
} }

View File

@@ -2,7 +2,9 @@ package fr.Skydust.JdrBot;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Timer;
import javax.security.auth.login.LoginException; import javax.security.auth.login.LoginException;
import fr.Skydust.JdrBot.cmds.*; import fr.Skydust.JdrBot.cmds.*;
@@ -11,6 +13,7 @@ import fr.Skydust.JdrBot.cmds.record.CancelRecord;
import fr.Skydust.JdrBot.cmds.record.Record; import fr.Skydust.JdrBot.cmds.record.Record;
import fr.Skydust.JdrBot.cmds.record.StopRecord; import fr.Skydust.JdrBot.cmds.record.StopRecord;
import fr.Skydust.JdrBot.stock.Command; import fr.Skydust.JdrBot.stock.Command;
import fr.Skydust.JdrBot.utils.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;
@@ -26,14 +29,32 @@ public class JdrBot {
public static String startcmdchar = "!|:"; public static String startcmdchar = "!|:";
public static void main(String args[]) { public static void main(String args[]) {
for (int i=0;i<args.length;i++) {
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 = String.join("", Arrays.copyOfRange(args,i+1,args.length));
if(command.startsWith("\"")) command = command.split("\"")[1]; // If the command is in "", remove them
new Timer().scheduleAtFixedRate(new HeartbeatTask(command),1000, 60000);
System.out.println("Registered Heartbeat Command: "+command);
}
}
try { try {
basedate = LocalDateTime.now(); basedate = LocalDateTime.now();
/*jda = JDABuilder.createDefault("MTY5OTMzMzgxMDMzOTE4NDY0.DerlJg.m7BdNv_OMHlYa-f4T3O0jJ9LldM")
.setActivity(Activity.playing("un jeu de rôle"))
.enableCache(CacheFlag.VOICE_STATE).build();
*/
jda = JDABuilder.createDefault("ODk0ODc0Nzk5Nzg3MTE0NTA2.YVwXGg.JfIsIIQHIXbVsjoGGv2SfejnT9s") // Prod Bot
//String token = "MTY5OTMzMzgxMDMzOTE4NDY0.DerlJg.m7BdNv_OMHlYa-f4T3O0jJ9LldM";
// Test Bot
String token = "ODk0ODc0Nzk5Nzg3MTE0NTA2.YVwXGg.JfIsIIQHIXbVsjoGGv2SfejnT9s";
jda = JDABuilder.createDefault(token)
.setActivity(Activity.playing("un jeu de rôle")) .setActivity(Activity.playing("un jeu de rôle"))
.enableCache(CacheFlag.VOICE_STATE).build(); .enableCache(CacheFlag.VOICE_STATE).build();

View File

@@ -6,6 +6,8 @@ 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.stock.Command; import fr.Skydust.JdrBot.stock.Command;
import fr.Skydust.JdrBot.utils.HeartbeatTask;
import net.dv8tion.jda.api.events.GatewayPingEvent;
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceLeaveEvent; import net.dv8tion.jda.api.events.guild.voice.GuildVoiceLeaveEvent;
import net.dv8tion.jda.api.events.guild.voice.GuildVoiceMoveEvent; import net.dv8tion.jda.api.events.guild.voice.GuildVoiceMoveEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
@@ -14,8 +16,6 @@ import net.dv8tion.jda.api.events.user.update.UserUpdateOnlineStatusEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class JdrBotListener extends ListenerAdapter { public class JdrBotListener extends ListenerAdapter {
Random r = new Random();
@Override @Override
public void onGuildMessageReceived(GuildMessageReceivedEvent e) { public void onGuildMessageReceived(GuildMessageReceivedEvent e) {
// IF it doesn't start with the startcmdchar, ignore for optimization // IF it doesn't start with the startcmdchar, ignore for optimization
@@ -36,10 +36,12 @@ public class JdrBotListener extends ListenerAdapter {
} }
} }
/* LastTimeOnline listener */
@Override @Override
public void onUserUpdateOnlineStatus(UserUpdateOnlineStatusEvent e) { public void onUserUpdateOnlineStatus(UserUpdateOnlineStatusEvent e) {
LastTimeOnline.onUserUpdateOnlineStatus(e); LastTimeOnline.onUserUpdateOnlineStatus(e);
} }
/* Empty voice channel listener */
@Override @Override
public void onGuildVoiceMove(GuildVoiceMoveEvent e) { public void onGuildVoiceMove(GuildVoiceMoveEvent e) {
StopMusic.onGuildVoiceMove(e); StopMusic.onGuildVoiceMove(e);
@@ -48,8 +50,12 @@ public class JdrBotListener extends ListenerAdapter {
public void onGuildVoiceLeave(GuildVoiceLeaveEvent e) { public void onGuildVoiceLeave(GuildVoiceLeaveEvent e) {
StopMusic.onGuildVoiceLeave(e); StopMusic.onGuildVoiceLeave(e);
} }
/* Menu system listener */
@Override @Override
public void onMessageReactionAdd(MessageReactionAddEvent e) { MenuSystem.onMessageReactionAdd(e); } public void onMessageReactionAdd(MessageReactionAddEvent e) { MenuSystem.onMessageReactionAdd(e); }
/* Heartbeat command listener */
@Override
public void onGatewayPing(GatewayPingEvent e) { HeartbeatTask.HeartbeatUpdateEvent(e); }
public boolean isACommand(String message, String cmd) { public boolean isACommand(String message, String cmd) {
return message.matches("^("+ JdrBot.startcmdchar +")("+ cmd +")( .*|)$"); return message.matches("^("+ JdrBot.startcmdchar +")("+ cmd +")( .*|)$");

View File

@@ -52,11 +52,13 @@ public class PlayMusic extends Command {
return; return;
} }
//TODO: WHILE LOADING, CAN CALL AGAIN // Create a new JukeboxSystem for the guild
JukeboxSystem jukeboxSystem = new JukeboxSystem();
jukeboxSystems.put(e.getGuild().getIdLong(), jukeboxSystem);
// Creates a message to be edited by the jukebox system // Creates a message to be edited by the jukebox system
e.getGuild().getAudioManager().openAudioConnection(e.getMember().getVoiceState().getChannel()); e.getGuild().getAudioManager().openAudioConnection(e.getMember().getVoiceState().getChannel());
e.getChannel().sendMessage("Chargement...").queue(msg -> jukeboxSystems.put(e.getGuild().getIdLong(), new JukeboxSystem(msg))); e.getChannel().sendMessage("Chargement...").queue(jukeboxSystem::load);
} }
public static JukeboxSystem getGuildsJukebox(Guild guild) { public static JukeboxSystem getGuildsJukebox(Guild guild) {

View File

@@ -25,13 +25,13 @@ public class StopMusic extends Command {
} }
public static void onGuildVoiceLeave(GuildVoiceLeaveEvent e) { public static void onGuildVoiceLeave(GuildVoiceLeaveEvent e) {
if(e.getGuild().getAudioManager().isConnected() && e.getChannelLeft().getName().equals(e.getGuild().getAudioManager().getConnectedChannel().getName()) && e.getChannelLeft().getMembers().size() == 1) { if(e.getGuild().getAudioManager().isConnected() && e.getChannelLeft().getIdLong() == e.getGuild().getAudioManager().getConnectedChannel().getIdLong() && e.getChannelLeft().getMembers().size() == 1) {
stopMusic(e.getGuild()); stopMusic(e.getGuild());
} }
} }
public static void onGuildVoiceMove(GuildVoiceMoveEvent e) { public static void onGuildVoiceMove(GuildVoiceMoveEvent e) {
if(e.getGuild().getAudioManager().isConnected() && e.getChannelLeft().getName().equals(e.getGuild().getAudioManager().getConnectedChannel().getName()) && e.getChannelLeft().getMembers().size() == 1) { if(e.getGuild().getAudioManager().isConnected() && e.getChannelLeft().getIdLong() == e.getGuild().getAudioManager().getConnectedChannel().getIdLong() && e.getChannelLeft().getMembers().size() == 1) {
stopMusic(e.getGuild()); stopMusic(e.getGuild());
} }
} }
@@ -39,15 +39,18 @@ public class StopMusic extends Command {
public static void stopMusic(Guild g) { public static void stopMusic(Guild g) {
JukeboxSystem jukebox = PlayMusic.getGuildsJukebox(g); JukeboxSystem jukebox = PlayMusic.getGuildsJukebox(g);
// Deletes the jukebox message
if(jukebox != null) { if(jukebox != null) {
System.out.println("JukeboxMessageIDStop:"+jukebox.jukeboxMessage.getId());
jukebox.jukeboxMessage.delete().queue(); jukebox.jukeboxMessage.delete().queue();
} }
// Clears the guild's jukebox system
PlayMusic.jukeboxSystems.put(g.getIdLong(), null); PlayMusic.jukeboxSystems.put(g.getIdLong(), null);
// Stops the audio
PlayMusic.getGuildAudioPlayer(g).scheduler.stop(); PlayMusic.getGuildAudioPlayer(g).scheduler.stop();
// Leave the voice channel if not recording
if(!Record.getGuildRecordState(g).isRecording) { if(!Record.getGuildRecordState(g).isRecording) {
g.getAudioManager().closeAudioConnection(); g.getAudioManager().closeAudioConnection();
} }

View File

@@ -1,7 +1,6 @@
package fr.Skydust.JdrBot.jukebox; package fr.Skydust.JdrBot.jukebox;
import fr.Skydust.JdrBot.cmds.playmusic.PlayMusic; import fr.Skydust.JdrBot.cmds.playmusic.PlayMusic;
import fr.Skydust.JdrBot.cmds.playmusic.StopMusic;
import fr.Skydust.JdrBot.menu.Menu; import fr.Skydust.JdrBot.menu.Menu;
import fr.Skydust.JdrBot.menu.MenuSystem; import fr.Skydust.JdrBot.menu.MenuSystem;
import fr.Skydust.JdrBot.utils.Utils; import fr.Skydust.JdrBot.utils.Utils;
@@ -14,7 +13,7 @@ import java.util.*;
public class JukeboxSystem { public class JukeboxSystem {
// Const // Const
public static final String initialFolder = "Songs"; public static final String initialFolder = "Songs";
public static final String musicPlayerThumbnail = "https://cdn4.iconfinder.com/data/icons/miu/24/device-volume-loudspeaker-speaker-up-glyph-128.png"; public static final String musicPlayerThumbnail = "https://cd4.iconfinder.com/data/icons/miu/24/device-volume-loudspeaker-speaker-up-glyph-128.png";
// Dyn // Dyn
// Keeping track of the song currently played to update menus accordingly // Keeping track of the song currently played to update menus accordingly
@@ -22,11 +21,11 @@ public class JukeboxSystem {
public String songPlayedPath = ""; public String songPlayedPath = "";
private final HashMap<String, Menu> linkedPath = new HashMap<>(); private final HashMap<String, Menu> linkedPath = new HashMap<>();
public final Message jukeboxMessage; public Message jukeboxMessage;
private String currentFolder = ""; private String currentFolder = "";
public JukeboxSystem(Message msg) { public void load(Message msg) {
jukeboxMessage = msg; jukeboxMessage = msg;
openFolder(initialFolder); openFolder(initialFolder);
} }
@@ -42,7 +41,7 @@ public class JukeboxSystem {
File[] files = new File(currentFolder).listFiles(); File[] files = new File(currentFolder).listFiles();
// If it isn't the root folder, place the return button // If it isn't the root folder, place the return button
if(!isInRootFolder()) { if(isntInRootFolder()) {
items.add(Utils.ReturnUnicode + " Retour"); items.add(Utils.ReturnUnicode + " Retour");
} }
if(files != null) { if(files != null) {
@@ -87,7 +86,7 @@ public class JukeboxSystem {
} }
// Return button // Return button
if (!isInRootFolder() && itemId == 0) { if (isntInRootFolder() && itemId == 0) {
// Back one menu // Back one menu
String subFolder = currentFolder.substring(0, currentFolder.lastIndexOf("/")); String subFolder = currentFolder.substring(0, currentFolder.lastIndexOf("/"));
currentFolder = subFolder; currentFolder = subFolder;
@@ -129,11 +128,10 @@ public class JukeboxSystem {
jukeboxMessage.getTextChannel().retrieveMessageById(jukeboxMessage.getIdLong()).queue(msg -> { jukeboxMessage.getTextChannel().retrieveMessageById(jukeboxMessage.getIdLong()).queue(msg -> {
MenuSystem.changeMenu(msg, finalMenu); MenuSystem.changeMenu(msg, finalMenu);
}); });
} }
public boolean isInRootFolder() { public boolean isntInRootFolder() {
return currentFolder.equals(initialFolder); return !currentFolder.equals(initialFolder);
} }
public static String getFileNameFromItem(String item) { public static String getFileNameFromItem(String item) {
@@ -141,21 +139,8 @@ public class JukeboxSystem {
} }
private final Comparator<File> sortItemsComp = (o1, o2) -> { private final Comparator<File> sortItemsComp = (o1, o2) -> {
if (o1.isDirectory() && !o2.isDirectory()) if (o1.isDirectory() && !o2.isDirectory()) return -1; // Directory before non-directory
{ else if (!o1.isDirectory() && o2.isDirectory()) return 1; // Non-directory after directory
// Directory before non-directory else return o1.compareTo(o2); // Alphabetic order otherwise
return -1;
}
else if (!o1.isDirectory() && o2.isDirectory())
{
// Non-directory after directory
return 1;
}
else
{
// Alphabetic order otherwise
//return o1.compareTo(o2);
return o1.compareTo(o2);
}
}; };
} }

View File

@@ -14,10 +14,10 @@ import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.CompressionLevel; import net.lingala.zip4j.model.enums.CompressionLevel;
import net.lingala.zip4j.model.enums.CompressionMethod; import net.lingala.zip4j.model.enums.CompressionMethod;
import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.EncoderException;
import ws.schild.jave.AudioAttributes;
import ws.schild.jave.Encoder; import ws.schild.jave.Encoder;
import ws.schild.jave.EncodingAttributes;
import ws.schild.jave.MultimediaObject; import ws.schild.jave.MultimediaObject;
import ws.schild.jave.encode.AudioAttributes;
import ws.schild.jave.encode.EncodingAttributes;
import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioFormat;
@@ -106,7 +106,7 @@ public class RecordState {
audio.setChannels(2); audio.setChannels(2);
EncodingAttributes ea = new EncodingAttributes(); EncodingAttributes ea = new EncodingAttributes();
ea.setAudioAttributes(audio); ea.setAudioAttributes(audio);
ea.setFormat("mp3"); ea.setOutputFormat("mp3");
encoder.encode(new MultimediaObject(wavFile),mp3File,ea); encoder.encode(new MultimediaObject(wavFile),mp3File,ea);
wavFile.delete(); wavFile.delete();

View File

@@ -0,0 +1,36 @@
package fr.Skydust.JdrBot.utils;
import fr.Skydust.JdrBot.JdrBot;
import net.dv8tion.jda.api.events.GatewayPingEvent;
import java.util.TimerTask;
public class HeartbeatTask extends TimerTask {
private String command = "";
private static boolean heartbeatUpdated = false;
public HeartbeatTask(String command) {
this.command = command;
}
@Override
public void run() {
if(heartbeatUpdated) {
long ping = JdrBot.jda.getGatewayPing();
try {
Runtime.getRuntime().exec(command.replaceAll("\\{ping\\}", String.valueOf(ping)));
} catch (Exception e) {
System.out.println("Error: "+e.getMessage());
}
System.out.println("Sent heartbeat "+ ping);
heartbeatUpdated = false;
}
}
public static void HeartbeatUpdateEvent(GatewayPingEvent e) {
heartbeatUpdated = true;
}
}