diff --git a/.classpath b/.classpath index 26bbf1c..3a153ed 100644 --- a/.classpath +++ b/.classpath @@ -1,17 +1,13 @@ - - - - - - + + diff --git a/TODO.txt b/TODO.txt index b8ca799..b040f1f 100644 --- a/TODO.txt +++ b/TODO.txt @@ -2,4 +2,9 @@ finish loop // DONE add socket server for better management / integration // DONE implement pheonix in a smarter way than last time -add better security to the socket server \ No newline at end of file +add better security to the socket server +add argument alias usage support +add on join actions and configs +// DONE clean up database accessor for a more modular setup + + diff --git a/src/pkg/deepCurse/nopalmo/command/CommandInterface.java b/src/pkg/deepCurse/nopalmo/command/CommandInterface.java index f273709..2a57b91 100644 --- a/src/pkg/deepCurse/nopalmo/command/CommandInterface.java +++ b/src/pkg/deepCurse/nopalmo/command/CommandInterface.java @@ -5,7 +5,7 @@ import java.util.HashMap; import org.jetbrains.annotations.Nullable; import net.dv8tion.jda.api.Permission; -import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Global; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.GlobalDB; import pkg.deepCurse.nopalmo.manager.Argument; import pkg.deepCurse.nopalmo.manager.CommandBlob; @@ -61,10 +61,10 @@ public interface CommandInterface { // TODO rewrite to implement type args? } } } - return Global.prefix + getCommandName() + " " + sB.toString().trim(); + return GlobalDB.prefix + getCommandName() + " " + sB.toString().trim(); } - return Global.prefix + getCommandName(); + return GlobalDB.prefix + getCommandName(); } public default int getTimeout() { diff --git a/src/pkg/deepCurse/nopalmo/command/commands/general/Prefix.java b/src/pkg/deepCurse/nopalmo/command/commands/general/Prefix.java index 400840e..05a90ad 100644 --- a/src/pkg/deepCurse/nopalmo/command/commands/general/Prefix.java +++ b/src/pkg/deepCurse/nopalmo/command/commands/general/Prefix.java @@ -3,9 +3,9 @@ package pkg.deepCurse.nopalmo.command.commands.general; import java.util.HashMap; import pkg.deepCurse.nopalmo.command.CommandInterface.GuildCommandInterface; -import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Global; -import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Guild; -import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Users; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.GlobalDB; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.GuildDB; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.UserDB; import pkg.deepCurse.nopalmo.manager.Argument; import pkg.deepCurse.nopalmo.manager.CommandBlob; @@ -25,15 +25,20 @@ public class Prefix implements GuildCommandInterface { public void runGuildCommand(CommandBlob blob, HashMap argumentList) throws Exception { if (argumentList.get("prefix") != null) { - Guild.Prefix.setPrefix(blob.getGuildID(), argumentList.get("prefix").getWildCardString()); + GuildDB.setPrefix(blob.getGuildID(), argumentList.get("prefix").getWildCardString()); blob.getChannel().sendMessage("Set prefix to " + argumentList.get("prefix").getWildCardString()).queue(); - if (!Users.isAdvancedUser(blob.getAuthorID())) + if (!UserDB.isAdvancedUser(blob.getAuthorID())) blob.getChannel() .sendMessage( "Remember: you can always ping me to use any command in case you forget the prefix") .queue(); + +// if () { +// +// } + } else { - Guild.Prefix.setPrefix(blob.getGuildID(), Global.prefix); + GuildDB.setPrefix(blob.getGuildID(), GlobalDB.prefix); blob.getChannel().sendMessage("Reset prefix to default").queue(); } diff --git a/src/pkg/deepCurse/nopalmo/command/commands/info/Help.java b/src/pkg/deepCurse/nopalmo/command/commands/info/Help.java index 4d6cefa..ceb37e3 100644 --- a/src/pkg/deepCurse/nopalmo/command/commands/info/Help.java +++ b/src/pkg/deepCurse/nopalmo/command/commands/info/Help.java @@ -9,7 +9,7 @@ import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.TextChannel; import pkg.deepCurse.nopalmo.command.CommandInterface; import pkg.deepCurse.nopalmo.command.CommandInterface.GuildCommandInterface; -import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Global; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.GlobalDB; import pkg.deepCurse.nopalmo.manager.Argument; import pkg.deepCurse.nopalmo.manager.CommandBlob; import pkg.deepCurse.nopalmo.manager.CommandManager; @@ -33,8 +33,7 @@ public class Help implements GuildCommandInterface { // boolean blob.isDeveloper() = argumentMap.get("dev") != null; if (argumentMap.get("commandName") == null) { - EmbedBuilder embed = new EmbedBuilder().setTitle( - blob.isDeveloper() ? "^Commands:" + blob.isDeveloper() : "Commands:" + blob.isDeveloper()); + EmbedBuilder embed = new EmbedBuilder().setTitle(blob.isDeveloper() ? "^Commands:" : "Commands:"); HashMap> commandHash = new HashMap>(); @@ -127,7 +126,7 @@ public class Help implements GuildCommandInterface { embed.setFooter(blob.getMember().getEffectiveName(), blob.getAuthor().getEffectiveAvatarUrl()); embed.setTimestamp(Instant.now()); - embed.setColor(Global.getEmbedColor()); + embed.setColor(Integer.parseInt(GlobalDB.getGlobalValue("embedcolor"))); blob.getChannel().sendMessageEmbeds(embed.build()).queue(); @@ -141,7 +140,7 @@ public class Help implements GuildCommandInterface { if (!blob.isFromGuild() ? true : !(command.isNSFW() && !((TextChannel) blob.getChannel()).isNSFW())) { EmbedBuilder eB = new EmbedBuilder(); - eB.setColor(Global.getEmbedColor()); + eB.setColor(Integer.parseInt(GlobalDB.getGlobalValue("embedcolor"))); StringBuilder sB = new StringBuilder(); eB.setTitle("Help results for: " + command.getCommandName()); diff --git a/src/pkg/deepCurse/nopalmo/command/commands/info/Info.java b/src/pkg/deepCurse/nopalmo/command/commands/info/Info.java index be52bdd..5071b64 100644 --- a/src/pkg/deepCurse/nopalmo/command/commands/info/Info.java +++ b/src/pkg/deepCurse/nopalmo/command/commands/info/Info.java @@ -6,7 +6,7 @@ import org.jetbrains.annotations.Nullable; import pkg.deepCurse.nopalmo.command.CommandInterface.GuildCommandInterface; import pkg.deepCurse.nopalmo.command.CommandInterface.PrivateCommandInterface; -import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Users; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.UserDB; import pkg.deepCurse.nopalmo.manager.Argument; import pkg.deepCurse.nopalmo.manager.CommandBlob; @@ -32,8 +32,11 @@ public class Info implements GuildCommandInterface, PrivateCommandInterface { HashMap args = new HashMap(); args.put("userdump", new Argument("userdump", (CommandBlob blob) -> { - blob.getChannel().sendMessage(!Users.dump(blob.getAuthorID()).isEmpty() ? Users.dump(blob.getAuthorID()) - : "Sorry, but this user does not exist in the database").queue(); + blob.getChannel() + .sendMessage( + !UserDB.generateDump(blob.getAuthorID()).isEmpty() ? UserDB.generateDump(blob.getAuthorID()) + : "Sorry, but this user does not exist in the database") + .queue(); }).setPrefixRequirement(true).setAutoStartRunnable(true).setSkipOriginalTaskOnRunnable(true).addAliases("u")); return args; diff --git a/src/pkg/deepCurse/nopalmo/command/commands/info/Reload.java b/src/pkg/deepCurse/nopalmo/command/commands/info/Reload.java index 3a24012..45e7574 100644 --- a/src/pkg/deepCurse/nopalmo/command/commands/info/Reload.java +++ b/src/pkg/deepCurse/nopalmo/command/commands/info/Reload.java @@ -5,11 +5,9 @@ import java.util.HashMap; import org.jetbrains.annotations.Nullable; import pkg.deepCurse.nopalmo.command.CommandInterface.DualCommandInterface; -import pkg.deepCurse.nopalmo.global.Reactions; +import pkg.deepCurse.nopalmo.core.Loader; import pkg.deepCurse.nopalmo.manager.Argument; import pkg.deepCurse.nopalmo.manager.CommandBlob; -import pkg.deepCurse.nopalmo.manager.StatusManager; -import pkg.deepCurse.nopalmo.utils.LogHelper; public class Reload implements DualCommandInterface { @@ -35,43 +33,8 @@ public class Reload implements DualCommandInterface { @Override public void runDualCommand(CommandBlob blob, HashMap argumentMap) throws Exception { - StringBuilder sB = new StringBuilder(); - - LogHelper.log("Init reaction/emote list", getClass()); - sB.append("Init reaction/emote list\n"); - try { - Reactions.init(); - LogHelper.log("Initialized reaction/emote list. . .", getClass()); - sB.append("Initialized reaction/emote list. . .\n"); - } catch (Exception e) { - LogHelper.log("Failed to initialize reaction/emote list. . .\n" + e + "\n", getClass()); - sB.append("Failed to initialize reaction/emote list. . .\n" + e + "\n"); - } - - LogHelper.log("Init command list", getClass()); - sB.append("Init command list\n"); - try { - blob.getCommandManager().init(); - LogHelper.log("Initialized command list. . .", getClass()); - sB.append("Initialized command list. . .\n"); - } catch (Exception e) { - LogHelper.log("Failed to initialize command list. . .\n" + e + "\n", getClass()); - sB.append("Failed to initialize command list. . .\n" + e + "\n"); - } - - LogHelper.log("Init status list", getClass()); - sB.append("Init status list\n"); - try { - StatusManager.init(); - LogHelper.log("Initialized status list. . .", getClass()); - sB.append("Initialized status list. . .\n"); - } catch (Exception e) { - LogHelper.log("Failed to initialize status list. . .\n" + e + "\n", getClass()); - sB.append("Failed to initialize status list. . .\n" + e + "\n"); - } - - blob.getChannel().sendMessage(sB.toString()).queue(); +// blob.getChannel().sendMessage("Refreshing caches. . .").queue(); + blob.getChannel().sendMessage(Loader.init()).queue(); } - } diff --git a/src/pkg/deepCurse/nopalmo/command/commands/testing/BontebokInterpret.java b/src/pkg/deepCurse/nopalmo/command/commands/testing/BontebokInterpret.java index 183b2d9..aa90f5d 100644 --- a/src/pkg/deepCurse/nopalmo/command/commands/testing/BontebokInterpret.java +++ b/src/pkg/deepCurse/nopalmo/command/commands/testing/BontebokInterpret.java @@ -1,52 +1,53 @@ -package pkg.deepCurse.nopalmo.command.commands.testing; - -import java.util.HashMap; - -import org.jetbrains.annotations.Nullable; - -import pkg.deepCurse.bontebok.core.BontebokInterpreter; -import pkg.deepCurse.nopalmo.command.CommandInterface.DualCommandInterface; -import pkg.deepCurse.nopalmo.manager.Argument; -import pkg.deepCurse.nopalmo.manager.CommandBlob; - -public class BontebokInterpret implements DualCommandInterface { - - @Override - public String[] getCommandCalls() { - return new String[] { "bontebok", "interpret", "int", "bo" }; - } - - @Override - public HelpPage getHelpPage() { - return HelpPage.TESTING; - } - - @Override - public String getHelp() { - return "This command will interpret a string using the bontebok interpreter"; - } - - @Override - public @Nullable HashMap getArguments() { - return null; - } - - @Override - public void runDualCommand(CommandBlob blob, HashMap argumentMap) throws Exception { - - blob.getChannel().sendMessage("Interpreting. . .").queue(); - - String returnValue = BontebokInterpreter.InterpretString(argumentMap.get("null").getWildCardString(), null); - - switch (returnValue.substring(0, 1)) { +//package pkg.deepCurse.nopalmo.command.commands.testing; +// +//import java.util.HashMap; +// +//import org.jetbrains.annotations.Nullable; +// +//import pkg.deepCurse.nopalmo.command.CommandInterface.DualCommandInterface; +//import pkg.deepCurse.nopalmo.core.Boot; +//import pkg.deepCurse.nopalmo.manager.Argument; +//import pkg.deepCurse.nopalmo.manager.CommandBlob; +// +//public class BontebokInterpret implements DualCommandInterface { +// +// @Override +// public String[] getCommandCalls() { +// return new String[] { "bontebok", "interpret", "int", "bo" }; +// } +// +// @Override +// public HelpPage getHelpPage() { +// return HelpPage.TESTING; +// } +// +// @Override +// public String getHelp() { +// return "This command will interpret a string using the bontebok interpreter"; +// } +// +// @Override +// public @Nullable HashMap getArguments() { +// return null; +// } +// +// @Override +// public void runDualCommand(CommandBlob blob, HashMap argumentMap) throws Exception { +// +// blob.getChannel().sendMessage("Interpreting. . .").queue(); +// +// String returnValue = Boot.bontebokManager.getBontebokInterpreter() +// .InterpretString(argumentMap.get("null").getWildCardString()); +// +// switch (returnValue.substring(0, 1)) { // case "0": // blob.getChannel().sendMessage("Operation completed with return value 0").queue(); // break; - case "1": - blob.getChannel().sendMessage("Operation failed with return value 1" - + (returnValue.substring(1).isBlank() ? "" : ": " + returnValue.substring(1))).queue(); - break; - } - } - -} +// case "1": +// blob.getChannel().sendMessage("Operation failed with return value 1" +// + (returnValue.substring(1).isBlank() ? "" : ": " + returnValue.substring(1))).queue(); +// break; +// } +// } +// +//} diff --git a/src/pkg/deepCurse/nopalmo/command/commands/testing/Purge.java b/src/pkg/deepCurse/nopalmo/command/commands/testing/Purge.java new file mode 100644 index 0000000..7c2aac9 --- /dev/null +++ b/src/pkg/deepCurse/nopalmo/command/commands/testing/Purge.java @@ -0,0 +1,127 @@ +package pkg.deepCurse.nopalmo.command.commands.testing; + +import java.util.HashMap; + +import org.jetbrains.annotations.Nullable; + +import pkg.deepCurse.nopalmo.command.CommandInterface.GuildCommandInterface; +import pkg.deepCurse.nopalmo.manager.Argument; +import pkg.deepCurse.nopalmo.manager.CommandBlob; + +public class Purge implements GuildCommandInterface { + + @Override + public String[] getCommandCalls() { + return new String[] { "p" }; + } + + @Override + public HelpPage getHelpPage() { + return HelpPage.TESTING; + } + + @Override + public String getHelp() { + return "Purges the channel of messages using many useful arguments to control the mode"; + } + + @Override + public @Nullable HashMap getArguments() { + return null; + } + + @Override + public void runGuildCommand(CommandBlob blob, HashMap argumentList) throws Exception { + } + +// @Override +// public void runGuildCommand(CommandBlob blob, HashMap argumentList) throws Exception { +// +// if (args.size() == 1) { +// if (!blob.getMember().hasPermission(Permission.MESSAGE_MANAGE)) { +// blob.getChannel().sendMessage("You don't have the **MESSAGE_MANAGE** permission!").queue(); +// return; +// } +// int num = 0; +// try { +// num = Integer.parseInt(args.get(0)); +// } catch (NumberFormatException nfe) { +// throw new NumberFormatException("Enter a number dumbass"); +// } +// blob.getMessage().delete().complete(); +// int currentNum = num / 100; +// if (currentNum == 0) { +// List msg = event.getChannel().getHistory().retrievePast(num).complete(); +// event.getChannel().purgeMessages(msg); +// // event.getChannel().sendMessage("Successfully purged `" + num + "` +// // messages.").queue(); +// return; +// } +// try { +// for (int i = 0; i <= currentNum; i++) { +// if (i == num) { +// List msg = event.getChannel().getHistory().retrievePast(num).complete(); +// event.getChannel().purgeMessages(msg); +// // event.getChannel().sendMessage("Successfully purged `" + num + "` +// // messages.").queue(); +// } else { +// List msg = event.getChannel().getHistory().retrievePast(100).complete(); +// event.getChannel().purgeMessages(msg); +// num -= 100; +// } +// } +// } catch (Exception e) { +// if (Main.mode == BotMode.DEV) { +// StringWriter sw = new StringWriter(); +// PrintWriter pw = new PrintWriter(sw); +// e.printStackTrace(pw); +// event.getChannel().sendMessage("```\n" + sw.toString() + "```").queue(); +// System.out.println("Error caught in: " + e.toString()); +// e.printStackTrace(); +// } else { +// event.getChannel().sendMessage("```\n" + e + "```").queue(); // sends limited message +// e.printStackTrace(); +// } +// return; +// } +// } else if (args.size() == 2) { +// +// if (args.get(0).contentEquals("-id") | args.get(0).contentEquals("-i")) { +// long msgID = Long.parseLong(args.get(1)); +// blob.getChannel().retrieveMessageById(msgID).complete(); +// +// for (Message i : blob.getChannel().getIterableHistory()) { +// if (i.getIdLong() == msgID) { +// break; +// } else { +// i.delete().queue(); +// Thread.sleep(1000); +// } +// } +// // i need a better way to get args, flags, and args of flags +// } else if (args.get(0).contentEquals("-u") | args.get(0).contentEquals("-user")) { +// +// long userID = Long.parseLong(args.get(1).replaceAll("[^0-9]", "")); +// if (blob.getJDA().getUserById(userID) == null) { +// throw new NullPointerException("Null user id"); +// } +// +// for (Message i : blob.getChannel().getIterableHistory()) { +// if (i.getAuthor().getIdLong() == userID) { +// i.delete().complete(); +// Thread.sleep(1000); +// } +// +// } +// +// } else { +// pkg.deepCurse.nopalmo.global.Tools.wrongUsage(blob.getChannel(), this); +// } +// +// } else { +// pkg.deepCurse.nopalmo.global.Tools.wrongUsage(blob.getChannel(), this); +// } +// +// } + +} diff --git a/src/pkg/deepCurse/nopalmo/core/Boot.java b/src/pkg/deepCurse/nopalmo/core/Boot.java index e128491..438a585 100644 --- a/src/pkg/deepCurse/nopalmo/core/Boot.java +++ b/src/pkg/deepCurse/nopalmo/core/Boot.java @@ -3,9 +3,11 @@ package pkg.deepCurse.nopalmo.core; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; -import java.sql.SQLException; import java.util.List; +import org.slf4j.Logger; +import org.slf4j.impl.SimpleLoggerFactory; + import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.OnlineStatus; @@ -15,9 +17,8 @@ import net.dv8tion.jda.api.requests.GatewayIntent; import net.dv8tion.jda.api.utils.ChunkingFilter; import net.dv8tion.jda.api.utils.MemberCachePolicy; import net.dv8tion.jda.api.utils.cache.CacheFlag; -import pkg.deepCurse.nopalmo.database.DatabaseTools; -import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Global; -import pkg.deepCurse.nopalmo.global.Reactions; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.GlobalDB; import pkg.deepCurse.nopalmo.listener.MessageReceivedListener; import pkg.deepCurse.nopalmo.manager.CommandManager; import pkg.deepCurse.nopalmo.manager.StatusManager; @@ -31,13 +32,13 @@ import pkg.deepCurse.phoenixRuntime.core.PhoenixSettings; public class Boot { public static JDA bot; // TODO create sharding handler - public static DatabaseTools databaseTools = null; + private static Logger logger = new SimpleLoggerFactory().getLogger(Boot.class.getSimpleName()); + public static final CommandManager commandManager = new CommandManager(); +// public static BontebokManager bontebokManager = null; public static boolean isProd = false; - public static final long pid = ProcessHandle.current().pid(); public static boolean running = true; - public static final CommandManager commandManager = new CommandManager(); public static void main(String[] args) { @@ -48,11 +49,11 @@ public class Boot { // proceed as a failure settings.commandManager.addCommand("phoenix-update", (PhoenixRuntime runtime, List commandArgs) -> { - LogHelper.log("Received ", Boot.class); + logger.info("Received "); Socks.sendStringSock(settings.address, settings.commonPort, "phoenix-update-confirm"); - LogHelper.log("Sent ", Boot.class); + logger.info("Sent "); if (bot != null) { bot.shutdown(); @@ -69,28 +70,21 @@ public class Boot { @Override public void boot() { - LogHelper.log("Booting: <" + pid + ">", Boot.class); + logger.info("Booting: <" + pid + ">"); long preBootTime = System.currentTimeMillis(); isProd = args[2].contentEquals("prod"); - LogHelper.log("Connecting to mariadb:nopalmo", Boot.class); try { - databaseTools = new DatabaseTools(args[1]); - LogHelper.log("Connected. . .", Boot.class); - } catch (SQLException | ClassNotFoundException e1) { - e1.printStackTrace(); - LogHelper.log("Failed to connect\nShutting down. . .", Boot.class); + logger.info("Connecting to mariadb:nopalmo"); + NopalmoDBTools.init(isProd ? "nopalmo" : "chaos", "nopalmo", args[1]); + } catch (Exception e) { + e.printStackTrace(); + logger.info("Failed to connect\nShutting down. . ."); System.exit(4); } - - LogHelper.log("Init reaction/emote list", Boot.class); - Reactions.init(); - LogHelper.log("Initialized reaction/emote list. . .", Boot.class); - LogHelper.log("Init commands list", Boot.class); - commandManager.init(); - LogHelper.log("Initialized commands list. . .", Boot.class); + logger.info("Connected. . ."); try { // bot = JDABuilder.createDefault(args[0]).setChunkingFilter(ChunkingFilter.ALL) @@ -107,25 +101,16 @@ public class Boot { .setChunkingFilter(ChunkingFilter.ALL).setMemberCachePolicy(MemberCachePolicy.ALL) - .enableIntents(GatewayIntent.DIRECT_MESSAGE_REACTIONS, + .enableIntents(GatewayIntent.DIRECT_MESSAGE_REACTIONS, GatewayIntent.DIRECT_MESSAGES, + GatewayIntent.GUILD_BANS, GatewayIntent.GUILD_EMOJIS, GatewayIntent.GUILD_MEMBERS, + GatewayIntent.GUILD_MESSAGE_REACTIONS, GatewayIntent.GUILD_MESSAGES) - GatewayIntent.DIRECT_MESSAGES, GatewayIntent.GUILD_BANS, GatewayIntent.GUILD_EMOJIS, - GatewayIntent.GUILD_MEMBERS, GatewayIntent.GUILD_MESSAGE_REACTIONS, - - GatewayIntent.GUILD_MESSAGES // , GatewayIntent.GUILD_VOICE_STATES - ) - - .enableCache(// CacheFlag.CLIENT_STATUS, - CacheFlag.EMOTE, // CacheFlag.ACTIVITY, - CacheFlag.MEMBER_OVERRIDES // , CacheFlag.VOICE_STATE - ) + .enableCache(CacheFlag.EMOTE, CacheFlag.MEMBER_OVERRIDES) // .setIdle(true) .setAutoReconnect(true) -// .addEventListeners(new GuildMessageReceivedListener()) -// .addEventListeners(new DirectMessageReceivedListener()) .addEventListeners(new MessageReceivedListener()) .setEnableShutdownHook(true) @@ -136,20 +121,18 @@ public class Boot { LogHelper.crash(e); } - LogHelper.log("Using account: " + bot.getSelfUser().getName(), Boot.class); + Loader.init(); + + logger.info("Using account: " + bot.getSelfUser().getName()); bot.getPresence().setStatus(OnlineStatus.ONLINE); bot.getPresence().setActivity(Activity.listening("Infected Mushroom")); - LogHelper.log("Init status list", Boot.class); - StatusManager.init(); - LogHelper.log("Initialized status list. . .", Boot.class); - long bootTime = System.currentTimeMillis() - preBootTime; - LogHelper.log("Taken " + bootTime + "ms to boot", Boot.class); + logger.info("Taken " + bootTime + "ms to boot"); - LogHelper.log("Starting loop", Boot.class); + logger.info("Starting loop"); loop(); } @@ -162,7 +145,7 @@ public class Boot { long lastTimeUpdateStatus = lastTime; long lastTimeCheckUpdate = lastTime; - long dynamicWait = Global.getDynamicWait(); + long dynamicWait = Long.parseLong(GlobalDB.getGlobalValue("dynamicwait")); while (running) { @@ -181,7 +164,8 @@ public class Boot { lastTimeCheckUpdate = now; } - if (now > lastTimeUpdateStatus + dynamicWait && Global.isShuffleStatusEnabled()) { + if (now > lastTimeUpdateStatus + dynamicWait + && GlobalDB.getGlobalValue("isshufflestatusenabled").contentEquals("true")) { lastTimeUpdateStatus = now; StatusManager.shuffle(bot); @@ -206,7 +190,7 @@ public class Boot { }); runtime.setLockedRunnable(() -> { - LogHelper.log("System is locked\nSending instead. . . ", Boot.class); + logger.info("System is locked\nSending instead. . . "); try { Socket cSocket = new Socket("127.0.0.1", settings.commonPort); diff --git a/src/pkg/deepCurse/nopalmo/core/Loader.java b/src/pkg/deepCurse/nopalmo/core/Loader.java new file mode 100644 index 0000000..df15d08 --- /dev/null +++ b/src/pkg/deepCurse/nopalmo/core/Loader.java @@ -0,0 +1,73 @@ +package pkg.deepCurse.nopalmo.core; + +import org.slf4j.Logger; +import org.slf4j.impl.SimpleLoggerFactory; + +import pkg.deepCurse.nopalmo.global.Reactions; +import pkg.deepCurse.nopalmo.manager.StatusManager; + +public class Loader { + + private static Logger logger = new SimpleLoggerFactory().getLogger(Loader.class.getSimpleName()); + + public static String init() { + StringBuilder sB = new StringBuilder(); + + logger.info("Init reaction/emote list"); + sB.append("Init reaction/emote list\n"); + try { + Reactions.init(); + logger.info("Initialized reaction/emote list. . ."); + sB.append("Initialized reaction/emote list. . .\n"); + } catch (Exception e) { + logger.info("Failed to initialize reaction/emote list. . .\n" + e + "\n"); + sB.append("Failed to initialize reaction/emote list. . .```properties\n" + e + "```\n"); + } + + logger.info("Init command list"); + sB.append("Init command list\n"); + try { + Boot.commandManager.init(); + logger.info("Initialized command list. . ."); + sB.append("Initialized command list. . .\n"); + } catch (Exception e) { + logger.info("Failed to initialize command list. . .\n" + e + "\n"); + sB.append("Failed to initialize command list. . .```properties\n" + e + "```\n"); + } + + logger.info("Init status list"); + sB.append("Init status list\n"); + try { + StatusManager.init(); + logger.info("Initialized status list. . ."); + sB.append("Initialized status list. . .\n"); + } catch (Exception e) { + logger.info("Failed to initialize status list. . .\n" + e + "\n"); + sB.append("Failed to initialize status list. . .```properties\n" + e + "```\n"); + } + +// logger.info("Init bontedok settings"); +// sB.append("Init bontedok settings\n"); +// BontebokSettings settings = null; +// try { +// settings = new BontebokSettings(); +// logger.info("Initialized bontedok settings. . ."); +// sB.append("Initilaized bontedok settings\n"); +// } catch (Exception e) { +// logger.info("Failed to initialize bontebok settings. . .\n" + e + "\n"); +// sB.append("Failed to initialize bontebok settings. . .```properties\n" + e + "```\n"); +// } +// logger.info("Init bontedok functions"); +// sB.append("Init bontedok functions\n"); +// try { +// Boot.bontebokManager = new BontebokManager(settings); +// Boot.bontebokManager.init(); +// logger.info("Initialized bontedok functions. . ."); +// sB.append("Initilaized bontedok functions\n"); +// } catch (Exception e) { +// logger.info("Failed to initialize bontebok functions. . .\n" + e + "\n"); +// sB.append("Failed to initialize bontebok functions. . .```properties\n" + e + "```\n"); +// } + return sB.toString(); + } +} \ No newline at end of file diff --git a/src/pkg/deepCurse/nopalmo/core/database/NopalmoDBTools.java b/src/pkg/deepCurse/nopalmo/core/database/NopalmoDBTools.java new file mode 100644 index 0000000..cdbb90e --- /dev/null +++ b/src/pkg/deepCurse/nopalmo/core/database/NopalmoDBTools.java @@ -0,0 +1,805 @@ +package pkg.deepCurse.nopalmo.core.database; + +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Optional; +import java.util.Random; +import org.fluentjdbc.DbContext; +import org.fluentjdbc.DbContextConnection; +import org.fluentjdbc.DbContextTable; +import org.slf4j.Logger; +import org.slf4j.impl.SimpleLoggerFactory; + +import com.mysql.cj.jdbc.MysqlDataSource; + +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.GlobalDB; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.InfractionDB; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.UserDB; + +public class NopalmoDBTools { + + private static Logger logger = new SimpleLoggerFactory().getLogger(NopalmoDBTools.class.getSimpleName()); + + private static DbContext context = null; + + private static DbContextTable users = null; + private static DbContextTable guilds = null; + private static DbContextTable developers = null; + private static DbContextTable global = null; + @SuppressWarnings("unused") // it will remain un implemented for a little bit + private static DbContextTable actions = null; + private static DbContextTable infractions = null; + + private static MysqlDataSource dataSource = null; + + public static void init(String dbName, String username, String pass) { +// logger.info("Connecting. . ."); + context = new DbContext(); + dataSource = new MysqlDataSource(); + dataSource.setDatabaseName(dbName); + dataSource.setUser(username); + dataSource.setPassword(pass); + + users = context.table("users"); + guilds = context.table("guilds"); + developers = context.table("developers"); + global = context.table("global"); + actions = context.table("actions"); + infractions = context.table("infractions"); + + GlobalDB.prefix = GlobalDB.getGlobalValue("prefix"); + +// logger.info("Connected"); + } + + public static void close() throws SQLException { + dataSource.getConnection().close(); + } + + public class Tools { + + public class UserDB { + + public static boolean getUserBoolean(long userID, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + Optional out = users.query().where("userid", userID).singleString(value); + return out.isPresent() ? out.get().contentEquals("1") : null; + } + } + + public static String getUserString(long userID, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + Optional out = users.query().where("userid", userID).singleString(value); + return out.isPresent() ? out.get() : null; + } + } + + public static long getUserLong(long userID, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + Optional out = users.query().where("userid", userID).singleLong(value); + return out.isPresent() ? out.get().longValue() : null; + } + } + + public static boolean userExists(long userID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + return users.query().where("userid", userID).singleLong("userid").isPresent(); + } + } + + public static void setUserBoolean(long userID, String columnName, boolean value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + users.insert().setPrimaryKey("userid", userID).setField(columnName, value).execute(); + } catch (Exception e) { +// e.printStackTrace(); + try { + users.query().where("userid", userID).update().setField(columnName, value).execute(); + } catch (Exception e2) { + e2.printStackTrace(); + e.printStackTrace(); + } + } + } + } + + public static void setUserString(long userID, String columnName, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + users.insert().setPrimaryKey("userid", userID).setField(columnName, value).execute(); + } catch (Exception e) { +// e.printStackTrace(); + try { + users.query().where("userid", userID).update().setField(columnName, value).execute(); + } catch (Exception e2) { + e2.printStackTrace(); + e.printStackTrace(); + } + } + } + } + + public static void setUserLong(long userID, String columnName, long value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + users.insert().setPrimaryKey("userid", userID).setField(columnName, value).execute(); + } catch (Exception e) { +// e.printStackTrace(); + try { + users.query().where("userid", userID).update().setField(columnName, value).execute(); + } catch (Exception e2) { + e2.printStackTrace(); + e.printStackTrace(); + } + } + } + } + + public static void addUser(long userID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + users.insert().setPrimaryKey("userid", userID).execute(); + } catch (Exception e) { + + } + } + } + + public static void removeUser(long userID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + users.query().where("userid", userID).executeDelete(); + } + } + + public static boolean isDirectMessagingEnabled(long userID) { + return getUserBoolean(userID, "allowdms"); + } + + public static boolean isAdvancedUser(long userID) { + return getUserBoolean(userID, "advanceduser"); + } + + public static long getPremiumLevel(long userID) { + return getUserLong(userID, "premiumlevel"); + } + + public static void setDirectMessagingBoolean(long userID, boolean value) { + setUserBoolean(userID, "allowdms", value); + } + + public static void setAdvancedUserBoolean(long userID, boolean value) { + setUserBoolean(userID, "advanceduser", value); + } + + public static void setPremiumLevel(long userID, int value) { + setUserLong(userID, "premiumlevel", value); + } + + /** + * this exists because the lib i tried swapping to doesnt have shit to do with + * columns, and since its only input is long, it should be fine + */ + public static String generateDump(long userID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + Statement st = null; + ResultSet rs = null; + String query = "select * from users where userid = " + userID; + try { + st = users.getConnection().createStatement(); + rs = st.executeQuery(query); + ResultSetMetaData rsMeta = rs.getMetaData(); + int columnCount = rsMeta.getColumnCount(); + StringBuilder sB = new StringBuilder(); + while (rs.next()) { + // Object[] values = new Object[columnCount]; + for (int i = 1; i <= columnCount; i++) { + // values[i - 1] = resultSet.getObject(i); + sB.append(rsMeta.getColumnLabel(i) + ": " + rs.getString(i) + "\n"); + } + } + return sB.toString().isEmpty() ? "No data here" : sB.toString(); + + } catch (SQLException e) { + return null; + } finally { // @formatter:off + try {if (rs != null)rs.close();} catch (Exception e) {} + try {if (st != null)st.close();} catch (Exception e) {} + // @formatter:on + } + } + } + } + + public class GuildDB { + + public static boolean getGuildBoolean(long guildID, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + Optional out = guilds.query().where("guildid", guildID).singleString(value); + return out.isPresent() ? out.get().contentEquals("1") : null; + } + } + + public static String getGuildString(long guildID, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + Optional out = guilds.query().where("guildid", guildID).singleString(value); + return out.isPresent() ? out.get() : null; + } + } + + public static long getGuildLong(long guildID, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + Optional out = guilds.query().where("guildid", guildID).singleLong(value); + return out.isPresent() ? out.get().longValue() : null; + } + } + + public static boolean guildExists(long guildID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + return guilds.query().where("guildid", guildID).singleLong("guildid").isPresent(); + } + } + + public static void setGuildBoolean(long guildID, String columnName, boolean value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + guilds.insert().setPrimaryKey("guildid", guildID).setField(columnName, value).execute(); + } catch (Exception e) { +// e.printStackTrace(); + try { + guilds.query().where("guildid", guildID).update().setField(columnName, value).execute(); + } catch (Exception e2) { + e2.printStackTrace(); + e.printStackTrace(); + } + } + } + } + + public static void setGuildString(long guildID, String columnName, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + guilds.insert().setPrimaryKey("guildid", guildID).setField(columnName, value).execute(); + } catch (Exception e) { +// e.printStackTrace(); + try { + guilds.query().where("guildid", guildID).update().setField(columnName, value).execute(); + } catch (Exception e2) { + e2.printStackTrace(); + e.printStackTrace(); + } + } + } + } + + public static void setGuildLong(long guildID, String columnName, long value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + guilds.insert().setPrimaryKey("guildid", guildID).setField(columnName, value).execute(); + } catch (Exception e) { +// e.printStackTrace(); + try { + guilds.query().where("guildid", guildID).update().setField(columnName, value).execute(); + } catch (Exception e2) { + e2.printStackTrace(); + e.printStackTrace(); + } + } + } + } + + public static void addGuild(long guildID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + guilds.insert().setPrimaryKey("guildid", guildID).execute(); + } catch (Exception e) { + } + } + } + + public static void removeGuild(long guildID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + guilds.query().where("guildid", guildID).executeDelete(); + } + } + + public static void setJoinMessage(long guildID, String value) { + setGuildString(guildID, "joinmessage", value); + } + + public static void setLeaveMessage(long guildID, String value) { + setGuildString(guildID, "leavemessage", value); + } + + public static String getJoinMessage(long guildID) { + return getGuildString(guildID, "joinmessage"); + } + + public static String getLeaveMessage(long guildID) { + return getGuildString(guildID, "leavemessage"); + } + + public static String getPrefix(long guildID) { + return getGuildString(guildID, "prefix"); + } + + public static void setPrefix(long guildID, String value) { + setGuildString(guildID, "prefix", value); + } + + public static String getDateObjectFormat(long guildID) { + return getGuildString(guildID, "dateobjectformat"); + } + + public static void setDateObjectFormat(long guildID, String value) { + setGuildString(guildID, "dateobjectformat", value); + } + + public static boolean getUpdateOwnNameWithPrefix(long guildID) { + return getGuildBoolean(guildID, "updatesownnamewithprefix"); + } + + public static void setUpdateOwnNameWithPrefix(long guildID, boolean value) { + setGuildBoolean(guildID, "updatesownnamewithprefix", value); + } + + } + + public class DeveloperDB { + + public static boolean getDeveloperBoolean(long userID, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + Optional out = developers.query().where("developerid", userID).singleString(value); + return out.isPresent() ? out.get().contentEquals("1") : null; + } + } + + public static String getDeveloperString(long userID, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + Optional out = developers.query().where("developerid", userID).singleString(value); + return out.isPresent() ? out.get() : null; + } + } + + public static long getDeveloperLong(long userID, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + Optional out = developers.query().where("developerid", userID).singleLong(value); + return out.isPresent() ? out.get().longValue() : null; + } + } + + public static boolean developerExists(long userID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + return developers.query().where("developerid", userID).singleLong("developerid").isPresent(); + } + } + + public static void setDeveloperBoolean(long developerID, String columnName, boolean value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + developers.insert().setPrimaryKey("developerid", developerID).setField(columnName, value) + .execute(); + } catch (Exception e) { +// e.printStackTrace(); + try { + developers.query().where("developerid", developerID).update().setField(columnName, value) + .execute(); + } catch (Exception e2) { + e2.printStackTrace(); + e.printStackTrace(); + } + } + } + } + + public static void setDeveloperString(long developerID, String columnName, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + developers.insert().setPrimaryKey("developerid", developerID).setField(columnName, value) + .execute(); + } catch (Exception e) { +// e.printStackTrace(); + try { + developers.query().where("developerid", developerID).update().setField(columnName, value) + .execute(); + } catch (Exception e2) { + e2.printStackTrace(); + e.printStackTrace(); + } + } + } + } + + public static void setDeveloperLong(long developerID, String columnName, long value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + developers.insert().setPrimaryKey("developerid", developerID).setField(columnName, value) + .execute(); + } catch (Exception e) { +// e.printStackTrace(); + try { + developers.query().where("developerid", developerID).update().setField(columnName, value) + .execute(); + } catch (Exception e2) { + e2.printStackTrace(); + e.printStackTrace(); + } + } + } + } + + public static void addDeveloper(long developerID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + developers.insert().setPrimaryKey("developerid", developerID).execute(); + } catch (Exception e) { + + } + } + } + + public static void removeDeveloper(long developerID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + developers.query().where("developerid", developerID).executeDelete(); + } + } + + public static boolean hasPermission(long userID, String permission) { + return getDeveloperBoolean(userID, permission); + } + + public static void setPermission(long userID, String permission, boolean value) { + setDeveloperBoolean(userID, permission, value); + } + + } + + public class GlobalDB { + + public static String prefix = null; + + public static String getGlobalValue(String id) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + return global.query().where("id", id).singleString("value").isPresent() + ? global.query().where("id", id).singleString("value").get() + : null; + } + } + +// public static void setGlobalValue(long id, String columnName, String value) { +// try (DbContextConnection idk = context.startConnection(dataSource)) { +// try { +// global.insert().setPrimaryKey("id", id).setField(columnName, value).execute(); +// } catch (Exception e) { +//// e.printStackTrace(); +// try { +// global.query().where("id", id).update().setField(columnName, value).execute(); +// } catch (Exception e2) { +// e2.printStackTrace(); +// e.printStackTrace(); +// } +// } +// } +// } + + public static boolean globalValueExists(long id) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + return global.query().where("id", id).singleLong("id").isPresent(); + } + } + + } + + public class ActionDB { + // TODO postponed until a later date + } + + public class InfractionDB { + + public static long createInfraction(long userID, String reason, long expiryDate) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + long time = System.currentTimeMillis(); + infractions.insert().setPrimaryKey("userid", userID).setField("reason", reason) + .setField("epochdate", time).setField("expirydate", expiryDate).execute(); + + return infractions.query().where("epochdate", time).singleLong("epochdate").isPresent() + ? infractions.query().where("epochdate", time).singleLong("epochdate").get().longValue() + : null; + } + } + + /** + * do not use unless for bulk testing in the first 10000 ids + * + * @param userID + * @param reason + * @param expiryDate + * @param infractionID + */ + public static void createInfraction(long userID, String reason, long expiryDate, long infractionID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + infractions.insert().setPrimaryKey("infractionid", infractionID).setField("reason", reason) + .setField("epochdate", System.currentTimeMillis()).setField("expirydate", expiryDate) + .setField("userid", userID).execute(); + } + } + + public static void deleteInfraction(long infractionID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + infractions.query().where("infractionid", infractionID).executeDelete(); + } + } + + public static void setInfractionBoolean(long infractionID, String columnName, boolean value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + infractions.insert().setPrimaryKey("infractionid", infractionID).setField(columnName, value) + .execute(); + } catch (Exception e) { + try { + infractions.query().where("infractionid", infractionID).update().setField(columnName, value) + .execute(); + } catch (Exception e2) { + e2.printStackTrace(); + e.printStackTrace(); + } + } + } + } + + public static void setInfractionString(long infractionID, String columnName, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + infractions.insert().setPrimaryKey("infractionid", infractionID).setField(columnName, value) + .execute(); + } catch (Exception e) { + try { + infractions.query().where("infractionid", infractionID).update().setField(columnName, value) + .execute(); + } catch (Exception e2) { + e2.printStackTrace(); + e.printStackTrace(); + } + } + } + } + + public static void setInfractionLong(long infractionID, String columnName, long value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + infractions.insert().setPrimaryKey("infractionid", infractionID).setField(columnName, value) + .execute(); + } catch (Exception e) { + try { + infractions.query().where("infractionid", infractionID).update().setField(columnName, value) + .execute(); + } catch (Exception e2) { + e2.printStackTrace(); + e.printStackTrace(); + } + } + } + } + + public static HashMap getInfractionFromID(long infractionID) { + if (infractionExists(infractionID)) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + HashMap map = new HashMap(); + Statement st = null; + ResultSet rs = null; + String query = "select * from infractions where infractionid = " + infractionID; + try { + st = infractions.getConnection().createStatement(); + rs = st.executeQuery(query); + ResultSetMetaData rsMeta = rs.getMetaData(); + int columnCount = rsMeta.getColumnCount(); + if (rs.next()) { + + for (int i = 1; i <= columnCount; i++) { + map.put(rsMeta.getColumnLabel(i), rs.getString(i)); + } + } + return map.isEmpty() ? null : map; + } catch (SQLException e) { + return null; + } finally { // @formatter:off + try {if (rs != null)rs.close();} catch (Exception e) {} + try {if (st != null)st.close();} catch (Exception e) {} + // @formatter:on + } + } + } else { + return null; + } + } + + public static boolean infractionExists(long infractionID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + return infractions.query().where("infractionID", infractionID).singleLong("infractionID") + .isPresent(); + } + } + + public static ArrayList> getUserInfractions(long userID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + Statement st = null; + ResultSet rs = null; + String query = "select * from infractions where userid = " + userID; + try { + st = infractions.getConnection().createStatement(); + rs = st.executeQuery(query); + ResultSetMetaData rsMeta = rs.getMetaData(); + int columnCount = rsMeta.getColumnCount(); + ArrayList> hashList = new ArrayList>(); + while (rs.next()) { + HashMap infractionHash = new HashMap(); + for (int i = 1; i <= columnCount; i++) { + infractionHash.put(rsMeta.getColumnLabel(i), rs.getString(i)); + } + hashList.add(infractionHash); + } + return hashList.isEmpty() ? null : hashList; + } catch (SQLException e) { + return null; + } finally { // @formatter:off + try {if (rs != null)rs.close();} catch (Exception e) {} + try {if (st != null)st.close();} catch (Exception e) {} + // @formatter:on + } + } + } + + } + + } + + private static ArrayList eLL = null; + private static ArrayList eL = null; + + public static void main(String... args) { + init("chaos", "nopalmo", args[0]); +// } +// +// public static void test(Runnable runnable) { + + long userID = 99; + long guildID = 99; + + Random random = new Random(); + long minutes = 0; + long seconds = 20; + eL = new ArrayList(); + eLL = new ArrayList(); + ArrayList times = new ArrayList(); + for (int i = 0; i < 10; i++) { + times.add(Tests.userLoop((minutes > 0) ? (minutes * 60) : 1 * ((seconds > 0) ? (seconds * 1000) : 1000), + 1000000000, random)); +// runnable.run(); + } + for (int i = 0; i < 10; i++) { + times.add( + Tests.infractionLoop((minutes > 0) ? (minutes * 60) : 1 * ((seconds > 0) ? (seconds * 1000) : 1000), + 1000000000, userID, random)); + } + + if (!eL.isEmpty() && !eLL.isEmpty()) { + for (int i = 0; i < eL.size(); i++) { + System.err.println('\n' + eLL.get(i)); + eL.get(i).printStackTrace(); + } + } + + long total = 0; + for (long i : times) { + total += i; + } + logger.info("Average of {} tests, with length of {} minutes, {} seconds, is {} : {}", times.size(), minutes, + seconds, total / times.size(), total); + } + + private class Tests { + + public static long infractionLoop(long time, long count, long userID, Random random) { + + long userStartTime = System.currentTimeMillis(); + + long currentTime = System.currentTimeMillis(); + long targetTime = System.currentTimeMillis() + time; + + long currentCount = 0; + long targetCount = count; + + for (long i = 1L; true; i++) { + + if (currentTime >= targetTime) { + logger.info("Breaking: Exceeding target time frame"); + break; + } else if (currentCount >= targetCount) { + logger.info("Breaking: Exceeding target count"); + break; + } + + try { + InfractionDB.createInfraction(userID, String.valueOf(random.nextInt()), 0, i); + } catch (Throwable e) { + eLL.add("onCreate"); + eL.add(e); + } + InfractionDB.getInfractionFromID(i); + InfractionDB.setInfractionLong(i, "expirydate", userStartTime); + InfractionDB.getInfractionFromID(i); + try { + InfractionDB.deleteInfraction(i); + } catch (Throwable e) { + eLL.add("onRemove"); + eL.add(e); + } + + currentTime = System.currentTimeMillis(); + currentCount++; + + } + + logger.info("Time taken: {}", (System.currentTimeMillis() - userStartTime)); + logger.info("Total completed count: {}", currentCount); +// return System.currentTimeMillis() - userStartTime; + return currentCount; + } + + public static long userLoop(long time, long count, Random random) { + + long userStartTime = System.currentTimeMillis(); + + long currentTime = System.currentTimeMillis(); + long targetTime = System.currentTimeMillis() + time; + + long currentCount = 0; + long targetCount = count; + + for (long i = 1L; true; i++) { + + if (currentTime >= targetTime) { + logger.info("Breaking: Exceeding target time frame"); + break; + } else if (currentCount >= targetCount) { + logger.info("Breaking: Exceeding target count"); + break; + } + + try { + UserDB.addUser(i); + } catch (Throwable e) { + eLL.add("onCreate"); + eL.add(e); + } + + UserDB.setAdvancedUserBoolean(i, true); + UserDB.setDirectMessagingBoolean(i, false); + UserDB.setPremiumLevel(i, 2); + UserDB.getPremiumLevel(i); + UserDB.isAdvancedUser(i); + UserDB.isDirectMessagingEnabled(i); + + try { + UserDB.removeUser(i); + } catch (Throwable e) { + eLL.add("onRemove"); + eL.add(e); + } + + currentTime = System.currentTimeMillis(); + currentCount++; + + } + + logger.info("Time taken: {}", (System.currentTimeMillis() - userStartTime)); + logger.info("Total completed count: {}", currentCount); +// return System.currentTimeMillis() - userStartTime; + return currentCount; + } + + } +} diff --git a/src/pkg/deepCurse/nopalmo/core/database/Schemat.ic b/src/pkg/deepCurse/nopalmo/core/database/Schemat.ic new file mode 100644 index 0000000..9530e3a --- /dev/null +++ b/src/pkg/deepCurse/nopalmo/core/database/Schemat.ic @@ -0,0 +1,111 @@ + public static boolean getGuildBoolean(long guildID, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + Optional out = guilds.query().where("guildid", guildID).singleString(value); + return out.isPresent() ? out.get().contentEquals("1") : null; + } + } + + public static String getGuildString(long guildID, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + Optional out = guilds.query().where("guildid", guildID).singleString(value); + return out.isPresent() ? out.get() : null; + } + } + + public static long getGuildLong(long guildID, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + Optional out = guilds.query().where("guildid", guildID).singleLong(value); + return out.isPresent() ? out.get().longValue() : null; + } + } + + public static void setGuildBoolean(long guildID, String columnName, boolean value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + guilds.insert().setPrimaryKey("guildid", guildID).setField(columnName, value).execute(); + } catch (Exception e) { +// e.printStackTrace(); + try { + guilds.query().where("guildid", guildID).update().setField(columnName, value).execute(); + } catch (Exception e2) { + e2.printStackTrace(); + e.printStackTrace(); + } + } + } + } + + public static void setGuildString(long guildID, String columnName, String value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + guilds.insert().setPrimaryKey("guildid", guildID).setField(columnName, value).execute(); + } catch (Exception e) { +// e.printStackTrace(); + try { + guilds.query().where("guildid", guildID).update().setField(columnName, value).execute(); + } catch (Exception e2) { + e2.printStackTrace(); + e.printStackTrace(); + } + } + } + } + + public static void setGuildLong(long guildID, String columnName, long value) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + guilds.insert().setPrimaryKey("guildid", guildID).setField(columnName, value).execute(); + } catch (Exception e) { +// e.printStackTrace(); + try { + guilds.query().where("guildid", guildID).update().setField(columnName, value).execute(); + } catch (Exception e2) { + e2.printStackTrace(); + e.printStackTrace(); + } + } + } + } + + public static boolean guildExists(long guildID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + return guilds.query().where("guildid", guildID).singleLong("guildid").isPresent(); + } + } + + public static void addGuild(long guildID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + try { + guilds.insert().setPrimaryKey("guildid", guildID).execute(); + } catch (Exception e) { + } + } + } + + public static void removeGuild(long guildID) { + try (DbContextConnection idk = context.startConnection(dataSource)) { + guilds.query().where("guildid", guildID).executeDelete(); + } + } + + + + + + +TYPE + +add +remove +exists +set(long string boolean) +get(long string boolean) + +misc interactions... + + + + + + + diff --git a/src/pkg/deepCurse/nopalmo/database/DatabaseTools.java b/src/pkg/deepCurse/nopalmo/database/DatabaseTools.java deleted file mode 100644 index b1f04fc..0000000 --- a/src/pkg/deepCurse/nopalmo/database/DatabaseTools.java +++ /dev/null @@ -1,545 +0,0 @@ -package pkg.deepCurse.nopalmo.database; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; - -import javax.annotation.Nonnull; - -import org.jetbrains.annotations.Nullable; - -import pkg.deepCurse.nopalmo.core.Boot; -import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Global; -import pkg.deepCurse.nopalmo.utils.LogHelper; - -public class DatabaseTools { - - private static Connection connection = null; - - public DatabaseTools(String password) throws SQLException, ClassNotFoundException { - connection = createConnection(password); - Global.updatePrefix(); - } - - public static Connection createConnection(String password) throws SQLException, ClassNotFoundException { - - String dbName = Boot.isProd ? "nopalmo" : "chaos"; - - String driver = "com.mysql.cj.jdbc.Driver"; - String url = "jdbc:mysql://localhost/" + dbName; - String username = "nopalmo"; - - Class.forName(driver); - return DriverManager.getConnection(url, username, password); - } - - private static void checkUpdateCounts(PreparedStatement pstmt, int[] updateCounts) { - checkUpdateCounts(pstmt.toString(), updateCounts); - } - - @Deprecated - public static void checkUpdateCounts(String action, int[] updateCounts) { - for (int i = 0; i < updateCounts.length; i++) { - if (updateCounts[i] >= 0) { - LogHelper.log("Successfully executed; updateCount=" + updateCounts[i] + "; On action " + action, - DatabaseTools.class); - } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) { - LogHelper.log("Successfully executed; updateCount=Statement.SUCCESS_NO_INFO; On action " + action, - DatabaseTools.class); - } else if (updateCounts[i] == Statement.EXECUTE_FAILED) { - LogHelper.log("Failed to execute; updateCount=Statement.EXECUTE_FAILED; On action " + action, - DatabaseTools.class); - } - } - } - - public class Tools { - - // these sub classes will represent tables and the methods therein will be for - // actions within said table - - public class Users { - - public static int getPremiumLevel(long userID) { - Statement st = null; - ResultSet rs = null; - String query = "select * from users where userid = " + userID; - try { - st = connection.createStatement(); - rs = st.executeQuery(query); - if (rs.next()) { - return rs.getInt("premiumlevel"); - } else { - // throw new SQLException(null, null, 33); // we need a real catcher here - System.err - .println("Failed to execute; errorCode=NO_ROW_FOUND; No row found; On action " + query); - return 0; - } - } catch (SQLException e) { - SQLCode.getMessage(query, e.getErrorCode()); - return 0; - } finally { // @formatter:off - try {if (rs != null)rs.close();} catch (Exception e) {} - try {if (st != null)st.close();} catch (Exception e) {} - // @formatter:on - } - } - - public static boolean isAdvancedUser(long userID) { - Statement st = null; - ResultSet rs = null; - String query = "select * from users where userid = " + userID; - try { - st = connection.createStatement(); - rs = st.executeQuery(query); - if (rs.next()) { - return rs.getBoolean("advanceduser"); - } else { - // throw new SQLException(null, null, 33); // we need a real catcher here - System.err - .println("Failed to execute; errorCode=NO_ROW_FOUND; No row found; On action " + query); - return false; - } - } catch (SQLException e) { - SQLCode.getMessage(query, e.getErrorCode()); - return false; - } finally { // @formatter:off - try {if (rs != null)rs.close();} catch (Exception e) {} - try {if (st != null)st.close();} catch (Exception e) {} - // @formatter:on - } - } - - public static String dump(long userID) { - Statement st = null; - ResultSet rs = null; - String query = "select * from users where userid = " + userID; - try { - st = connection.createStatement(); - rs = st.executeQuery(query); - ResultSetMetaData rsMeta = rs.getMetaData(); - int columnCount = rsMeta.getColumnCount(); - StringBuilder sB = new StringBuilder(); - while (rs.next()) { - // Object[] values = new Object[columnCount]; - for (int i = 1; i <= columnCount; i++) { - // values[i - 1] = resultSet.getObject(i); - sB.append(rsMeta.getColumnLabel(i) + ": " + rs.getString(i) + "\n"); - } - } - return sB.toString(); - - } catch (SQLException e) { - SQLCode.getMessage(query, e.getErrorCode()); - return null; - } finally { // @formatter:off - try {if (rs != null)rs.close();} catch (Exception e) {} - try {if (st != null)st.close();} catch (Exception e) {} - // @formatter:on - } - } - - public static void addUser(long idLong) { - - } - - } - - public class Guild { - - public class Prefix { - - @Nullable - public static String getPrefix(@Nonnull long guildID) { - Statement st = null; - ResultSet rs = null; - String query = "select * from guilds where guildid = " + guildID; - try { - st = connection.createStatement(); - rs = st.executeQuery(query); - if (rs.next()) { - return rs.getString("prefix"); - } else { - // throw new SQLException(null, null, 33); // we need a real catcher here - System.err.println( - "Failed to execute; errorCode=NO_ROW_FOUND; No row found; On action " + query); - return createPrefix(guildID, Global.prefix); - } - } catch (SQLException e) { - SQLCode.getMessage(query, e.getErrorCode()); - return null; - } finally { // @formatter:off - try {if (rs != null)rs.close();} catch (Exception e) {} - try {if (st != null)st.close();} catch (Exception e) {} - // @formatter:on - } - } - - public static String createPrefix(@Nonnull long guildID, @Nullable String prefix) - throws IllegalArgumentException { - - if (prefix == null || prefix.isEmpty()) { - // throw new IllegalArgumentException("Input cannot be empty"); - prefix = Global.prefix; - } - - PreparedStatement pstmt = null; - - String query = "insert into guilds(guildid, prefix) values(?, ?);"; - try { - pstmt = connection.prepareStatement(query); - - pstmt.setLong(1, guildID); - pstmt.setString(2, prefix); - pstmt.addBatch(); - - int[] updateCounts = pstmt.executeBatch(); - checkUpdateCounts(pstmt, updateCounts); - pstmt.close(); - // connection.commit(); - return prefix; - } catch (SQLException e) { - SQLCode.sqlTranslate(pstmt, e); - for (int i : new int[] { 1062 }) { - if (i == e.getErrorCode()) { - return setPrefix(guildID, prefix); - } - } - try { - connection.rollback(); - } catch (Exception e2) { - e.printStackTrace(); - } - return null; - } - } - - public static String setPrefix(long guildID, String prefix) throws IllegalArgumentException { - - if (prefix.isEmpty()) { - throw new IllegalArgumentException("Input cannot be empty"); - } - - PreparedStatement pstmt = null; - - String query = "update guilds set prefix = ? where guildid = ?;"; - try { - pstmt = connection.prepareStatement(query); - - pstmt.setLong(2, guildID); - pstmt.setString(1, prefix); - pstmt.addBatch(); - - int[] updateCounts = pstmt.executeBatch(); - checkUpdateCounts(pstmt, updateCounts); - pstmt.close(); - // conn.commit(); - return prefix; - } catch (SQLException e) { - SQLCode.sqlTranslate(pstmt, e); - try { - connection.rollback(); - } catch (Exception e2) { - e.printStackTrace(); - } - return null; - } - } - } - } - - public class Developers { - - public static boolean getDeveloperBoolean(long userID, String key) { - Statement st = null; - ResultSet rs = null; - String query = "select * from developers where userid = " + userID; - try { - st = connection.createStatement(); - rs = st.executeQuery(query); - if (rs.next()) { - return rs.getBoolean(key); - } else { - // throw new SQLException(null, null, 33); // we need a real catcher here - System.err - .println("Failed to execute; errorCode=NO_ROW_FOUND; No row found; On action " + query); - return false; - } - - } catch (SQLException e) { - SQLCode.getMessage(query, e.getErrorCode()); - // LogHelper.log("eeeeee"); - return false; - } finally { - try { - if (rs != null) - rs.close(); - } catch (Exception e) { - } - - try { - if (st != null) - st.close(); - } catch (Exception e) { - } - - // try { if (conn != null) conn.close(); } catch (Exception e) {}; - } - // return null; - } - - public static String getDeveloperString(long userID, String key) { - Statement st = null; - ResultSet rs = null; - String query = "select * from developers where userid = " + userID; - try { - st = connection.createStatement(); - rs = st.executeQuery(query); - if (rs.next()) { - return rs.getString(key); - } else { - // throw new SQLException(null, null, 33); // we need a real catcher here - System.err - .println("Failed to execute; errorCode=NO_ROW_FOUND; No row found; On action " + query); - return null; - } - - } catch (SQLException e) { - SQLCode.getMessage(query, e.getErrorCode()); - // LogHelper.log("eeeeee"); - return null; - } finally { - try { - if (rs != null) - rs.close(); - } catch (Exception e) { - } - - try { - if (st != null) - st.close(); - } catch (Exception e) { - } - - // try { if (conn != null) conn.close(); } catch (Exception e) {}; - } - // return null; - } - - public static boolean canPowerOffBot(long userID) { - return getDeveloperBoolean(userID, "canPowerOffBot"); - } - - public static boolean canUseInformationCommands(long userID) { - return getDeveloperBoolean(userID, "canuseinformationcommands"); - } - - public static boolean hasPermission(long userID, String permission) { - return getDeveloperBoolean(userID, permission); - } - - } - - public class Global { - - public static String prefix = null; - - public static void updatePrefix() throws SQLException { - Statement st = null; - ResultSet rs = null; - String query = "select * from global where id = 'prefix'"; - String msg = "Failed to execute; errorCode=NO_ROW_FOUND; No row found; On action " + query; - try { - st = connection.createStatement(); - rs = st.executeQuery(query); - if (rs.next()) { - prefix = rs.getString("value"); - } else { - // throw new SQLException(null, null, 33); // we need a real catcher here - - System.err.println(msg); - throw new NullPointerException(msg); - } - - } catch (SQLException e) { - SQLCode.getMessage(query, e.getErrorCode()); - // LogHelper.log("eeeeee"); - throw new SQLException(e); - } finally { - try { - if (rs != null) - rs.close(); - } catch (Exception e) { - } - - try { - if (st != null) - st.close(); - } catch (Exception e) { - } - - // try { if (conn != null) conn.close(); } catch (Exception e) {}; - } - // return null; - } - - public static boolean isShuffleStatusEnabled() { - Statement st = null; - ResultSet rs = null; - String query = "select * from global where id = 'isshufflestatusenabled'"; - try { - st = connection.createStatement(); - rs = st.executeQuery(query); - if (rs.next()) { - return rs.getString("value").contentEquals("true"); - } else { - System.err - .println("Failed to execute; errorCode=NO_ROW_FOUND; No row found; On action " + query); - return false; - } - - } catch (SQLException e) { - SQLCode.getMessage(query, e.getErrorCode()); - // LogHelper.log("eeeeee"); - return false; - } finally { - try { - if (rs != null) - rs.close(); - } catch (Exception e) { - } - - try { - if (st != null) - st.close(); - } catch (Exception e) { - } - - // try { if (conn != null) conn.close(); } catch (Exception e) {}; - } - // return null; - } - - public static int getDynamicWait() { - Statement st = null; - ResultSet rs = null; - String query = "select * from global where id = 'dynamicwait'"; - try { - st = connection.createStatement(); - rs = st.executeQuery(query); - if (rs.next()) { - return rs.getInt("value"); - } else { - System.err - .println("Failed to execute; errorCode=NO_ROW_FOUND; No row found; On action " + query); - return 45000; - } - - } catch (SQLException e) { - SQLCode.getMessage(query, e.getErrorCode()); - // LogHelper.log("eeeeee"); - return 45000; - } finally { - try { - if (rs != null) - rs.close(); - } catch (Exception e) { - } - - try { - if (st != null) - st.close(); - } catch (Exception e) { - } - - // try { if (conn != null) conn.close(); } catch (Exception e) {}; - } - // return null; - } - - public static int getEmbedColor() { - Statement st = null; - ResultSet rs = null; - String query = "select * from global where id = 'embedcolor'"; - try { - st = connection.createStatement(); - rs = st.executeQuery(query); - if (rs.next()) { - return rs.getInt("value"); - } else { - System.err - .println("Failed to execute; errorCode=NO_ROW_FOUND; No row found; On action " + query); - return 0; - } - - } catch (SQLException e) { - SQLCode.getMessage(query, e.getErrorCode()); - // LogHelper.log("eeeeee"); - return 0; - } finally { - try { - if (rs != null) - rs.close(); - } catch (Exception e) { - } - - try { - if (st != null) - st.close(); - } catch (Exception e) { - } - - // try { if (conn != null) conn.close(); } catch (Exception e) {}; - } - // return null; - } - - } - -// public class Reaction { // started off as a good idea but it sucks -// public static String getReaction(long reactionID) { -// Statement st = null; -// ResultSet rs = null; -// String query = "select * from reactions where id = '"+reactionID+"'"; -// try { -// st = connection.createStatement(); -// rs = st.executeQuery(query); -// if (rs.next()) { -// return rs.getString("val"); -// } else { -// // throw new SQLException(null, null, 33); // we need a real catcher here -// System.err -// .println("Failed to execute; errorCode=NO_ROW_FOUND; No row found; On action " + query); -// return null; -// } -// -// } catch (SQLException e) { -// sqlTranslate(query, e.getErrorCode()); -// // LogHelper.log("eeeeee"); -// return null; -// } finally { -// try { -// if (rs != null) -// rs.close(); -// } catch (Exception e) { -// } -// -// try { -// if (st != null) -// st.close(); -// } catch (Exception e) { -// } -// -// // try { if (conn != null) conn.close(); } catch (Exception e) {}; -// } -// // return null; -// } -// } - - } - -} diff --git a/src/pkg/deepCurse/nopalmo/database/RamDisk.java b/src/pkg/deepCurse/nopalmo/database/RamDisk.java deleted file mode 100644 index 5b60a0e..0000000 --- a/src/pkg/deepCurse/nopalmo/database/RamDisk.java +++ /dev/null @@ -1,14 +0,0 @@ -package pkg.deepCurse.nopalmo.database; - -import java.util.HashMap; - -public class RamDisk { - - public static HashMap bools = new HashMap(); - // public static - - public static void init() { - bools.put("shouldRun", true); - } - -} diff --git a/src/pkg/deepCurse/nopalmo/database/SQLCode.java b/src/pkg/deepCurse/nopalmo/database/SQLCode.java deleted file mode 100644 index 68dc8c8..0000000 --- a/src/pkg/deepCurse/nopalmo/database/SQLCode.java +++ /dev/null @@ -1,32 +0,0 @@ -package pkg.deepCurse.nopalmo.database; - -import java.sql.PreparedStatement; -import java.sql.SQLException; - -public class SQLCode { - - public static String getMessage(String action, int errorCode) { - switch (errorCode) { - case 1062: - System.err.println("Failed to execute; errorCode=" + errorCode + "; ER_DUP_ENTRY; On action " + action); - return ""; - case 1054: - System.err - .println("Failed to execute; errorCode=" + errorCode + "; ER_BAD_FIELD_ERROR; On action " + action); - return ""; - default: - System.err.println("Failed to execute; errorCode=" + errorCode + "; Unknown code; On action " + action); - return ""; - } - } - - @Deprecated - public static void sqlTranslate(String action, SQLException e) { - SQLCode.getMessage(action, e.getErrorCode()); - } - - public static void sqlTranslate(PreparedStatement pstmt, SQLException e) { - SQLCode.getMessage(pstmt.toString(), e.getErrorCode()); - } - -} diff --git a/src/pkg/deepCurse/nopalmo/global/Tools.java b/src/pkg/deepCurse/nopalmo/global/Tools.java index c9eb1f1..f13243e 100644 --- a/src/pkg/deepCurse/nopalmo/global/Tools.java +++ b/src/pkg/deepCurse/nopalmo/global/Tools.java @@ -1,10 +1,14 @@ package pkg.deepCurse.nopalmo.global; +import java.util.Random; + import net.dv8tion.jda.api.entities.MessageChannel; import pkg.deepCurse.nopalmo.command.CommandInterface; public class Tools { + public static Random random = new Random(); + public static void wrongUsage(MessageChannel messageChannel, CommandInterface command) { messageChannel.sendMessage("Wrong Command Usage!\n" + command.getUsage(false)).queue(); } diff --git a/src/pkg/deepCurse/nopalmo/listener/MessageReceivedListener.java b/src/pkg/deepCurse/nopalmo/listener/MessageReceivedListener.java index 77e8054..9a3917b 100644 --- a/src/pkg/deepCurse/nopalmo/listener/MessageReceivedListener.java +++ b/src/pkg/deepCurse/nopalmo/listener/MessageReceivedListener.java @@ -2,41 +2,50 @@ package pkg.deepCurse.nopalmo.listener; import javax.annotation.Nonnull; +import org.slf4j.Logger; +import org.slf4j.impl.SimpleLoggerFactory; + import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.events.ReadyEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import pkg.deepCurse.nopalmo.core.Boot; -import pkg.deepCurse.nopalmo.database.DatabaseTools; -import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Global; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.DeveloperDB; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.GlobalDB; import pkg.deepCurse.nopalmo.global.Reactions; -import pkg.deepCurse.nopalmo.utils.LogHelper; public class MessageReceivedListener extends ListenerAdapter { + private Logger logger = new SimpleLoggerFactory().getLogger(this.getClass().getSimpleName()); + @Override public void onReady(@Nonnull ReadyEvent event) { - LogHelper.log("MessageReceivedListener is now ready\n" + event.getGuildAvailableCount() + "/" + logger.info("MessageReceivedListener is now ready " + event.getGuildAvailableCount() + "/" + event.getGuildTotalCount() + " : " + event.getGuildUnavailableCount() + " <" - + event.getResponseNumber() + ">", getClass()); + + event.getResponseNumber() + ">"); } @Override public void onMessageReceived(@Nonnull MessageReceivedEvent event) { - Message message = event.getMessage(); - String messageRaw = message.getContentRaw(); + try { + Message message = event.getMessage(); + String messageRaw = message.getContentRaw(); - if (messageRaw.contentEquals(Global.prefix + Global.prefix) - && DatabaseTools.Tools.Developers.canPowerOffBot(event.getAuthor().getIdLong())) { + if (messageRaw.contentEquals(GlobalDB.prefix + GlobalDB.prefix) + && DeveloperDB.hasPermission(event.getAuthor().getIdLong(), "canpoweroffbot")) { - message.addReaction(Reactions.getReaction(":eggplant")).complete(); + message.addReaction(Reactions.getReaction(":eggplant")).complete(); - event.getJDA().shutdown(); - System.exit(7); - } + event.getJDA().shutdown(); + System.exit(7); + } - if (!event.getAuthor().isBot()) { - Boot.commandManager.startCommand(event); + if (!event.getAuthor().isBot()) { + Boot.commandManager.startCommand(event); + } + } catch (Throwable e) { + event.getChannel().sendMessage(e.toString()).queue(); + e.printStackTrace(); } } } diff --git a/src/pkg/deepCurse/nopalmo/manager/Argument.java b/src/pkg/deepCurse/nopalmo/manager/Argument.java index 3f99858..9e59399 100644 --- a/src/pkg/deepCurse/nopalmo/manager/Argument.java +++ b/src/pkg/deepCurse/nopalmo/manager/Argument.java @@ -106,11 +106,6 @@ public class Argument { // return this; // } - public Argument setPrefixRequirement(Boolean bool) { - this.requiresPrefix = bool; - return this; - } - public Argument setIsWildcard(Boolean bool) { if (this.position <= -1) { @@ -129,6 +124,11 @@ public class Argument { return this.requiresPrefix; } + public Argument setPrefixRequirement(Boolean bool) { + this.requiresPrefix = bool; + return this; + } + public int getPosition() { return position; } diff --git a/src/pkg/deepCurse/nopalmo/manager/BontebokManager.java b/src/pkg/deepCurse/nopalmo/manager/BontebokManager.java index dcd8a10..4353be6 100644 --- a/src/pkg/deepCurse/nopalmo/manager/BontebokManager.java +++ b/src/pkg/deepCurse/nopalmo/manager/BontebokManager.java @@ -1,59 +1,77 @@ -package pkg.deepCurse.nopalmo.manager; - -import java.util.List; - -import pkg.deepCurse.bontebok.core.BontebokFunctionInterface; -import pkg.deepCurse.bontebok.core.BontebokInterpreter; -import pkg.deepCurse.nopalmo.global.Reactions; - -public class BontebokManager { - - public static void init() { - BontebokInterpreter.functionMap.put("reply", new BontebokNopalmoFunctionInterface() { - - @Override - public void run(List args, CommandBlob blob) { - StringBuilder sB = new StringBuilder(); - for (String i : args) { - sB.append(i); - } - blob.getMessage().reply(sB.toString()).queue(); - } - - @Override - public int getRequiredArgs() { - return -1; - } - - }); - - BontebokInterpreter.functionMap.put("react", new BontebokNopalmoFunctionInterface() { - - @Override - public void run(List args, CommandBlob blob) { - try { - blob.getMessage().addReaction(Reactions.getReaction(args.get(0))).queue(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public int getRequiredArgs() { - return 1; - } - }); - - } - - public interface BontebokNopalmoFunctionInterface extends BontebokFunctionInterface { - - @Override - public default void run(List args) { - - } - - void run(List args, CommandBlob blob); - } - -} +//package pkg.deepCurse.nopalmo.manager; +// +//import java.util.List; +// +//import pkg.deepCurse.bontebok.core.BontebokFunctionInterface; +//import pkg.deepCurse.bontebok.core.BontebokInterpreter; +//import pkg.deepCurse.bontebok.core.BontebokSettings; +//import pkg.deepCurse.nopalmo.global.Reactions; +// +//public class BontebokManager { +// +// private BontebokInterpreter interpreter = null; +// private BontebokSettings settings = null; +// +// public BontebokManager(BontebokSettings settings) { +// interpreter = new BontebokInterpreter(settings); +// this.settings = settings; +// } +// +// public BontebokManager init() { +// interpreter.clearFunctionMap(); +// interpreter.addFunction("reply", new BontebokNopalmoFunctionInterface() { +// +// @Override +// public void run(List args, CommandBlob blob) { +// StringBuilder sB = new StringBuilder(); +// for (String i : args) { +// sB.append(i); +// } +// blob.getMessage().reply(sB.toString()).queue(); +// } +// +// @Override +// public int getRequiredArgs() { +// return -1; +// } +// +// }); +// +// interpreter.addFunction("react", new BontebokNopalmoFunctionInterface() { +// +// @Override +// public void run(List args, CommandBlob blob) { +// try { +// blob.getMessage().addReaction(Reactions.getReaction(args.get(0))).queue(); +// } catch (Exception e) { +// e.printStackTrace(); +// } +// } +// +// @Override +// public int getRequiredArgs() { +// return 1; +// } +// }); +// return this; +// } +// +// public BontebokInterpreter getBontebokInterpreter() { +// return interpreter; +// } +// +// public BontebokSettings getBontebokSettings() { +// return settings; +// } +// +// public interface BontebokNopalmoFunctionInterface extends BontebokFunctionInterface { +// +// @Override +// public default void run(List args) { +// +// } +// +// void run(List args, CommandBlob blob); +// } +// +//} diff --git a/src/pkg/deepCurse/nopalmo/manager/CommandBlob.java b/src/pkg/deepCurse/nopalmo/manager/CommandBlob.java index 8d4572a..b5d9877 100644 --- a/src/pkg/deepCurse/nopalmo/manager/CommandBlob.java +++ b/src/pkg/deepCurse/nopalmo/manager/CommandBlob.java @@ -28,6 +28,7 @@ public class CommandBlob { private Guild guild = null; private Member member = null; private Message message = null; +// private BontebokInterpreter interpreter = null; private boolean isDeveloper = false; private boolean isWebhookMessage = false; @@ -172,4 +173,13 @@ public class CommandBlob { public void setDeveloper(boolean isDeveloper) { this.isDeveloper = isDeveloper; } + +// public BontebokInterpreter getInterpreter() { +// return interpreter; +// } +// +// public CommandBlob setInterpreter(BontebokInterpreter interpreter) { +// this.interpreter = interpreter; +// return this; +// } } diff --git a/src/pkg/deepCurse/nopalmo/manager/CommandLoop.java b/src/pkg/deepCurse/nopalmo/manager/CommandLoop.java new file mode 100644 index 0000000..cb24747 --- /dev/null +++ b/src/pkg/deepCurse/nopalmo/manager/CommandLoop.java @@ -0,0 +1,9 @@ +package pkg.deepCurse.nopalmo.manager; + +public class CommandLoop { + + public static add() { + + } + +} diff --git a/src/pkg/deepCurse/nopalmo/manager/CommandManager.java b/src/pkg/deepCurse/nopalmo/manager/CommandManager.java index 6f31cfa..1001f0d 100644 --- a/src/pkg/deepCurse/nopalmo/manager/CommandManager.java +++ b/src/pkg/deepCurse/nopalmo/manager/CommandManager.java @@ -26,14 +26,13 @@ import pkg.deepCurse.nopalmo.command.commands.info.Help; import pkg.deepCurse.nopalmo.command.commands.info.Info; import pkg.deepCurse.nopalmo.command.commands.info.Ping; import pkg.deepCurse.nopalmo.command.commands.info.Reload; -import pkg.deepCurse.nopalmo.command.commands.testing.BontebokInterpret; import pkg.deepCurse.nopalmo.command.commands.testing.GuildCommand; import pkg.deepCurse.nopalmo.command.commands.testing.PrivateCommand; import pkg.deepCurse.nopalmo.core.Boot; -import pkg.deepCurse.nopalmo.database.DatabaseTools; -import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Developers; -import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Global; -import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Users; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.DeveloperDB; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.GlobalDB; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.GuildDB; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.UserDB; import pkg.deepCurse.nopalmo.global.Tools; public class CommandManager { @@ -59,7 +58,7 @@ public class CommandManager { addCommand(new GuildCommand()); // guild addCommand(new PrivateCommand()); // private addCommand(new Reload()); // dual - addCommand(new BontebokInterpret()); // dual +// addCommand(new BontebokInterpret()); // dual addCommand(new Stupid()); // guild } @@ -83,47 +82,51 @@ public class CommandManager { public void startCommand(MessageReceivedEvent event) { // TODO split up more final String message = event.getMessage().getContentRaw(); - String prefix = null; - if (event.isFromGuild()) { - prefix = DatabaseTools.Tools.Guild.Prefix.getPrefix(event.getGuild().getIdLong()); - } else { - prefix = Global.prefix; - } - String pingPrefix = "<@!" + event.getJDA().getSelfUser().getIdLong() + ">"; + final String prefix = event.isFromGuild() ? (GuildDB.getPrefix(event.getGuild().getIdLong()) != null + ? GuildDB.getPrefix(event.getGuild().getIdLong()) + : GlobalDB.prefix) : GlobalDB.prefix; + final String pingPrefix = "<@!" + event.getJDA().getSelfUser().getIdLong() + ">"; String splicer = null; - if (message.startsWith(pingPrefix + " ")) { - splicer = pingPrefix + " "; - } else if (message.startsWith(prefix)) { - splicer = prefix; - } else if (message.startsWith(pingPrefix)) { - splicer = pingPrefix; - } else { - return; - } - - Users.addUser(event.getAuthor().getIdLong()); - + + if (message.startsWith(pingPrefix + " ")) { + splicer = pingPrefix + " "; + } else if (message.startsWith(prefix)) { + splicer = prefix; + } else if (message.startsWith(pingPrefix)) { + splicer = pingPrefix; + } else { + return; + } + final String[] split = message.replaceFirst("(?i)" + Pattern.quote(splicer), "").split("\\s+"); final String commandCall = split[0].toLowerCase(); if (commandMap.containsKey(commandCall)) { + + UserDB.addUser(event.getAuthor().getIdLong()); + + if (event.isFromGuild()) { + GuildDB.addGuild(event.getGuild().getIdLong()); + } + final List args = Arrays.asList(split).subList(1, split.length); - executor.execute(() -> { - long commandStartTime = System.currentTimeMillis(); - try { CommandBlob commandBlob = new CommandBlob(event, this); CommandInterface command = commandMap.get(commandCall); + +// commandBlob.setInterpreter(Boot.bontebokManager.getBontebokInterpreter()); + HashMap argumentMap = new HashMap(); + HashMap positionalArgs = new HashMap(); + + long commandStartTime = System.currentTimeMillis(); boolean printTime = false; byte argSkipCount = 0; boolean remainsValid = true; - HashMap positionalArgs = new HashMap(); - if (command.getArguments() != null) { for (Argument i : command.getArguments().values()) { if (i.getPosition() >= 0) { @@ -155,24 +158,33 @@ public class CommandManager { } commandBlob.setDeveloper( - Developers.getDeveloperBoolean(commandBlob.getAuthorID(), "developercommandpermission")); - - // split up so global commands are actually global, and will not be affected by - // neighboring local args + DeveloperDB.getDeveloperBoolean(commandBlob.getAuthorID(), "developercommandpermission")); for (int i = 0; i < newArgs.size(); i++) { String x = newArgs.get(i); x = x.toLowerCase(); if (argSkipCount <= 0) { if (command.getArguments() != null) { +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + if (x.startsWith(Argument.argumentPrefix)) { String pre = x.substring(Argument.argumentPrefix.length()); + + if (!command.getArguments().keySet().contains(pre)) { + for (Argument arg : command.getArguments().values()) { + if (arg.getAliases().contains(pre)) { +// System.out.println("ALIAS FOUND"); + pre = arg.getArgName(); + } + } + } // TODO RIP ROOT ALIAS PREFIX IN FAVOR OF "--long-name" "-s (shortname)" "wildcard" + if (command.getArguments().keySet().contains(pre)) { + offset++; if (command.getArguments().get(pre).getPermission() == null - || DatabaseTools.Tools.Developers.hasPermission( - commandBlob.getAuthorID(), + || DeveloperDB.hasPermission(commandBlob.getAuthorID(), command.getArguments().get(pre).getPermission())) { if (command.getArguments().get(pre).isSkipOriginalTaskOnRunnable()) { remainsValid = false; @@ -191,11 +203,27 @@ public class CommandManager { Tools.wrongUsage(event.getChannel(), command); remainsValid = false; } + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + } else { + + if (!command.getArguments().keySet().contains(x)) { + for (Argument arg : command.getArguments().values()) { + if (arg.getAliases().contains(x)) { +// System.out.println("ALIAS FOUND"); + x = arg.getArgName(); + } + } + } // TODO RIP ROOT ALIAS PREFIX IN FAVOR OF "--long-name" "-s (shortname)" "wildcard" + if (command.getArguments().get(x) != null) { + if (command.getArguments().get(x).isPrefixRequired()) { + Tools.wrongUsage(event.getChannel(), command); + remainsValid = false; + } if (command.getArguments().get(x).getPermission() == null - || DatabaseTools.Tools.Developers.hasPermission( - commandBlob.getAuthorID(), + || DeveloperDB.hasPermission(commandBlob.getAuthorID(), command.getArguments().get(x).getPermission())) { if (command.getArguments().get(x).isSkipOriginalTaskOnRunnable()) { remainsValid = false; @@ -210,25 +238,39 @@ public class CommandManager { Tools.invalidPermissions(event.getChannel(), command); remainsValid = false; } + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + } else { - if (positionalArgs.get(i - offset) != null) { - if (positionalArgs.get(i - offset).getPermission() == null - || DatabaseTools.Tools.Developers.hasPermission( - commandBlob.getAuthorID(), - positionalArgs.get(i - offset).getPermission())) { - if (positionalArgs.get(i - offset).isSkipOriginalTaskOnRunnable()) { + + Argument posix = positionalArgs.get(i - offset); + +// if (!command.getArguments().keySet().contains(x)) { +// for (Argument arg : command.getArguments().values()) { +// if (arg.getAliases().contains(x)) { +//// System.out.println("ALIAS FOUND"); +// x = arg.getArgName(); +// } +// } +// } // TODO RIP ROOT ALIAS PREFIX IN FAVOR OF "--long-name" "-s (shortname)" "wildcard" + + if (posix != null) { + if (posix.getPermission() == null + || DeveloperDB.hasPermission(commandBlob.getAuthorID(), + posix.getPermission())) { + if (posix.isSkipOriginalTaskOnRunnable()) { remainsValid = false; } - if (positionalArgs.get(i - offset).getIsWildcard()) { - argumentMap.put(positionalArgs.get(i - offset).getArgName(), - positionalArgs.get(i - offset).setWildCardString(x)); + if (posix.getIsWildcard()) { + argumentMap.put(posix.getArgName(), + posix.setWildCardString(x)); } else { Tools.wrongUsage(event.getChannel(), command); remainsValid = false; } - if (positionalArgs.get(i - offset).isAutoStartRunnable() - && positionalArgs.get(i - offset).getRunnableArg() != null) { - positionalArgs.get(i - offset).getRunnableArg().run(commandBlob); + if (posix.isAutoStartRunnable() + && posix.getRunnableArg() != null) { + posix.getRunnableArg().run(commandBlob); } } else { Tools.invalidPermissions(event.getChannel(), command); @@ -237,17 +279,15 @@ public class CommandManager { } else event.getChannel().sendMessage("pos is null").queue(); } - } - } else { -// Tools.wrongUsage(event.getChannel(), command); -// remainsValid = false; +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + } } } - } - if (command.getPremiumLevel() > Users.getPremiumLevel(commandBlob.getAuthorID())) { + if (command.getPremiumLevel() > UserDB.getPremiumLevel(commandBlob.getAuthorID())) { commandBlob.getChannel().sendMessage( "Sorry, but you cannot run this command, it is premium subs only, of at least tier " + command.getPremiumLevel()) @@ -296,11 +336,9 @@ public class CommandManager { if (command instanceof GuildCommandInterface && !event.isFromGuild() && !(command instanceof PrivateCommandInterface)) { event.getChannel() - .sendMessage( - "Sorry, but you need to be in a " - + (DatabaseTools.Tools.Users.isAdvancedUser( - commandBlob.getAuthorID()) ? "guild" : "server") - + " to use this command. . .") + .sendMessage("Sorry, but you need to be in a " + + (UserDB.isAdvancedUser(commandBlob.getAuthorID()) ? "guild" : "server") + + " to use this command. . .") .queue(); } else if (command instanceof PrivateCommandInterface && event.isFromGuild() && !(command instanceof GuildCommandInterface)) { diff --git a/src/pkg/deepCurse/nopalmo/manager/StatusManager.java b/src/pkg/deepCurse/nopalmo/manager/StatusManager.java index 88246ac..4ec6190 100644 --- a/src/pkg/deepCurse/nopalmo/manager/StatusManager.java +++ b/src/pkg/deepCurse/nopalmo/manager/StatusManager.java @@ -2,12 +2,12 @@ package pkg.deepCurse.nopalmo.manager; import java.util.ArrayList; import java.util.List; -import java.util.Random; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.Activity; import pkg.deepCurse.nopalmo.core.Boot; -import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Global; +import pkg.deepCurse.nopalmo.core.database.NopalmoDBTools.Tools.GlobalDB; +import pkg.deepCurse.nopalmo.global.Tools; public class StatusManager { @@ -18,25 +18,19 @@ public class StatusManager { activityList.add(Activity.watching("my lead developer eat a watermelon whole")); activityList.add(Activity.watching( Boot.bot.getUserCache().asList().size() + " users in " + Boot.bot.getGuilds().size() + " servers")); - activityList.add(Activity.watching("for " + Global.prefix + "help")); + activityList.add(Activity.watching("for " + GlobalDB.prefix + "help")); activityList.add(Activity.listening("Infected Mushroom")); -// activityList.add(EntityBuilder.createActivity("owo", null, ActivityType.CUSTOM_STATUS)); } public static void shuffle(JDA bot) { - - int rand = new Random().nextInt(activityList.size()); - + int rand = Tools.random.nextInt(activityList.size()); bot.getPresence().setActivity(activityList.get(rand)); selection = rand; - } public static void set(JDA bot, int interger) { - bot.getPresence().setActivity(activityList.get(interger)); selection = interger; - } public static void increment(JDA bot) { diff --git a/src/pkg/deepCurse/nopalmo/utils/LogHelper.java b/src/pkg/deepCurse/nopalmo/utils/LogHelper.java index 8ee3130..02c98a5 100644 --- a/src/pkg/deepCurse/nopalmo/utils/LogHelper.java +++ b/src/pkg/deepCurse/nopalmo/utils/LogHelper.java @@ -9,20 +9,15 @@ package pkg.deepCurse.nopalmo.utils; */ public class LogHelper { - public static int loggerLevel = 0; - - public static boolean bootEnabled = true; - public static boolean guildCommandManagerEnabled = true; - - public static void log(String text, Class clazz) { - log(text, 0, clazz); - } - - public static void log(String text, int level, Class clazz) { - if (bootEnabled && level <= loggerLevel) { - System.out.println(clazz + ": " + text); - } - } +// public static void log(String text, Class clazz) { +// log(text, 0, clazz); +// } +// +// public static void log(String text, int level, Class clazz) { +// if (bootEnabled && level <= loggerLevel) { +// System.out.println(clazz + ": " + text); +// } +// } public static void crash(Exception e) { e.printStackTrace();