Merge pull request #3 from lever1209/development

Development
This commit is contained in:
lever1209 2021-12-06 11:02:29 -04:00 committed by GitHub
commit da8514e44e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 1263 additions and 244 deletions

View file

@ -0,0 +1,49 @@
package pkg.deepCurse.nopalmo.command;
import java.util.HashMap;
import org.jetbrains.annotations.Nullable;
import pkg.deepCurse.nopalmo.manager.Argument;
public abstract class AbstractCommand { // TODO rewrite to implement type args?
public abstract String[] getCommandCalls();
public String getCommandName() {
return getCommandCalls()[0];
}
public boolean isNSFW() {
return false;
}
public boolean isPremium() { // im probably never gonna use this, but ill leave it in for those who want to
// see how i would implement it
return false;
}
public abstract HelpPage getHelpPage();
public enum HelpPage {
General, DEV, EGG, Moderation, Fun, Info
}
public String getHelp() {
return null;
}
public String getUsage() {
return null;
}
public int getTimeout() {
return 0;
}
@Nullable
public HashMap<String, Argument> getArguments() {
return null;
}
}

View file

@ -0,0 +1,12 @@
package pkg.deepCurse.nopalmo.command;
import java.util.HashMap;
import pkg.deepCurse.nopalmo.manager.Argument;
import pkg.deepCurse.nopalmo.manager.DirectCommandBlob;
public abstract class DirectCommand extends AbstractCommand {
public abstract void runCommand(DirectCommandBlob blob, HashMap<String, Argument> argumentList) throws Exception;
}

View file

