Finish implementing configuration file
All checks were successful
continuous-integration/drone/push Build is passing

Configuration file is now fully functional.
Startup arguments for bot token and heartbeat key have now been removed.
This commit is contained in:
Bea 2022-11-22 00:04:34 +01:00
parent b6bf366822
commit 843ee43275
6 changed files with 57 additions and 49 deletions

View File

@ -5,8 +5,10 @@ import org.jetbrains.annotations.Nullable;
import wtf.beatrice.hidekobot.database.DatabaseManager; import wtf.beatrice.hidekobot.database.DatabaseManager;
import wtf.beatrice.hidekobot.listeners.MessageLogger; import wtf.beatrice.hidekobot.listeners.MessageLogger;
import wtf.beatrice.hidekobot.utils.ConfigurationManager; import wtf.beatrice.hidekobot.utils.ConfigurationManager;
import wtf.beatrice.hidekobot.utils.Logger;
import java.awt.*; import java.awt.*;
import java.lang.reflect.Field;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
@ -15,13 +17,13 @@ import java.util.List;
public class Cache public class Cache
{ {
private static final Logger logger = new Logger(Cache.class);
private static ConfigurationManager configManager = null; private static ConfigurationManager configManager = null;
private static DatabaseManager dbManager = null; private static DatabaseManager dbManager = null;
private static boolean verbose = false; private static boolean verbose = false;
private static MessageLogger verbosityLogger; private static MessageLogger verbosityLogger;
private static final long botMaintainerId = 979809420714332260L; private static final long botMaintainerId = 979809420714332260L;
private static long botOwnerId = 0L;
private final static String expiryTimestampFormat = "yy/MM/dd HH:mm:ss"; private final static String expiryTimestampFormat = "yy/MM/dd HH:mm:ss";
// note: discord sets interactions' expiry time to 15 minutes by default, so we can't go higher than that. // note: discord sets interactions' expiry time to 15 minutes by default, so we can't go higher than that.
@ -30,16 +32,10 @@ public class Cache
// used to count eg. uptime // used to count eg. uptime
private static LocalDateTime startupTime; private static LocalDateTime startupTime;
// todo: allow people to set their own url
private static final String heartbeatLink = "https://status.beatrice.wtf/api/push/%apikey%?status=up&msg=OK&ping=";
private static String heartbeatApiKey = "";
private final static String execPath = System.getProperty("user.dir"); private final static String execPath = System.getProperty("user.dir");
private static final String botVersion = "0.1.5-slash"; // we should probably find a way to make this consistent with Maven private static final String botVersion = "0.1.5-slash"; // we should probably find a way to make this consistent with Maven
private static final String botName = "HidekoBot"; private static final String botName = "HidekoBot";
private static final Color botColor = Color.PINK;
private static List<Command> registeredCommands = new ArrayList<>(); private static List<Command> registeredCommands = new ArrayList<>();
private final static String defaultInviteLink = private final static String defaultInviteLink =
@ -97,7 +93,19 @@ public class Cache
* *
* @return a long of the account's id * @return a long of the account's id
*/ */
public static long getBotOwnerId() { return botOwnerId; } public static long getBotOwnerId() {
return configManager == null ? 0L : (Long) configManager.getConfigValue("bot-owner-id");
}
/**
* Get the bot's token.
*
* @return a String of the bot's token.
*/
public static String getBotToken() {
return configManager == null ? null : (String) configManager.getConfigValue("bot-token");
}
/** /**
* Get the bot maintainer's profile id. * Get the bot maintainer's profile id.
@ -179,7 +187,20 @@ public class Cache
* *
* @return the Color object. * @return the Color object.
*/ */
public static Color getBotColor() { return botColor; } public static Color getBotColor() {
Color defaultColor = Color.PINK;
if(configManager == null) return defaultColor;
String colorName = (String) configManager.getConfigValue("bot-color");
Color color = null;
try {
Field field = Color.class.getField(colorName);
color = (Color)field.get(null);
} catch (Exception e) {
logger.log("Unknown color: " + colorName);
}
return color == null ? defaultColor : color;
}
/** /**
* Set the list of registered commands. They will be sorted alphabetically. * Set the list of registered commands. They will be sorted alphabetically.
@ -225,18 +246,12 @@ public class Cache
public static LocalDateTime getStartupTime() { return startupTime; } public static LocalDateTime getStartupTime() { return startupTime; }
public static String getFullHeartBeatLink() { public static String getFullHeartBeatLink() {
return heartbeatLink.replace("%apikey%", heartbeatApiKey); return configManager == null ? null : (String) configManager.getConfigValue("heartbeat-link");
} }
//todo javadocs //todo javadocs
public static void setHeartBeatApiKey(String key) {
heartbeatApiKey = key;
}
public static String getHeartBeatApiKey() {
return heartbeatApiKey;
}
public static String getExecPath() { return execPath; } public static String getExecPath() { return execPath; }
public static ConfigurationManager getConfigurationManager() private static ConfigurationManager getConfigurationManager()
{ return configManager; } { return configManager; }
public static void setConfigManager(ConfigurationManager configurationManager) public static void setConfigManager(ConfigurationManager configurationManager)

View File

@ -29,27 +29,29 @@ import java.util.concurrent.TimeUnit;
public class HidekoBot public class HidekoBot
{ {
private static String botToken;
private static JDA jda; private static JDA jda;
// create a logger instance for ease of use
private static final Logger logger = new Logger(HidekoBot.class); private static final Logger logger = new Logger(HidekoBot.class);
public static void main(String[] args) public static void main(String[] args)
{ {
// check if bot token was specified as a startup argument // load configuration
if(args.length < 1) logger.log("Loading configuration...");
String configFilePath = Cache.getExecPath() + File.separator + "config.yml";
ConfigurationManager configurationManager = new ConfigurationManager(configFilePath);
configurationManager.initConfig();
Cache.setConfigManager(configurationManager);
logger.log("Configuration loaded!");
String botToken = Cache.getBotToken();
if(botToken == null || botToken.isEmpty())
{ {
logger.log("Please specify your bot token!"); logger.log("Invalid bot token!");
shutdown();
return; return;
} }
// load token from args
botToken = args[0];
try try
{ {
// try to create the bot object and authenticate it with discord. // try to create the bot object and authenticate it with discord.
@ -79,19 +81,18 @@ public class HidekoBot
// if there is more than 1 arg, then iterate through them because we have additional things to do. // if there is more than 1 arg, then iterate through them because we have additional things to do.
// we are doing this at the end because we might need the API to be already initialized for some things. // we are doing this at the end because we might need the API to be already initialized for some things.
if(args.length > 1) { if(args.length > 1) {
List<String> argsList = new ArrayList<>(Arrays.asList(args).subList(1, args.length)); List<String> argsList = new ArrayList<>(Arrays.asList(args));
// NOTE: do not replace with enhanced for, since we might need
// to know what position we're at or do further elaboration of the string.
// we were using this for api key parsing in the past.
for(int i = 0; i < argsList.size(); i++) for(int i = 0; i < argsList.size(); i++)
{ {
String arg = argsList.get(i); String arg = argsList.get(i);
if(arg.equals("verbose")) Cache.setVerbose(true); if(arg.equals("verbose")) Cache.setVerbose(true);
if(arg.equals("refresh")) forceUpdateCommands = true; if(arg.equals("refresh")) forceUpdateCommands = true;
if(arg.startsWith("heartbeat="))
{
String apiKey = arg.replaceAll(".*=", ""); //remove the "heartbeat=" part
Cache.setHeartBeatApiKey(apiKey);
}
} }
} }
@ -111,13 +112,6 @@ public class HidekoBot
jda.getPresence().setStatus(OnlineStatus.ONLINE); jda.getPresence().setStatus(OnlineStatus.ONLINE);
jda.getPresence().setActivity(Activity.playing("Hatsune Miku: Project DIVA")); jda.getPresence().setActivity(Activity.playing("Hatsune Miku: Project DIVA"));
// load configuration
String configFilePath = Cache.getExecPath() + File.separator + "config.yml";
ConfigurationManager configurationManager = new ConfigurationManager(configFilePath);
configurationManager.initConfig();
Cache.setConfigManager(configurationManager);
// connect to database // connect to database
logger.log("Connecting to database..."); logger.log("Connecting to database...");
String dbFilePath = Cache.getExecPath() + File.separator + "db.sqlite"; // in current directory String dbFilePath = Cache.getExecPath() + File.separator + "db.sqlite"; // in current directory

View File

@ -13,7 +13,7 @@ public class DieCommand
public void runSlashCommand(@NotNull SlashCommandInteractionEvent event) public void runSlashCommand(@NotNull SlashCommandInteractionEvent event)
{ {
if(Cache.getBotOwnerId() != event.getMember().getIdLong()) if(Cache.getBotOwnerId() != event.getUser().getIdLong())
{ {
event.reply("Sorry, only the bot owner can run this command!").setEphemeral(true).queue(); event.reply("Sorry, only the bot owner can run this command!").setEphemeral(true).queue();
} else { } else {

View File

@ -21,10 +21,9 @@ public class HeartBeatTask implements Runnable
@Override @Override
public void run() public void run()
{ {
String apiKey = Cache.getHeartBeatApiKey();
if(apiKey == null || apiKey.isEmpty()) return;
String urlString = Cache.getFullHeartBeatLink(); String urlString = Cache.getFullHeartBeatLink();
if(urlString == null || urlString.isEmpty()) return;
try { try {
URL heartbeatUrl = new URL(urlString); URL heartbeatUrl = new URL(urlString);
@ -46,7 +45,7 @@ public class HeartBeatTask implements Runnable
} }
} catch (IOException e) { } catch (IOException e) {
logger.log("Error while trying to push heartbeat: " + e.getMessage()); logger.log("Error while trying to push heartbeat: " + e.getMessage() + ", " + e.getCause().getMessage());
} }
} }

View File

@ -127,9 +127,9 @@ public class ConfigurationManager
private void loadConfig(LinkedHashMap<String, Object> configurationEntries) private void loadConfig(LinkedHashMap<String, Object> configurationEntries)
{ {
configurationEntries.putAll(configurationEntries); this.configurationEntries.putAll(configurationEntries);
} }
private Object getConfigValue(String key) public Object getConfigValue(String key)
{ {
return configurationEntries.get(key); return configurationEntries.get(key);
} }

View File

@ -1,4 +1,4 @@
bot-token: 'MTAxMjUzNzI5MTMwODI4NjAyMw.GWeNuh.00000000000000000000000000000000000000' bot-token: 'MTAxMjUzNzI5MTMwODI4NjAyMw.GWeNuh.00000000000000000000000000000000000000'
bot-owner-id: '000000000000000000' bot-owner-id: 000000000000000000
bot-color: 'PINK' bot-color: 'PINK'
heartbeat-link: 'https://your-heartbeat-api.com/api/push/apikey?status=up&msg=OK&ping=' heartbeat-link: 'https://your-heartbeat-api.com/api/push/apikey?status=up&msg=OK&ping='