some sheeet

added a lock and finished the broken half created command manager (for
now)

Signed-off-by: deepCurse <leverplays@gmail.com>
This commit is contained in:
lever1209 2021-12-07 16:01:12 -04:00
commit 7a57e8a39d
No known key found for this signature in database
GPG key ID: EEBCBB60C9DFC782
14 changed files with 298 additions and 103 deletions

4
exit-codes.txt Normal file
View file

@ -0,0 +1,4 @@
3 : Failed to lock
4 : Failed to connect to maria
7 : Shut down by developer
8 : LoggerHelper.crash(Exception e);

View file

@ -27,6 +27,7 @@ public class Prefix implements GuildCommandInterface {
Guild.Prefix.setPrefix(
blob.getEvent().getGuild().getIdLong(), argumentList.get("prefix").getWildCardString());
blob.getEvent().getChannel().sendMessage("Set prefix to " + argumentList.get("prefix").getWildCardString()).queue();
blob.getChannel().sendMessage("Remember: you can always ping me to use any command in case you forget the prefix").queue();
} else {
Guild.Prefix.setPrefix(
blob.getEvent().getGuild().getIdLong(), Global.prefix);

View file

@ -8,6 +8,7 @@ import java.util.List;
import net.dv8tion.jda.api.EmbedBuilder;
import pkg.deepCurse.nopalmo.command.CommandInterface.GuildCommandInterface;
import pkg.deepCurse.nopalmo.database.DatabaseTools.Tools.Global;
import pkg.deepCurse.nopalmo.global.Tools;
import pkg.deepCurse.nopalmo.manager.Argument;
import pkg.deepCurse.nopalmo.manager.CommandBlob;
import pkg.deepCurse.nopalmo.manager.GuildCommandBlob;
@ -24,8 +25,17 @@ public class Help implements GuildCommandInterface {
@Override
public void runGuildCommand(GuildCommandBlob blob, HashMap<String, Argument> argumentMap) throws Exception {
if (argumentMap.isEmpty() || argumentMap.get("dev") != null) {
EmbedBuilder embed = new EmbedBuilder().setTitle("Commands:");
boolean isDevEnabled = argumentMap.get("dev") != null;
final List<HelpPage> deniedPages = new ArrayList<HelpPage>();
deniedPages.add(HelpPage.DEV);
deniedPages.add(HelpPage.EGG);
deniedPages.add(HelpPage.TESTING);
// System.out.println(argumentMap.size()+":"+devEnabled+"\n"+argumentMap.toString());
if (argumentMap.isEmpty() || (isDevEnabled && argumentMap.size() == 1)) {
EmbedBuilder embed = new EmbedBuilder().setTitle(isDevEnabled ? "^Commands:" : "Commands:");
HashMap<HelpPage, List<String>> commandHash = new HashMap<HelpPage, List<String>>();
@ -40,8 +50,7 @@ public class Help implements GuildCommandInterface {
}
for (HelpPage i : HelpPage.values()) {
if ((i == HelpPage.DEV || i == HelpPage.TESTING || i == HelpPage.EGG)
&& argumentMap.get("dev") == null) {
if (deniedPages.contains(i) && argumentMap.get("dev") == null) {
} else if (commandHash.get(i) != null) {
@ -93,69 +102,65 @@ public class Help implements GuildCommandInterface {
embed.setTimestamp(Instant.now());
embed.setColor(0);
blob.getEvent().getChannel().sendMessageEmbeds(embed.build()).queue();
blob.getChannel().sendMessageEmbeds(embed.build()).queue();
return;
} else if (argumentMap.get("commandName") != null) {
GuildCommandInterface command = manager.getCommand(argumentMap.get("commandName").getWildCardString());
if (command.getHelpPage() != HelpPage.EGG) {
if (command != null && ((deniedPages.contains(command.getHelpPage()) && isDevEnabled)
|| !deniedPages.contains(command.getHelpPage()))) {
if (!command.isNSFW()) {
EmbedBuilder eB = new EmbedBuilder();
eB.setColor(0);
StringBuilder sB = new StringBuilder();
eB.setTitle("Help results for: " + command.getCommandName());
if (command.getHelp() != null) {
eB.addField("Help info:", command.getHelp(), false);
} else {
eB.addField("Help info:", "This command does not contain help information", false);
}
eB.addField("Usage:", command.getUsage(), false);
eB.setFooter("Page: " + command.getHelpPage().toString());
String alias = "`";
if (command.getCommandCalls().length > 1) {
for (int i = 1; i < command.getCommandCalls().length; i++) {
if (i == 1) {
alias += command.getCommandCalls()[i];
} else {
alias += ", " + command.getCommandCalls()[i];
sB.append("`"+command.getCommandCalls()[i]+"` ");
}
sB.append("\n");
}
alias += "`";
String endAilias = "";
if (!alias.contentEquals("``")) {
endAilias = "Aliases: " + alias + "\n";
} else {
endAilias = "Aliases: none\n";
if (command.isNSFW()) {
sB.append("Is nsfw: "+command.isNSFW());
}
eB.setColor(0);
StringBuilder sB = new StringBuilder();
sB.append(endAilias);
try {
if (command.getRequiredPermission() != null) {
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();
blob.getChannel().sendMessageEmbeds(eB.build()).queue();
} else {
throw new NullPointerException("Invalid input");
blob.getChannel().sendMessage("Sorry, but you are not allowed to view information about that command here, try somewhere more private").queue();
}
} else {
// Tools.wrongUsage(blob.getChannel(), command);
blob.getChannel().sendMessage(
"Sorry, but there is no command named: " + argumentMap.get("commandName").getWildCardString())
.queue();
}
}
// ##########################################################################################################################
// ##########################################################################################################################
// ##########################################################################################################################
// ##########################################################################################################################
// ##########################################################################################################################
// }
// https://download.java.net/java/GA/jdk16/7863447f0ab643c585b9bdebf67c69db/36/GPL/openjdk-16_linux-x64_bin.tar.gz
}
@Override
@ -191,8 +196,8 @@ public class Help implements GuildCommandInterface {
args.put("commandName", new Argument("commandName").setPosition(0).setIsWildcard(true));
args.put("dev", new Argument("dev", (CommandBlob blob) -> {
blob.getChannel().sendMessage("dev").queue();
}).setPrefixRequirement(true).setAutoStartRunnable(true));
blob.getChannel().sendMessage("DEV FLAG USED").queue();
}).setPrefixRequirement(true).setAutoStartRunnable(true).setPermissionLevel("infopermission"));
return args;
}

View file

@ -14,6 +14,7 @@ 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.nopalmo.utils.Locks;
import pkg.deepCurse.nopalmo.utils.LogHelper;
public class Boot {
@ -25,8 +26,23 @@ public class Boot {
public static boolean isProd = false;
public static long pid = ProcessHandle.current().pid();
public static void main(String[] args) {
LogHelper.boot("Booting. . .");
LogHelper.boot("Booting: <" + pid + ">");
LogHelper.boot("Testing Lock. . .");
try {
if (Locks.dirLock("nopalmo.lock")) {
LogHelper.boot("Failed to lock. . .\nShutting down. . .");
System.exit(3);
} else {
LogHelper.boot("Nopalmo is locked. . .");
}
} catch (Exception e) {
LogHelper.crash(e);
}
long preBootTime = System.currentTimeMillis();
@ -38,7 +54,7 @@ public class Boot {
LogHelper.boot("Connected. . .");
} catch (SQLException | ClassNotFoundException e1) {
e1.printStackTrace();
LogHelper.boot("Failed to connect. . .\nShutting down. . .");
LogHelper.boot("Failed to connect\nShutting down. . .");
System.exit(4);
}
@ -49,11 +65,19 @@ public class Boot {
guildCommandManager.init();
LogHelper.boot("Initialized guild commands list. . .");
try {
LogHelper.boot("Sleeping");
Thread.sleep(90000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
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()).addEventListeners(new DirectMessageReceivedListener()) .build().awaitReady();
.addEventListeners(new GuildMessageReceivedListener())
.addEventListeners(new DirectMessageReceivedListener()).build().awaitReady();
} catch (Exception e) {
LogHelper.crash(e);
}
@ -64,6 +88,8 @@ public class Boot {
LogHelper.boot("Taken " + bootTime + "ms to boot");
LogHelper.boot("Starting loop");
}
}

View file

@ -126,8 +126,7 @@ public class DatabaseTools {
}
}
public static String setPrefix(long guildID, String prefix)
throws IllegalArgumentException {
public static String setPrefix(long guildID, String prefix) throws IllegalArgumentException {
if (prefix.isEmpty()) {
throw new IllegalArgumentException("Input cannot be empty");
@ -163,7 +162,7 @@ public class DatabaseTools {
public class Developers {
public static boolean canPowerOffBot(long userID) {
public static boolean getDeveloperBoolean(long userID, String key) {
Statement st = null;
ResultSet rs = null;
String query = "select * from developers where userid = " + userID;
@ -171,7 +170,7 @@ public class DatabaseTools {
st = connection.createStatement();
rs = st.executeQuery(query);
if (rs.next()) {
return rs.getBoolean("canpoweroffbot");
return rs.getBoolean(key);
} else {
// throw new SQLException(null, null, 33); // we need a real catcher here
System.err
@ -201,6 +200,56 @@ public class DatabaseTools {
// 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());
// System.out.println("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 {

View file

@ -9,6 +9,10 @@ public class Tools {
messageChannel.sendMessage("Wrong Command Usage!\n" + command.getUsage()).queue();
}
public static void invalidPermissions(MessageChannel messageChannel, CommandInterface command) {
messageChannel.sendMessage("Sorry, but you are not allowed to use that! Try this:\n" + command.getUsage()).queue();
}
// public static void wrongUsage(MessageChannel tc, DirectCommandInterface c) {
// tc.sendMessage("Wrong Command Usage!\n" + c.getUsage()).queue();
// }

View file

@ -29,7 +29,7 @@ public class DirectMessageReceivedListener extends ListenerAdapter {
// TODO re enable
event.getJDA().shutdown();
System.exit(0);
System.exit(7);
}
String[] prefixArray = new String[] { Global.prefix, "<@! " + event.getJDA().getSelfUser().getIdLong() + ">" };

View file

@ -33,7 +33,7 @@ public class GuildMessageReceivedListener extends ListenerAdapter {
message.delete().complete();
event.getJDA().shutdown();
System.exit(0);
System.exit(7);
}
if (!event.getAuthor().isBot()) {

View file

@ -27,6 +27,7 @@ public class Argument {
private boolean autoStartRunnable = false;
private boolean skipOriginalTaskOnRunnable = false;
private RunnableArg runnableArg = null;
private String permissionLevel;
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
@ -183,4 +184,13 @@ public class Argument {
return runnableArg;
}
public Argument setPermissionLevel(String string) {
this.permissionLevel = string;
return this;
}
public String getPermission() {
return this.permissionLevel;
}
}

View file

@ -2,12 +2,15 @@ package pkg.deepCurse.nopalmo.manager;
import java.util.ArrayList;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
public class GuildCommandBlob {
private GuildCommandManager commandManager = null;
private ArrayList<String> args = null;
private JDA bot = null;
private long userID = 0;
private long channelID = 0;
@ -18,6 +21,7 @@ public class GuildCommandBlob {
this.event = event;
setUserID(event.getAuthor().getIdLong());
setChannelID(event.getChannel().getIdLong());
this.bot = event.getJDA();
}
public ArrayList<String> getArgs() {
@ -29,6 +33,14 @@ public class GuildCommandBlob {
return this;
}
public TextChannel getChannel() {
TextChannel textChannel = bot.getTextChannelById(channelID);
if (textChannel != null){
return textChannel;
}
return null;
}
public GuildCommandBlob setUserID(long userID) {
this.userID = userID;
return this;

View file

@ -2,6 +2,7 @@ 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;
@ -114,6 +115,9 @@ public class GuildCommandManager extends CommandManager {
}
}
List<String> newArgs = new ArrayList<String>();
int offset = 0;
for (int i = 0; i < args.size(); i++) {
String x = args.get(i);
x = x.toLowerCase();
@ -128,62 +132,90 @@ public class GuildCommandManager extends CommandManager {
guildMessageEvent.getMessage().delete().queue();
break;
default:
newArgs.add(x);
break;
}
}
// split up so global commands are actually global, and will not be affected by
// neighboring local args
for (int i = 0; i < newArgs.size(); i++) {
String x = newArgs.get(i);
x = x.toLowerCase();
if (argSkipCount <= 0) {
if (guildCommand.getArguments() != null) {
// if (positionalArgs.get(i) == null) {
if (x.startsWith(Argument.argumentPrefix)) {
String pre = x.substring(Argument.argumentPrefix.length());
if (guildCommand.getArguments().keySet().contains(pre)) {
offset++;
if (guildCommand.getArguments().get(pre).getPermission() == null
|| DatabaseTools.Tools.Developers.hasPermission(commandBlob.getUserID(),
guildCommand.getArguments().get(pre).getPermission())) {
argumentList.put(pre, guildCommand.getArguments().get(pre));
if (guildCommand.getArguments().get(pre).isAutoStartRunnable()
&& guildCommand.getArguments().get(pre)
.getRunnableArg() != null) {
&& guildCommand.getArguments().get(pre).getRunnableArg() != null) {
guildCommand.getArguments().get(pre).getRunnableArg()
.run(new CommandBlob(commandBlob));
}
} else {
Tools.invalidPermissions(guildMessageEvent.getChannel(), guildCommand);
remainsValid = false;
}
} else {
Tools.wrongUsage(guildMessageEvent.getChannel(), guildCommand);
remainsValid = false;
}
} else {
if (guildCommand.getArguments().get(x) != null) {
if (guildCommand.getArguments().get(x).getPrefixRequirement()) {
Tools.wrongUsage(guildMessageEvent.getChannel(), guildCommand);
remainsValid = false;
} else {
if (guildCommand.getArguments().get(x).getPermission() == null
|| DatabaseTools.Tools.Developers.hasPermission(commandBlob.getUserID(),
guildCommand.getArguments().get(x).getPermission())) {
argumentList.put(x, guildCommand.getArguments().get(x));
offset++;
if (guildCommand.getArguments().get(x).isAutoStartRunnable()
&& guildCommand.getArguments().get(x)
.getRunnableArg() != null) {
&& guildCommand.getArguments().get(x).getRunnableArg() != null) {
guildCommand.getArguments().get(x).getRunnableArg()
.run(new CommandBlob(commandBlob));
}
} else {
Tools.invalidPermissions(guildMessageEvent.getChannel(), guildCommand);
remainsValid = false;
}
} else {
if (positionalArgs.get(i).getIsWildcard()) {
argumentList.put(positionalArgs.get(i).getArgName(),
positionalArgs.get(i).setWildCardString(x));
if (positionalArgs.get(i - offset) != null) {
if (positionalArgs.get(i - offset).getPermission() == null
|| DatabaseTools.Tools.Developers.hasPermission(
commandBlob.getUserID(),
positionalArgs.get(i - offset).getPermission())) {
if (positionalArgs.get(i - offset).getIsWildcard()) {
argumentList.put(positionalArgs.get(i - offset).getArgName(),
positionalArgs.get(i - offset).setWildCardString(x));
} else {
Tools.wrongUsage(guildMessageEvent.getChannel(), guildCommand);
remainsValid = false;
}
if (positionalArgs.get(i).isAutoStartRunnable()
&& positionalArgs.get(i).getRunnableArg() != null) {
positionalArgs.get(i).getRunnableArg()
if (positionalArgs.get(i - offset).isAutoStartRunnable()
&& positionalArgs.get(i - offset).getRunnableArg() != null) {
positionalArgs.get(i - offset).getRunnableArg()
.run(new CommandBlob(commandBlob));
}
} else {
Tools.invalidPermissions(guildMessageEvent.getChannel(), guildCommand);
remainsValid = false;
}
} else
guildMessageEvent.getChannel().sendMessage("pos is null").queue();
}
}
// }
} else {
Tools.wrongUsage(guildMessageEvent.getChannel(), guildCommand);
remainsValid = false;
}
}
}
}
commandBlob.setCommandManager(this);

View file

@ -0,0 +1,52 @@
package pkg.deepCurse.nopalmo.utils;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Scanner;
import pkg.deepCurse.nopalmo.core.Boot;
public class Locks {
/**
*
* @param lockName
* @return true on exists, false on vacant
* @throws Exception
*/
public static boolean dirLock(String lockName) throws Exception {
long pid = 0L;
Scanner pidScanner = new Scanner(new File(System.getProperty("user.dir") + "/" + lockName));
StringBuilder pidBuilder = new StringBuilder();
while (pidScanner.hasNext()) {
pidBuilder.append(pidScanner.next());
}
pidScanner.close();
pid = Long.parseLong(pidBuilder.toString().replaceAll("[^0-9]", ""));
Process proc = new ProcessBuilder().command("readlink", "/proc/" + pid + "/cwd").start();
Scanner readlinkScanner = new Scanner(new InputStreamReader(proc.getInputStream()));
StringBuilder readlinkBuilder = new StringBuilder();
while (readlinkScanner.hasNext()) {
readlinkBuilder.append(readlinkScanner.next());
}
readlinkScanner.close();
if (readlinkBuilder.toString().contentEquals(new File(System.getProperty("user.dir")).getPath())) {
return true;
} else {
FileWriter writer = new FileWriter(new File(System.getProperty("user.dir") + "/" + lockName));
writer.write(String.valueOf(Boot.pid));
writer.close();
return false;
}
}
}

View file

@ -28,7 +28,7 @@ public class LogHelper {
public static void crash(Exception e) {
e.printStackTrace();
System.exit(69420);
System.exit(8);
}
public static void guildCommandManager(String text) {