Changed settings class into a singleton and improved logging

This commit is contained in:
anthorob committed 2021-09-10 19:57:59 -04:00
1 parent 967856ce57
commit a7d4c7d711
16 files changed
+75 -51

No files matched your search

+7 -9
View File
@@ -22,20 +22,18 @@ import javax.security.auth.login.LoginException;
public class MusicBot { public class MusicBot {
private static JDA jda; private static JDA jda;
public static Logger LOGGER = LoggerFactory.getLogger(MusicBot.class); private final static Logger logger = LoggerFactory.getLogger(MusicBot.class);
public static void main(String[] args) { public static void main(String[] args) {
System.setProperty("log4j.skipJansi", "false"); System.setProperty("log4j.skipJansi", "false");
Settings.init();
DBController.init(); DBController.init();
try { try {
jda = JDABuilder.createDefault(Settings.TOKEN).build(); jda = JDABuilder.createDefault(Settings.getInstance().getToken()).build();
jda.awaitReady(); jda.awaitReady();
} catch (LoginException | IllegalArgumentException e) { } catch (LoginException | IllegalArgumentException | InterruptedException e) {
LogHandler.log(e); logger.error(e.getMessage());
} catch (InterruptedException e) { shutdown();
LOGGER.error(e.getMessage());
} }
@@ -59,12 +57,12 @@ public class MusicBot {
} }
public static void shutdown() { public static void shutdown() {
LOGGER.info("[Net Neutrality] Shutting down..."); logger.info("[Net Neutrality] Shutting down...");
MusicManager.disconnectPlayers(); MusicManager.disconnectPlayers();
ThreadManager.shutdownExecutor(); ThreadManager.shutdownExecutor();
disconnect(); disconnect();
DBController.shutdown(); DBController.shutdown();
LOGGER.info("[Net Neutrality] Shutdown complete"); logger.info("[Net Neutrality] Shutdown complete");
System.exit(0); System.exit(0);
} }
@@ -6,6 +6,9 @@ package netneutrality;
* This file is closed-source. It should not be distributed or copied in any way or form * This file is closed-source. It should not be distributed or copied in any way or form
*/ */
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
@@ -13,11 +16,12 @@ import java.util.concurrent.TimeUnit;
public class ThreadManager { public class ThreadManager {
private final static Logger logger = LoggerFactory.getLogger(ThreadManager.class);
public static final ExecutorService executor = Executors.newSingleThreadExecutor(); public static final ExecutorService executor = Executors.newSingleThreadExecutor();
public static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2); public static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
public static void shutdownExecutor() { public static void shutdownExecutor() {
MusicBot.LOGGER.info("[Executor] Shutting down..."); logger.info("[Executor] Shutting down...");
try { try {
executor.shutdown(); executor.shutdown();
@@ -26,22 +30,22 @@ public class ThreadManager {
scheduler.awaitTermination(5, TimeUnit.SECONDS); scheduler.awaitTermination(5, TimeUnit.SECONDS);
} }
catch (InterruptedException e) { catch (InterruptedException e) {
MusicBot.LOGGER.warn("[Executor] Running tasks interrupted"); logger.warn("[Executor] Running tasks interrupted");
} }
finally { finally {
if (!executor.isTerminated()) { if (!executor.isTerminated()) {
MusicBot.LOGGER.warn("[Executor] Forcing shutdown of running tasks.."); logger.warn("[Executor] Forcing shutdown of running tasks..");
executor.shutdownNow(); executor.shutdownNow();
} }
if (!scheduler.isTerminated()) { if (!scheduler.isTerminated()) {
MusicBot.LOGGER.warn("[Executor] Forcing shutdown of running tasks.."); logger.warn("[Executor] Forcing shutdown of running tasks..");
scheduler.shutdownNow(); scheduler.shutdownNow();
} }
} }
MusicBot.LOGGER.info("[Executor] Shutdown finished!"); logger.info("[Executor] Shutdown finished!");
} }
@@ -9,6 +9,8 @@ package netneutrality.command;
import netneutrality.MusicBot; import netneutrality.MusicBot;
import org.reflections.Reflections; import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
@@ -17,6 +19,7 @@ import java.util.Set;
public class CommandManager { public class CommandManager {
private final static Logger logger = LoggerFactory.getLogger(CommandManager.class);
public static HashMap<String, AbstractCommand> commands = new HashMap<>(); public static HashMap<String, AbstractCommand> commands = new HashMap<>();
public static HashMap<String, AbstractCommand> commandsAlias = new HashMap<>(); public static HashMap<String, AbstractCommand> commandsAlias = new HashMap<>();
@@ -26,7 +29,7 @@ public class CommandManager {
} }
private static void initCommands() { private static void initCommands() {
MusicBot.LOGGER.info("Loading commands.."); logger.info("Loading commands..");
Reflections reflections = new Reflections("netneutrality.command"); Reflections reflections = new Reflections("netneutrality.command");
Set<Class<? extends AbstractCommand>> classes = reflections.getSubTypesOf(AbstractCommand.class); Set<Class<? extends AbstractCommand>> classes = reflections.getSubTypesOf(AbstractCommand.class);
@@ -51,7 +54,7 @@ public class CommandManager {
} }
} }
MusicBot.LOGGER.info("Loaded " + commands.size() + " commands!"); logger.info("Loaded " + commands.size() + " commands!");
} }
private static void initAlias() { private static void initAlias() {
@@ -73,7 +73,7 @@ public class HelpCommand extends AbstractCommand {
AbstractCommand command = commands.get(key); AbstractCommand command = commands.get(key);
if (command.isEnabled()) { if (command.isEnabled()) {
help.append(Settings.PREFIX).append(command.getCommand()); help.append(Settings.getInstance().getPrefix()).append(command.getCommand());
if (command.getUsage() != null) if (command.getUsage() != null)
help.append(" ").append(command.getUsage()); help.append(" ").append(command.getUsage());
@@ -59,7 +59,7 @@ public class DatabaseCommand extends AbstractCommand {
//TODO: Clean up the mess //TODO: Clean up the mess
event.getMessage().delete().queue(); event.getMessage().delete().queue();
if (!event.getAuthor().getDiscriminator().equals(Settings.getCreator().getDiscriminator())) if (!event.getAuthor().getDiscriminator().equals(Settings.getInstance().getCreator().getDiscriminator()))
return null; return null;
if (countArgs(args) > 0) { if (countArgs(args) > 0) {
@@ -74,7 +74,7 @@ public class DatabaseCommand extends AbstractCommand {
EmbedBuilder embed = new EmbedBuilder(); EmbedBuilder embed = new EmbedBuilder();
embed.setColor(Color.BLUE); embed.setColor(Color.BLUE);
embed.setTimestamp( embed.setTimestamp(
DateTimeFormatter.ofPattern(Settings.DATETIMEFORMAT).parse(message.getDateSent())); DateTimeFormatter.ofPattern(Settings.getInstance().DATETIMEFORMAT).parse(message.getDateSent()));
embed.setFooter("Guild : " + message.getServerName() + " | ID : " + message.getMessageId(), null); embed.setFooter("Guild : " + message.getServerName() + " | ID : " + message.getMessageId(), null);
embed.setDescription( embed.setDescription(
"Message from " + message.getSender() + " on the channel " + message.getChannelName()); "Message from " + message.getSender() + " on the channel " + message.getChannelName());
@@ -56,7 +56,7 @@ public class EvalMethod extends AbstractCommand {
@Override @Override
public String execute(MessageReceivedEvent event, String args) { public String execute(MessageReceivedEvent event, String args) {
if (event.getAuthor().getId().equals(Settings.getCreator().getId())) { if (event.getAuthor().getId().equals(Settings.getInstance().getCreator().getId())) {
ScriptEngine se = new ScriptEngineManager().getEngineByName("Nashorn"); ScriptEngine se = new ScriptEngineManager().getEngineByName("Nashorn");
try { try {
se.eval("var imports = new JavaImporter(java.io, java.lang, java.util);"); se.eval("var imports = new JavaImporter(java.io, java.lang, java.util);");
@@ -55,7 +55,7 @@ public class TestCommand extends AbstractCommand {
@Override @Override
public String execute(MessageReceivedEvent event, String args) { public String execute(MessageReceivedEvent event, String args) {
if (event.getAuthor().getDiscriminator().equals(Settings.getCreator().getDiscriminator())) { if (event.getAuthor().getDiscriminator().equals(Settings.getInstance().getCreator().getDiscriminator())) {
MessageFunction.isStartingWithMention(event.getMessage()); MessageFunction.isStartingWithMention(event.getMessage());
} }
@@ -38,7 +38,7 @@ public class DBMessage extends AbstractController {
String servername = guild.getName(); String servername = guild.getName();
String channelname = channel.getName(); String channelname = channel.getName();
String username = author.getName(); String username = author.getName();
String datesent = message.getTimeCreated().format(DateTimeFormatter.ofPattern(Settings.DATETIMEFORMAT)); String datesent = message.getTimeCreated().format(DateTimeFormatter.ofPattern(Settings.getInstance().DATETIMEFORMAT));
String messageid = message.getId(); String messageid = message.getId();
String msg = message.getContentRaw().trim(); String msg = message.getContentRaw().trim();
@@ -1,6 +1,7 @@
package netneutrality.handler; package netneutrality.handler;
import netneutrality.MusicBot; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
@@ -8,9 +9,9 @@ import java.io.InputStreamReader;
public class ConsoleHandler { public class ConsoleHandler {
private final static Logger logger = LoggerFactory.getLogger(ConsoleHandler.class);
public ConsoleHandler() { public ConsoleHandler() {
MusicBot.LOGGER.info("Console input ready!"); logger.info("Console input ready!");
} }
public String init() { public String init() {
@@ -2,9 +2,13 @@ package netneutrality.handler;
import netneutrality.MusicBot; import netneutrality.MusicBot;
import netneutrality.utils.Settings; import netneutrality.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogHandler { public class LogHandler {
private final static Logger logger = LoggerFactory.getLogger(LogHandler.class);
/** /**
* Log the exception to the owner's log TextChannel as defined in {@link Settings#getLogChannel()} * Log the exception to the owner's log TextChannel as defined in {@link Settings#getLogChannel()}
* *
@@ -12,8 +16,10 @@ public class LogHandler {
*/ */
public static void log(Exception e) { public static void log(Exception e) {
MusicBot.LOGGER.error(e.getMessage()); logger.error(e.getMessage());
Settings.getLogChannel().sendMessage("Error : " + e).queue();
//TODO: to remove or add check if jda is started
Settings.getInstance().getLogChannel().sendMessage("Error : " + e).queue();
} }
} }
@@ -37,7 +37,7 @@ public class NewCommandListener extends ListenerAdapter {
Message message = event.getMessage(); Message message = event.getMessage();
String msg = message.getContentDisplay().trim(); String msg = message.getContentDisplay().trim();
if (msg.startsWith(Settings.PREFIX)) { if (msg.startsWith(Settings.getInstance().getPrefix())) {
msg = msg.substring(1); msg = msg.substring(1);
String cmd = msg.split(" ", 2)[0]; String cmd = msg.split(" ", 2)[0];
@@ -7,18 +7,21 @@ package netneutrality.http.server;
*/ */
import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpServer;
import netneutrality.MusicBot; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
public class WebApi { public class WebApi {
private final static Logger logger = LoggerFactory.getLogger(WebApi.class);
private int port = 9000; private int port = 9000;
private HttpServer server; private HttpServer server;
public WebApi() { public WebApi() {
MusicBot.LOGGER.debug("Starting web server..."); logger.debug("Starting web server...");
try { try {
server = HttpServer.create(new InetSocketAddress(port), 0); server = HttpServer.create(new InetSocketAddress(port), 0);
} catch (IOException e) { } catch (IOException e) {
@@ -28,7 +31,7 @@ public class WebApi {
server.createContext("/guild", new GuildBrowser()); server.createContext("/guild", new GuildBrowser());
server.setExecutor(null); server.setExecutor(null);
server.start(); server.start();
MusicBot.LOGGER.debug("Web server started at [" + server.getAddress().getAddress().toString() + "]"); logger.debug("Web server started at [" + server.getAddress().getAddress().toString() + "]");
} }
@@ -75,7 +75,7 @@ public class MusicManager {
leave(); leave();
}, 10, 10, TimeUnit.SECONDS); }, 10, 10, TimeUnit.SECONDS);
} else } else
MusicBot.LOGGER.error("Error connecting!"); logger.error("Error connecting!");
} }
public boolean isConnected() { public boolean isConnected() {
+22 -13
View File
@@ -12,33 +12,42 @@ import java.util.Properties;
public class Settings { public class Settings {
static Properties prop = new Properties(); public static Settings INSTANCE;
static String configFile = "bot.config"; private Properties prop = new Properties();
public static void init() { public Settings() {
String configFile = "bot.config";
InputStream is = Settings.class.getClassLoader().getResourceAsStream(configFile); InputStream is = Settings.class.getClassLoader().getResourceAsStream(configFile);
try (FileInputStream fis = new FileInputStream(configFile)) { try {
prop.load(fis); prop.load(is);
} catch (IOException ignored) { } catch (IOException e) {
e.printStackTrace();
} }
} }
public static final String DATETIMEFORMAT = "yyyy-MM-dd HH:mm:ss"; public static Settings getInstance() {
public static String PREFIX = prop.getProperty("bot.prefix"); if(INSTANCE == null) {
public static final String TOKEN = prop.getProperty("bot.token"); INSTANCE = new Settings();
}
public static User getCreator() { return INSTANCE;
}
public final String DATETIMEFORMAT = "yyyy-MM-dd HH:mm:ss";
public String getPrefix() { return prop.getProperty("bot.prefix"); }
public String getToken() { return prop.getProperty("bot.token"); }
public User getCreator() {
return MusicBot.getJDA().getUserById(prop.getProperty("bot.owner")); return MusicBot.getJDA().getUserById(prop.getProperty("bot.owner"));
} }
public static Guild getOwnerGuild() { public Guild getOwnerGuild() {
return MusicBot.getJDA().getGuildById(prop.getProperty("bot.ownerguild")); return MusicBot.getJDA().getGuildById(prop.getProperty("bot.ownerguild"));
} }
public static TextChannel getLogChannel() { public TextChannel getLogChannel() {
return MusicBot.getJDA().getTextChannelById(prop.getProperty("bot.errorchannel")); return MusicBot.getJDA().getTextChannelById(prop.getProperty("bot.errorchannel"));
} }
@@ -9,7 +9,7 @@ public class UserFunction {
public static boolean isAdmin(Member user) { public static boolean isAdmin(Member user) {
// This check will only be present during the development of the bot // This check will only be present during the development of the bot
if (user.getUser().getId().equals(Settings.getCreator().getId())) { if (user.getUser().getId().equals(Settings.getInstance().getCreator().getId())) {
return true; return true;
} }
+5 -5
View File
@@ -1,5 +1,5 @@
bot.token="" bot.token=
bot.prefix="$" bot.prefix=$
bot.owner="" bot.owner=
bot.ownerguild="" bot.ownerguild=
bot.errorchannel="" bot.errorchannel=