@ -1,41 +1,23 @@
package pkg.deepCurse.nopalmo.command;
import java.util.HashMap;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import pkg.deepCurse.nopalmo.manager.CommandBlob;
import pkg.deepCurse.nopalmo.manager.GuildCommandManager;
import pkg.deepCurse.nopalmo.manager.Argument;
import pkg.deepCurse.nopalmo.manager.GuildCommandBlob;
public abstract class GuildCommand {
public abstract class GuildCommand extends AbstractCommand {
public abstract void run(CommandBlob blob, GuildMessageReceivedEvent guildMessage, GuildCommandManager commandManager) throws Exception;
public abstract void runCommand(GuildCommandBlob blob, HashMap<String, Argument> argumentList) throws Exception;
public abstract String[] getCommandCalls();
public String getCommandName() {
return getCommandCalls()[0];
}
public boolean isHidden() {
return false;
}
public boolean isNSFW() {
return false;
}
public Permission[] getRequiredPermissions() {
return null;
}
public boolean isPremium() { // im probably never gonna use this, but ill leave it in for those who want to
// see how i would implement it
return false;
public Permission getRequiredPermission() {
return null;
}
public abstract HelpPage getHelpPage();
public enum HelpPage {
General, DEV, EGG, Moderation, Fun, Info
}
}

View file

@ -0,0 +1,84 @@
package pkg.deepCurse.nopalmo.command.directCommand.info;
import java.util.HashMap;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import pkg.deepCurse.nopalmo.command.DirectCommand;
import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Global;
import pkg.deepCurse.nopalmo.manager.Argument;
import pkg.deepCurse.nopalmo.manager.DirectCommandBlob;
import pkg.deepCurse.nopalmo.utils.UptimePing;
public class DirectMessagePing extends DirectCommand {
@Override
public void runCommand(DirectCommandBlob blob,
HashMap<String, Argument> argumentMap) throws Exception {
MessageReceivedEvent event = blob.getEvent();
if (argumentMap.isEmpty()) {
event.getChannel().sendMessage("Pong!\n" + event.getJDA().getGatewayPing() + "ms\n").queue();
return;
}
if (argumentMap.get("all") != null) {
event.getChannel().sendMessage("Gathering data. . .").queue(msg -> {
long timeToProcess = System.currentTimeMillis();
try { // TODO rewrite this block, all tries are not good practice
String out = "Pong!\n" + "Google: " + UptimePing.sendPing("www.google.com") + "ms\n"
+ "JDA Gateway: " + event.getJDA().getGatewayPing() + "ms\n" + "www.discord.com: "
+ UptimePing.sendPing("www.discord.com") + "ms";
msg.editMessage(out + "\nTime to process: " + (System.currentTimeMillis() - timeToProcess) + "ms")
.queue();
} catch (Exception e) {
e.printStackTrace();
}
});
}
// if (argumentArray == null || argumentArray.isEmpty()) {
//
// return;
// } else {
//
// for (Argument i : argumentArray) {
// if (i.getArgName().contentEquals("all")) {
//
// } else {
// Tools.wrongUsage(event.getChannel(), this);
// }
// }
// return;
// }
}
@Override
public String[] getCommandCalls() {
return new String[] { "ping" };
}
@Override
public String getUsage() {
return Global.prefix + "ping [" + Argument.argumentPrefix + "all]";
}
@Override
public HelpPage getHelpPage() {
return HelpPage.Info;
}
@Override
public HashMap<String, Argument> getArguments() {
HashMap<String, Argument> args = new HashMap<String, Argument>();
args.put("all", new Argument("all").setPrefixRequirement(true));
return args;
}
}

View file

@ -1,28 +0,0 @@
package pkg.deepCurse.nopalmo.command.guildCommand;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import pkg.deepCurse.nopalmo.command.GuildCommand;
import pkg.deepCurse.nopalmo.database.DatabaseTools;
import pkg.deepCurse.nopalmo.manager.CommandBlob;
import pkg.deepCurse.nopalmo.manager.GuildCommandManager;
public class Ping extends GuildCommand {
@Override
public void run(CommandBlob blob, GuildMessageReceivedEvent guildMessage, GuildCommandManager commandManager)
throws Exception {
DatabaseTools.Tools.Guild.Prefix.createPrefix(guildMessage.getGuild().getIdLong(), blob.getArgs().get(0));
}
@Override
public String[] getCommandCalls() {
return new String[] {"ping"};
}
@Override
public HelpPage getHelpPage() {
return HelpPage.Info;
}
}

View file

@ -0,0 +1,28 @@
package pkg.deepCurse.nopalmo.command.guildCommand.info;
import java.util.HashMap;
import pkg.deepCurse.nopalmo.command.GuildCommand;
import pkg.deepCurse.nopalmo.manager.Argument;
import pkg.deepCurse.nopalmo.manager.GuildCommandBlob;
public class Git extends GuildCommand {
@Override
public void runCommand(GuildCommandBlob blob, HashMap<String, Argument> argumentList) throws Exception {
blob.getEvent().getChannel().sendMessage("Heres the link: https://github.com/lever1209/nopalmo").queue();
}
@Override
public String[] getCommandCalls() {
// TODO Auto-generated method stub
return new String[] { "git", "source", "github" };
}
@Override
public HelpPage getHelpPage() {
// TODO Auto-generated method stub
return HelpPage.Info;
}
}

View file

@ -0,0 +1,173 @@
package pkg.deepCurse.nopalmo.command.guildCommand.info;
import java.time.Instant;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import net.dv8tion.jda.api.EmbedBuilder;
import pkg.deepCurse.nopalmo.command.GuildCommand;
import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Global;
import pkg.deepCurse.nopalmo.manager.Argument;
import pkg.deepCurse.nopalmo.manager.GuildCommandBlob;
import pkg.deepCurse.nopalmo.manager.GuildCommandManager;
public class Help extends GuildCommand {
public final GuildCommandManager manager;
public Help(GuildCommandManager m) {
this.manager = m;
}
@Override
public void runCommand(GuildCommandBlob blob, HashMap<String, Argument> argumentMap) throws Exception {
if (argumentMap.isEmpty()) {
EmbedBuilder embed = new EmbedBuilder().setTitle("Commands:");
HashMap<HelpPage, String> commandHash = new HashMap<HelpPage, String>();
for (GuildCommand command : manager.getGuildCommands()) {
commandHash.put(command.getHelpPage(),
commandHash.get(command.getHelpPage()) + command.getCommandName());
}
StringBuilder sB = new StringBuilder();
GuildCommand ping = blob.getCommandManager().getCommand("ping");
if (ping != null) {
sB.append("`" + ping.getUsage() + "`\n");
}
GuildCommand help = blob.getCommandManager().getCommand("help");
if (help != null) {
sB.append("`" + help.getUsage() + "`\n");
}
embed.addField("Information:", "Commands to take note of:\n" + sB, false);
// embed.addField("Commands : ", "`"+sB.toString()+"`\n", true);
// desc.append("`").append(sB).append("`\n");
// embed.addBlankField(true);
// embed.setFooter("Command list requested by: "+event.getAuthor().getAsTag(),
// event.getAuthor().getEffectiveAvatarUrl());
embed.setFooter(blob.getEvent().getMember().getEffectiveName(),
blob.getEvent().getMember().getUser().getEffectiveAvatarUrl());
embed.setTimestamp(Instant.now());
embed.setColor(0);
if (embed.isValidLength()) {
blob.getEvent().getChannel().sendMessageEmbeds(embed.build()).queue();
} else {
blob.getEvent().getChannel()
.sendMessage(
"Critical error!\nEmbed max size exceeded, please report this to the devs immediately")
.queue();
}
if (new Random().nextLong() == 69420l) { // i wonder who will find this, also, if you read the source to
// find this, shhhhhhhh - deepCurse
blob.getEvent().getChannel().sendMessage("we will rise above you humans")
.queue(msg -> msg.delete().queueAfter(300, TimeUnit.MILLISECONDS));
}
return;
}
// ##########################################################################################################################
// ##########################################################################################################################
// ##########################################################################################################################
// ##########################################################################################################################
// ##########################################################################################################################
try {
GuildCommand command = manager.getCommand(String.join("", blob.getArgs()));
// event.getChannel().sendMessage("Command help for `" + command.commandName() +
// "`:\n\tUsage: "+ command.usageString() + "\n" +
// command.helpString()).queue();
if (command.getHelpPage() != HelpPage.EGG) {
EmbedBuilder eB = new EmbedBuilder();
eB.setTitle("Help results for: " + command.getCommandName());
if (command.getHelp() != null) {
eB.addField("Help info:", command.getHelp(), false);
}
eB.addField("Usage:", command.getUsage(), false);
eB.setFooter("Page: " + command.getHelpPage().toString());
String alias = "`";
for (int i = 1; i < command.getCommandCalls().length; i++) {
if (i == 1) {
alias += command.getCommandCalls()[i];
} else {
alias += ", " + command.getCommandCalls()[i];
}
}
alias += "`";
String endAilias = "";
if (!alias.contentEquals("``")) {
endAilias = "Aliases: " + alias + "\n";
} else {
endAilias = "Aliases: none\n";
}
eB.setColor(0);
StringBuilder sB = new StringBuilder();
sB.append(endAilias);
try {
sB.append("Required Permission: " + command.getRequiredPermission().getName() + "\n");
} catch (NullPointerException e) {
}
if (command.getTimeout() > 0) {
sB.append("Usage Timeout: " + command.getTimeout() + "\n");
}
sB.append("Premium: " + command.isPremium() + "\n");
eB.addField("Misc", sB.toString(), false);
blob.getEvent().getChannel().sendMessageEmbeds(eB.build()).queue();
} else {
throw new NullPointerException("Invalid input");
}
} catch (java.lang.NullPointerException e) {
e.printStackTrace();
blob.getEvent().getChannel()
.sendMessage("The command `" + String.join("", blob.getArgs()) + "` does not exist!\n" + "Use `"
+ Global.prefix + getCommandCalls()[0] + "` for a list of all my commands!")
.queue();
return;
}
// }
// https://download.java.net/java/GA/jdk16/7863447f0ab643c585b9bdebf67c69db/36/GPL/openjdk-16_linux-x64_bin.tar.gz
}
@Override
public HelpPage getHelpPage() {
return HelpPage.Info;
}
@Override
public String[] getCommandCalls() {
return new String[] { "help", "h" };
}
@Override
public String getHelp() {
return "The help command, it seems like you already know how to use it. . .";
}
@Override
public String getUsage() {
return Global.prefix + getCommandCalls()[0] + " [Command name]";
}
}

View file

@ -0,0 +1,94 @@
package pkg.deepCurse.nopalmo.command.guildCommand.info;
import java.util.HashMap;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import pkg.deepCurse.nopalmo.command.GuildCommand;
import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Global;
import pkg.deepCurse.nopalmo.manager.Argument;
import pkg.deepCurse.nopalmo.manager.GuildCommandBlob;
import pkg.deepCurse.nopalmo.utils.UptimePing;
public class Ping extends GuildCommand {
@Override
public void runCommand(GuildCommandBlob blob, HashMap<String, Argument> argumentMap) throws Exception {
GuildMessageReceivedEvent event = blob.getEvent();
if (argumentMap.isEmpty()) {
event.getChannel().sendMessage("Pong!\n" + event.getJDA().getGatewayPing() + "ms\n").queue();
return;
}
if (argumentMap.get("all") != null) {
event.getChannel().sendMessage("Gathering data. . .").queue(msg -> {
long timeToProcess = System.currentTimeMillis();
long jdaPing = event.getJDA().getGatewayPing();
long googlePing = -1;
try {
googlePing = UptimePing.sendPing("www.google.com");
} catch (Exception e) {
e.printStackTrace();
}
long discordPing = -1;
try {
discordPing = UptimePing.sendPing("www.discord.com");
} catch (Exception e) {
e.printStackTrace();
}
String out = "Ping:\n"
+ (googlePing > 0 ? "Google: " + googlePing + "ms\n" : "Could not connect to www.google.com\n")
+ (discordPing > 0 ? "Discord: " + discordPing + "ms\n"
: "Could not connect to www.discord.com\n")
+ "JDA-Discord heartbeat: "+jdaPing+"ms";
msg.editMessage(out + "\nTime to process: " + (System.currentTimeMillis() - timeToProcess) + "ms")
.queue();
});
}
// if (argumentArray == null || argumentArray.isEmpty()) {
//
// return;
// } else {
//
// for (Argument i : argumentArray) {
// if (i.getArgName().contentEquals("all")) {
//
// } else {
// Tools.wrongUsage(event.getChannel(), this);
// }
// }
// return;
// }
}
@Override
public String[] getCommandCalls() {
return new String[] { "ping" };
}
@Override
public String getUsage() {
return Global.prefix + "ping [" + Argument.argumentPrefix + "all]";
}
@Override
public HelpPage getHelpPage() {
return HelpPage.Info;
}
@Override
public HashMap<String, Argument> getArguments() {
HashMap<String, Argument> args = new HashMap<String, Argument>();
args.put("all", new Argument("all").setPrefixRequirement(true));
return args;
}
}

View file

@ -2,8 +2,6 @@ package pkg.deepCurse.nopalmo.core;
import java.sql.SQLException;
import javax.security.auth.login.LoginException;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity;
@ -12,55 +10,60 @@ import net.dv8tion.jda.api.utils.ChunkingFilter;
import net.dv8tion.jda.api.utils.MemberCachePolicy;
import pkg.deepCurse.nopalmo.database.DatabaseTools;
import pkg.deepCurse.nopalmo.global.Reactions;
import pkg.deepCurse.nopalmo.listener.DirectMessageReceivedListener;
import pkg.deepCurse.nopalmo.listener.GuildMessageReceivedListener;
import pkg.deepCurse.nopalmo.manager.DirectCommandManager;
import pkg.deepCurse.nopalmo.manager.GuildCommandManager;
import pkg.deepCurse.simpleLoggingGarbage.core.Log;
import pkg.deepCurse.nopalmo.utils.LogHelper;
public class Boot {
public static JDA bot;
public static DatabaseTools databaseTools = null;
public static GuildCommandManager guildCommandManager = new GuildCommandManager(); // move to master manager
public static DirectCommandManager directCommandManager = new DirectCommandManager(); // move to master manager
public static boolean isProd = false;
public static void main(String[] args) {
Log.boot("Booting. . .");
LogHelper.boot("Booting. . .");
long preBootTime = System.currentTimeMillis();
isProd = args[2].contentEquals("prod");
Log.boot("Connecting to mariadb:nopalmo");
LogHelper.boot("Connecting to mariadb:nopalmo");
try {
databaseTools = new DatabaseTools(args[1]);
Log.boot("Connected. . .");
} catch (SQLException e1) {
LogHelper.boot("Connected. . .");
} catch (SQLException | ClassNotFoundException e1) {
e1.printStackTrace();
Log.boot("Failed to connect. . .\nShutting down. . .");
LogHelper.boot("Failed to connect. . .\nShutting down. . .");
System.exit(4);
}
Log.boot("Init reaction/emote list");
LogHelper.boot("Init reaction/emote list");
Reactions.init();
Log.boot("Initialized reaction/emote list. . .");
Log.boot("Init commands list");
LogHelper.boot("Initialized reaction/emote list. . .");
LogHelper.boot("Init guild commands list");
guildCommandManager.init();
Log.boot("Initialized commands list. . .");
LogHelper.boot("Initialized guild commands list. . .");
try {
bot = JDABuilder.createDefault(args[0]).setChunkingFilter(ChunkingFilter.NONE)
.setMemberCachePolicy(MemberCachePolicy.NONE).enableIntents(GatewayIntent.GUILD_MEMBERS)
.setActivity(Activity.watching("Loading users...")).setIdle(true)
.addEventListeners(new GuildMessageReceivedListener()).build().awaitReady();
} catch (LoginException e) {
Log.crash(e);
} catch (InterruptedException e) {
e.printStackTrace();
.addEventListeners(new GuildMessageReceivedListener()).addEventListeners(new DirectMessageReceivedListener()) .build().awaitReady();
} catch (Exception e) {
LogHelper.crash(e);
}
bot.getPresence().setActivity(Activity.listening("Infected Mushroom"));
long bootTime = System.currentTimeMillis() - preBootTime;
System.out.println("Taken "+bootTime+"ms to boot");
LogHelper.boot("Taken " + bootTime + "ms to boot");
}
}

View file

@ -13,59 +13,26 @@ import org.jetbrains.annotations.Nullable;
import pkg.deepCurse.nopalmo.core.Boot;
import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Global;
import pkg.deepCurse.simpleLoggingGarbage.core.Log;
public class DatabaseTools {
private static Connection connection = null;
public DatabaseTools(String password) throws SQLException {
public DatabaseTools(String password) throws SQLException, ClassNotFoundException {
connection = createConnection(password);
Global.updatePrefix();
}
public static Connection createConnection(String password) throws SQLException {
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";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
Log.crash(e);
}
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
sqlTranslate("Generate connection", e);
throw new SQLException(e);
}
}
private static void sqlTranslate(String action, int errorCode) {
switch (errorCode) {
case 1062:
System.err.println("Failed to execute; errorCode=" + errorCode + "; ER_DUP_ENTRY; On action " + action);
break;
case 1054:
System.err.println("Failed to execute; errorCode=" + errorCode + "; ER_BAD_FIELD_ERROR; On action " + action);
break;
default:
System.err.println("Failed to execute; errorCode=" + errorCode + "; Unknown code; On action " + action);
break;
}
}
@Deprecated
private static void sqlTranslate(String action, SQLException e) {
sqlTranslate(action, e.getErrorCode());
}
private static void sqlTranslate(PreparedStatement pstmt, SQLException e) {
sqlTranslate(pstmt.toString(), e.getErrorCode());
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
private static void checkUpdateCounts(PreparedStatement pstmt, int[] updateCounts) {
@ -87,8 +54,9 @@ public class DatabaseTools {
public class Tools {
// these sub classes will represent tables and the methods therein will be for actions within said table
// these sub classes will represent tables and the methods therein will be for
// actions within said table
public class Guild {
public class Prefix {
@ -110,7 +78,7 @@ public class DatabaseTools {
return createPrefix(guildID, Global.prefix);
}
} catch (SQLException e) {
sqlTranslate(query, e.getErrorCode());
SQLCode.getMessage(query, e.getErrorCode());
return null;
} finally { // @formatter:off
try {if (rs != null)rs.close();} catch (Exception e) {}
@ -143,7 +111,7 @@ public class DatabaseTools {
// connection.commit();
return prefix;
} catch (SQLException e) {
sqlTranslate(pstmt, e);
SQLCode.sqlTranslate(pstmt, e);
for (int i : new int[] { 1062 }) {
if (i == e.getErrorCode()) {
return setPrefix(connection, guildID, prefix);
@ -181,7 +149,7 @@ public class DatabaseTools {
conn.commit();
return prefix;
} catch (SQLException e) {
sqlTranslate(pstmt, e);
SQLCode.sqlTranslate(pstmt, e);
try {
conn.rollback();
} catch (Exception e2) {
@ -212,7 +180,7 @@ public class DatabaseTools {
}
} catch (SQLException e) {
sqlTranslate(query, e.getErrorCode());
SQLCode.getMessage(query, e.getErrorCode());
// System.out.println("eeeeee");
return false;
} finally {
@ -236,7 +204,7 @@ public class DatabaseTools {
}
public class Global {
public static String prefix = null;
public static void updatePrefix() throws SQLException {
@ -257,7 +225,7 @@ public class DatabaseTools {
}
} catch (SQLException e) {
sqlTranslate(query, e.getErrorCode());
SQLCode.getMessage(query, e.getErrorCode());
// System.out.println("eeeeee");
throw new SQLException(e);
} finally {

View file

@ -0,0 +1,32 @@
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());
}
}

View file

@ -3,23 +3,23 @@ package pkg.deepCurse.nopalmo.global;
import java.util.HashMap;
public class Reactions {
private static HashMap<String, Long> reactionMap = new HashMap<String, Long>();
public static void init() {
insert("galaxyThumb", 801657838358495232L);
}
public static void insert(String input, long id) {
reactionMap.put(input, id);
}
public static String getReaction(String id) {
return ":"+id+":"+reactionMap.get(id);
return ":" + id + ":" + reactionMap.get(id);
}
public static String getEmote(String id) {
return "<:"+id+":"+reactionMap.get(id)+">";
return "<:" + id + ":" + reactionMap.get(id) + ">";
}
}

View file

@ -1,5 +1,18 @@
package pkg.deepCurse.nopalmo.global;
import net.dv8tion.jda.api.entities.MessageChannel;
import net.dv8tion.jda.api.entities.TextChannel;
import pkg.deepCurse.nopalmo.command.DirectCommand;
import pkg.deepCurse.nopalmo.command.GuildCommand;
public class Tools {
public static void wrongUsage(TextChannel tc, GuildCommand c) {
tc.sendMessage("Wrong Command Usage!\n" + c.getUsage()).queue();
}
public static void wrongUsage(MessageChannel tc, DirectCommand c) {
tc.sendMessage("Wrong Command Usage!\n" + c.getUsage()).queue();
}
}

View file

@ -0,0 +1,64 @@
package pkg.deepCurse.nopalmo.listener;
import javax.annotation.Nonnull;
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;
public class DirectMessageReceivedListener extends ListenerAdapter {
@Override
public void onReady(@Nonnull ReadyEvent event) {
System.out.println("DirectMessageReceivedListener is now ready. . .");
}
@Override
public void onMessageReceived(@Nonnull MessageReceivedEvent event) {
Message message = event.getMessage();
String messageRaw = message.getContentRaw();
System.out.println(messageRaw + "\n<@!" + event.getJDA().getSelfUser().getIdLong() + ">");
if (messageRaw.contentEquals(Global.prefix + Global.prefix)
&& DatabaseTools.Tools.Developers.canPowerOffBot(event.getAuthor().getIdLong())) {
// message.addReaction(Reactions.getReaction("galaxyThumb")).complete(); TODO re
// enable
// message.delete().complete();
// pause thread as last resort
event.getJDA().shutdown();
System.exit(0);
}
String[] prefixArray = new String[] { Global.prefix, "<@! " + event.getJDA().getSelfUser().getIdLong() + ">" };
// FIXME BROKEN PING PREFIX
boolean shouldReturn = true;
for (String i : prefixArray) { // TODO switch to [] to skip for loop?
if (messageRaw.startsWith(i)) {
// System.out.println("breaking");
shouldReturn = false;
}
}
// TODO add pre manager commands
if (shouldReturn) {
return;
}
if (!event.getAuthor().isBot() && !event.isFromGuild()) {
Boot.directCommandManager.startCommand(event);
}
}
}

View file

@ -9,11 +9,9 @@ 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.global.Reactions;
import pkg.deepCurse.nopalmo.manager.GuildCommandManager;
public class GuildMessageReceivedListener extends ListenerAdapter {
@Override
public void onReady(@Nonnull ReadyEvent event) {
System.out.println("GuildMessageReceivedListener is now ready\n" + event.getGuildAvailableCount() + "/"
@ -25,38 +23,45 @@ public class GuildMessageReceivedListener extends ListenerAdapter {
public void onGuildMessageReceived(@Nonnull GuildMessageReceivedEvent event) {
Message message = event.getMessage();
String messageRaw = message.getContentRaw();
String[] prefixArray = new String[] { DatabaseTools.Tools.Guild.Prefix.getPrefix(event.getGuild().getIdLong()),
"<@!" + event.getJDA().getSelfUser().getIdLong() + ">" };
boolean shouldReturn = true;
for (String i : prefixArray) {
if (messageRaw.startsWith(i)) {
shouldReturn = false;
}
}
if (messageRaw.contentEquals(Global.prefix + Global.prefix)
&& DatabaseTools.Tools.Developers.canPowerOffBot(event.getAuthor().getIdLong())) {
message.addReaction(Reactions.getReaction("galaxyThumb")).complete();
System.out.println("Shutting down; id " + event.getAuthor().getIdLong() + " used");
// message.addReaction(Reactions.getReaction("galaxyThumb")).complete(); TODO re
// enable
message.delete().complete();
// pause thread as last resort
event.getJDA().shutdown();
System.exit(0);
}
String[] prefixArray = new String[] { DatabaseTools.Tools.Guild.Prefix.getPrefix(event.getGuild().getIdLong()),
"<@!" + event.getJDA().getSelfUser().getIdLong() + ">" }; // FIXME BROKEN PING PREFIX
boolean shouldReturn = true;
for (String i : prefixArray) { // TODO switch to [] to skip for loop?
if (messageRaw.startsWith(i)) {
shouldReturn = false;
break;
}
}
// TODO add pre manager commands
if (shouldReturn) {
return;
}
if (!event.getAuthor().isBot()) {
Boot.guildCommandManager.startCommand(event);
}
}
}

View file

@ -0,0 +1,123 @@
package pkg.deepCurse.nopalmo.manager;
public class Argument {
// README
//
// This tool is used simply for now, but it will be worth while if you get used
// to it
//
// this allows extra organization and ease of use throughout the creation of
// commands
// instead of one simple list where if args[1] == "all" do code
// this allows the same functionality, if not more with a little bit of learning
// you can go back to what it was before, but i honestly believe this system is
// worthwhile
// it just needs polish and reports on usage for optimization
//
//// TL;DR ITS A NEW FEATURE, GIVE IT TIME
private int requiredArgs = 0;
private String argName = null;
private Argument[] subArgs = null;
private boolean requiresPrefix = false;
public static final String argumentPrefix = "-"; // This exists for the sole reason of customization and will
// generally not change, ever, its recommended you keep it to
// something other than empty to help ensure that what the user
// entered is an arg and not something else
/**
* @implNote This is an experimental feature that has potential, but i have no
* use for it currently, imagine it akin to redstone, mojang had no
* idea people would build computers or 9x9 piston doors out of it
* @param requiredArgs
* @param argName
* @param subArgs
*/
public Argument(int requiredArgs, String argName, Argument[] subArgs) {
this.requiredArgs = requiredArgs;
this.argName = argName;
this.subArgs = subArgs;
}
/**
* @implNote This is an experimental feature that has potential, but i have no
* use for it currently, imagine it akin to redstone, mojang had no
* idea people would build computers or 9x9 piston doors out of it
* @param requiredArgs
* @param argName
* @param subArgs
*/
public Argument(int requiredArgs, String argName, Argument[] subArgs, RunnableArg runnableArg) {
this.requiredArgs = requiredArgs;
this.argName = argName;
this.subArgs = subArgs;
}
/**
* @implNote This is an experimental feature that has potential, but i have no
* use for it currently, imagine it akin to redstone, mojang had no
* idea people would build computers or 9x9 piston doors out of it
* @param requiredArgs
* @param argName
* @param subArgs
*/
public Argument(String argName) {
this.argName = argName;
}
/**
* @implNote This is an experimental feature that has potential, but i have no
* use for it currently, imagine it akin to redstone, mojang had no
* idea people would build computers or 9x9 piston doors out of it
* @param requiredArgs
* @param argName
* @param subArgs
*/
public Argument(String argName, RunnableArg runnableArg) {
this.argName = argName;
}
public int getRequiredArgs() {
return requiredArgs;
}
// public Argument setRequiredArgs(int requiredArgs) {
// this.requiredArgs = requiredArgs;
// return this;
// }
public String getArgName() {
return argName;
}
// public Argument setArgName(String argName) {
// this.argName = argName;
// return this;
// }
public Argument[] getSubArgs() {
return subArgs;
}
// public Argument setSubArgs(Argument[] subArgs) {
// this.subArgs = subArgs;
// return this;
// }
public Argument setPrefixRequirement(Boolean bool) {
this.requiresPrefix = bool;
return this;
}
public boolean getPrefixRequirement() {
return this.requiresPrefix;
}
public interface RunnableArg {
public void run();
}
}

View file

@ -1,24 +0,0 @@
package pkg.deepCurse.nopalmo.manager;
import java.util.ArrayList;
public class CommandBlob {
private String modifiedRaw = null;
private String modified = null;
private ArrayList<String> args = null;
public String getModifiedMessageContents() {
return this.modified;
}
public String getModifiedRawMessageContents() {
return this.modifiedRaw;
}
public ArrayList<String> getArgs() {
return args;
}
}

View file

@ -0,0 +1,63 @@
package pkg.deepCurse.nopalmo.manager;
import java.util.ArrayList;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
public class DirectCommandBlob {
private DirectCommandManager commandManager = null;
private ArrayList<String> args = null;
private long userID = 0;
private long channelID = 0;
private MessageReceivedEvent event = null;
public DirectCommandBlob(MessageReceivedEvent event) {
setUserID(event.getAuthor().getIdLong());
setChannelID(event.getChannel().getIdLong());this.event = event;
}
public ArrayList<String> getArgs() {
return args;
}
public DirectCommandBlob setArgs(ArrayList<String> newArguments) {
this.args = newArguments;
return this;
}
public DirectCommandBlob setUserID(long userID) {
this.userID = userID;
return this;
}
public long getUserID() {
return this.userID;
}
public DirectCommandManager getCommandManager() {
return commandManager;
}
public void setCommandManager(DirectCommandManager commandManager) {
this.commandManager = commandManager;
}
public long getChannelID() {
return channelID;
}
public void setChannelID(long channelID) {
this.channelID = channelID;
}
public MessageReceivedEvent getEvent() {
return event;
}
public void setEvent(MessageReceivedEvent event) {
this.event = event;
}
}

View file

@ -0,0 +1,181 @@
package pkg.deepCurse.nopalmo.manager;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import pkg.deepCurse.nopalmo.command.DirectCommand;
import pkg.deepCurse.nopalmo.command.directCommand.info.DirectMessagePing;
import pkg.deepCurse.nopalmo.core.Boot;
import pkg.deepCurse.nopalmo.database.DatabaseTools;
import pkg.deepCurse.nopalmo.global.Tools;
public class DirectCommandManager {
private final Map<String, DirectCommand> directCommandMap = new HashMap<>();
private static Executor executor = null;
public DirectCommandManager() {
init();
executor = Executors.newSingleThreadExecutor();
}
public void init() {
addCommand(new DirectMessagePing());
}
private void addCommand(DirectCommand c) {
if (!directCommandMap.containsKey(c.getCommandName())) {
directCommandMap.put(c.getCommandName(), c);
} else {
directCommandMap.remove(c.getCommandName());
directCommandMap.put(c.getCommandName(), c);
}
}
public Collection<DirectCommand> getDirectCommands() {
return directCommandMap.values();
}
public DirectCommand getCommand(String commandName) {
if (commandName != null) {
return directCommandMap.get(commandName);
}
return null;
}
public void startCommand(MessageReceivedEvent messageReceivedEvent) {
final String message = messageReceivedEvent.getMessage().getContentRaw();
final String[] split = message.replaceFirst("(?i)" + Pattern.quote(DatabaseTools.Tools.Global.prefix), "")
.split("\\s+");
final String command = split[0].toLowerCase();
if (directCommandMap.containsKey(command)) {
final List<String> args = Arrays.asList(split).subList(1, split.length);
executor.execute(() -> {
long commandStartTime = System.currentTimeMillis();
try {
// ArrayList<String> newArguments = new ArrayList<String>();
// ArrayList<String> commandFlags = new ArrayList<String>();
DirectCommandBlob commandBlob = new DirectCommandBlob(messageReceivedEvent);
DirectCommand directCommand = directCommandMap.get(command);
HashMap<String, Argument> argumentList = new HashMap<String, Argument>();
boolean printTime = false;
byte argSkipCount = 0;
boolean remainsValid = true;
for (String x : args) {
x = x.toLowerCase();
switch (x) {
case "\\time":
printTime = true;
break;
case "\\perm":
// commandFlags.add("user:380045419381784576");
commandBlob.setUserID(380045419381784576L);
break;
case "\\del":
messageReceivedEvent.getMessage().delete().queue();
break;
default: // in the rewrite process
if (argSkipCount <= 0) {
if (directCommand.getArguments() != null) {
if (x.startsWith(Argument.argumentPrefix)) {
String pre = x.substring(Argument.argumentPrefix.length());
if (directCommand.getArguments().keySet().contains(pre)) {
argumentList.put(pre, directCommand.getArguments().get(pre));
} else {
Tools.wrongUsage(messageReceivedEvent.getChannel(), directCommand);
remainsValid = false;
}
} else {
if (directCommand.getArguments().get(x).getPrefixRequirement()) {
Tools.wrongUsage(messageReceivedEvent.getChannel(), directCommand);
remainsValid = false;
} else {
argumentList.put(x, directCommand.getArguments().get(x));
}
}
}
//
// if (guildCommand.getArguments() != null) {
//
// String newArg = x;
//
// if (!newArg.startsWith(Argument.argumentPrefix)) {
// if (guildCommand.getArguments().get(newArg)!=null) {
//
// }
// }
//
// if (guildCommand.getArguments().containsKey(newArg)) {
//
// argumentList.put(guildCommand.getArguments().get(newArg).getArgName(),
// guildCommand.getArguments().get(newArg));
// } else
//
// argumentList.put(newArg, new Argument(newArg));
// }
}
}
}
commandBlob.setCommandManager(this);
if (remainsValid) {
directCommand.runCommand(commandBlob, argumentList);
}
if (printTime) {
messageReceivedEvent.getChannel()
.sendMessage("Time to run: " + (System.currentTimeMillis() - commandStartTime) + "ms")
.queue();
}
} catch (Exception e) {
if (Boot.isProd) {
messageReceivedEvent.getChannel().sendMessage("```properties\n" + e + "```").queue();
} else {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
messageReceivedEvent.getChannel().sendMessage("```properties\n" + sw.toString() + "```").queue();
System.err.println("Exception caught in: " + e.toString());
e.printStackTrace();
}
} catch (Throwable t) {
if (Boot.isProd) {
messageReceivedEvent.getChannel().sendMessage("```mathematica\n" + t + "```").queue();
} else {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
messageReceivedEvent.getChannel().sendMessage("```mathematica\n" + sw.toString() + "```").queue();
System.err.println("Error caught in: " + t.toString());
t.printStackTrace();
}
}
});
}
}
}

View file

@ -0,0 +1,61 @@
package pkg.deepCurse.nopalmo.manager;
import java.util.ArrayList;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
public class GuildCommandBlob {
private GuildCommandManager commandManager = null;
private ArrayList<String> args = null;
private long userID = 0;
private long channelID = 0;
private GuildMessageReceivedEvent event = null;
public GuildCommandBlob(GuildMessageReceivedEvent event) {
this.event = event;
setUserID(event.getAuthor().getIdLong());
setChannelID(event.getChannel().getIdLong());
}
public ArrayList<String> getArgs() {
return args;
}
public GuildCommandBlob setArgs(ArrayList<String> newArguments) {
this.args = newArguments;
return this;
}
public GuildCommandBlob setUserID(long userID) {
this.userID = userID;
return this;
}
public long getUserID() {
return this.userID;
}
public GuildCommandManager getCommandManager() {
return commandManager;
}
public void setCommandManager(GuildCommandManager commandManager) {
this.commandManager = commandManager;
}
public long getChannelID() {
return channelID;
}
public void setChannelID(long channelID) {
this.channelID = channelID;
}
public GuildMessageReceivedEvent getEvent() {
return event;
}
}

View file

@ -2,9 +2,10 @@ package pkg.deepCurse.nopalmo.manager;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
@ -12,14 +13,17 @@ import java.util.regex.Pattern;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import pkg.deepCurse.nopalmo.command.GuildCommand;
import pkg.deepCurse.nopalmo.command.guildCommand.Ping;
import pkg.deepCurse.nopalmo.command.guildCommand.info.Git;
import pkg.deepCurse.nopalmo.command.guildCommand.info.Help;
import pkg.deepCurse.nopalmo.command.guildCommand.info.Ping;
import pkg.deepCurse.nopalmo.core.Boot;
import pkg.deepCurse.nopalmo.database.DatabaseTools;
import pkg.deepCurse.nopalmo.global.Tools;
public class GuildCommandManager {
private final Map<String, GuildCommand> guildCommandMap = new HashMap<>();
Executor executor = null;
private static Executor executor = null;
public GuildCommandManager() {
init();
@ -27,7 +31,9 @@ public class GuildCommandManager {
}
public void init() {
addCommand(new Help(this));
addCommand(new Ping());
addCommand(new Git());
}
private void addCommand(GuildCommand c) {
@ -39,7 +45,7 @@ public class GuildCommandManager {
}
}
public Collection<GuildCommand> getguildCommandMap() {
public Collection<GuildCommand> getGuildCommands() {
return guildCommandMap.values();
}
@ -58,42 +64,120 @@ public class GuildCommandManager {
.split("\\s+");
final String command = split[0].toLowerCase();
executor.execute(() -> {
long commandStartTime = System.currentTimeMillis();
if (guildCommandMap.containsKey(command)) {
final List<String> args = Arrays.asList(split).subList(1, split.length);
try {
ArrayList<String> newArguments = new ArrayList<String>();
ArrayList<String[]> extractedFlags = new ArrayList<String[]>();
} catch (Exception e) {
if (Boot.isProd) {
guildMessage.getChannel().sendMessage("```\n" + e + "```").queue();
} else {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
guildMessage.getChannel().sendMessage("```\n" + sw.toString() + "```").queue();
System.err.println("Exception caught in: " + e.toString());
e.printStackTrace();
executor.execute(() -> {
long commandStartTime = System.currentTimeMillis();
try {
// ArrayList<String> newArguments = new ArrayList<String>();
// ArrayList<String> commandFlags = new ArrayList<String>();
GuildCommandBlob commandBlob = new GuildCommandBlob(guildMessage);
GuildCommand guildCommand = guildCommandMap.get(command);
HashMap<String, Argument> argumentList = new HashMap<String, Argument>();
boolean printTime = false;
byte argSkipCount = 0;
boolean remainsValid = true;
for (String x : args) {
x = x.toLowerCase();
switch (x) {
case "\\time":
printTime = true;
break;
case "\\perm":
// commandFlags.add("user:380045419381784576");
commandBlob.setUserID(380045419381784576L);
break;
case "\\del":
guildMessage.getMessage().delete().queue();
break;
default: // in the rewrite process
if (argSkipCount <= 0) {
if (guildCommand.getArguments() != null) {
if (x.startsWith(Argument.argumentPrefix)) {
String pre = x.substring(Argument.argumentPrefix.length());
if (guildCommand.getArguments().keySet().contains(pre)) {
argumentList.put(pre, guildCommand.getArguments().get(pre));
} else {
Tools.wrongUsage(guildMessage.getChannel(), guildCommand);
remainsValid = false;
}
} else {
if (guildCommand.getArguments().get(x).getPrefixRequirement()) {
Tools.wrongUsage(guildMessage.getChannel(), guildCommand);
remainsValid = false;
} else {
argumentList.put(x, guildCommand.getArguments().get(x));
}
}
}
//
// if (guildCommand.getArguments() != null) {
//
// String newArg = x;
//
// if (!newArg.startsWith(Argument.argumentPrefix)) {
// if (guildCommand.getArguments().get(newArg)!=null) {
//
// }
// }
//
// if (guildCommand.getArguments().containsKey(newArg)) {
//
// argumentList.put(guildCommand.getArguments().get(newArg).getArgName(),
// guildCommand.getArguments().get(newArg));
// } else
//
// argumentList.put(newArg, new Argument(newArg));
// }
}
}
}
commandBlob.setCommandManager(this);
if (remainsValid) {
guildCommand.runCommand(commandBlob, argumentList);
}
if (printTime) {
guildMessage.getChannel()
.sendMessage("Time to run: " + (System.currentTimeMillis() - commandStartTime) + "ms")
.queue();
}
} catch (Exception e) {
if (Boot.isProd) {
guildMessage.getChannel().sendMessage("```properties\n" + e + "```").queue();
} else {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
guildMessage.getChannel().sendMessage("```properties\n" + sw.toString() + "```").queue();
System.err.println("Exception caught in: " + e.toString());
e.printStackTrace();
}
} catch (Throwable t) {
if (Boot.isProd) {
guildMessage.getChannel().sendMessage("```mathematica\n" + t + "```").queue();
} else {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
guildMessage.getChannel().sendMessage("```mathematica\n" + sw.toString() + "```").queue();
System.err.println("Error caught in: " + t.toString());
t.printStackTrace();
}
}
} catch (Throwable t) {
if (Boot.isProd) {
guildMessage.getChannel().sendMessage("```\n" + t + "```").queue();
} else {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
guildMessage.getChannel().sendMessage("```\n" + sw.toString() + "```").queue();
System.err.println("Error caught in: " + t.toString());
t.printStackTrace();
}
}
});
});
}
}
}

View file

@ -0,0 +1,43 @@
package pkg.deepCurse.nopalmo.utils;
import pkg.deepCurse.nopalmo.core.Boot;
/**
* this class exists for the sole reason of im lazy, as far as i know, this is
* really bad practice and i will replace it at some point, or at least upgrade
* it, who knows really
*
* @author deepCurse
*/
public class LogHelper {
public static int loggerLevel = 0;
public static boolean bootEnabled = true;
public static boolean guildCommandManagerEnabled = true;
public static void boot(String text) {
boot(text, 0);
}
public static void boot(String text, int level) {
if (bootEnabled && level <= loggerLevel) {
System.out.println(Boot.class + ": " + text);
}
}
public static void crash(Exception e) {
e.printStackTrace();
System.exit(69420);
}
public static void guildCommandManager(String text) {
guildCommandManager(text);
}
public static void guildCommandManager(String text, int level) {
if (guildCommandManagerEnabled && level <= loggerLevel) {
System.out.println(Boot.class + ": " + text);
}
}
}

View file

@ -0,0 +1,38 @@
package pkg.deepCurse.nopalmo.utils;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.channels.SocketChannel;
import java.util.Date;
public class UptimePing {
public static long sendPing(String IP) throws Exception {
int port = 80;
long timeToRespond = 0;
InetAddress inetAddress = InetAddress.getByName(IP);
InetSocketAddress socketAddress = new InetSocketAddress(inetAddress, port);
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(true);
Date start = new Date();
if (sc.connect(socketAddress)) {
Date stop = new Date();
timeToRespond = (stop.getTime() - start.getTime());
}
// System.out.println("fix me"); // not sure why this is here
if (socketAddress.getAddress() == null) {
return -1;
} else {
return timeToRespond;
}
}
}

View file

@ -1,29 +0,0 @@
package pkg.deepCurse.simpleLoggingGarbage.core;
import javax.security.auth.login.LoginException;
/**
* this class exists for the sole reason of im lazy, as far as i know, this is
* really bad practice and i will replace it at some point, or at least upgrade
* it, who knows really
*
* @author deepCurse
*/
public class Log {
public static int loggerLevel = 0;
//@formatter:off
public static boolean bootEnabled = true;
public static void boot(String text) {
boot(text,0);
}
public static void boot(String text, int level) {
if (bootEnabled && level <= loggerLevel) {
System.out.println(text);
}
}
//@formatter:on
public static void crash(Exception e) {
}
}