Refactor Config class
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Bea 2022-11-21 20:20:11 +01:00
parent e396ce6417
commit f74ae43673
18 changed files with 72 additions and 70 deletions

View File

@ -35,7 +35,11 @@
<artifactId>sqlite-jdbc</artifactId>
<version>3.39.4.1</version>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.33</version>
</dependency>
</dependencies>
<build>

View File

@ -70,7 +70,7 @@ public class HidekoBot
// find the bot's user/application id
String botUserId = jda.getSelfUser().getId();
Configuration.setBotApplicationId(botUserId);
Cache.setBotApplicationId(botUserId);
// store if we have to force refresh commands despite no apparent changes.
boolean forceUpdateCommands = false;
@ -84,12 +84,12 @@ public class HidekoBot
{
String arg = argsList.get(i);
if(arg.equals("verbose")) Configuration.setVerbose(true);
if(arg.equals("verbose")) Cache.setVerbose(true);
if(arg.equals("refresh")) forceUpdateCommands = true;
if(arg.startsWith("heartbeat="))
{
String apiKey = arg.replaceAll(".*=", ""); //remove the "heartbeat=" part
Configuration.setHeartBeatApiKey(apiKey);
Cache.setHeartBeatApiKey(apiKey);
}
}
@ -117,7 +117,7 @@ public class HidekoBot
if(dbManager.connect() && dbManager.initDb())
{
logger.log("Database connection initialized!");
Configuration.setDatabaseManagerInstance(dbManager);
Cache.setDatabaseManagerInstance(dbManager);
// load data here...
@ -139,15 +139,15 @@ public class HidekoBot
Signal.handle(new Signal("INT"), signal -> shutdown());
// set startup time.
Configuration.setStartupTime(LocalDateTime.now());
Cache.setStartupTime(LocalDateTime.now());
// print the bot logo.
logger.log("\n\n" + logger.getLogo() + "\nv" + Configuration.getBotVersion() + " - bot is ready!\n", 2);
logger.log("\n\n" + logger.getLogo() + "\nv" + Cache.getBotVersion() + " - bot is ready!\n", 2);
// log the invite-link to console so noob users can just click on it.
logger.log("Bot User ID: " + botUserId, 3);
logger.log("Invite Link: " + Configuration.getInviteUrl(), 4);
logger.log("Invite Link: " + Cache.getInviteUrl(), 4);
}
public static JDA getAPI()

View File

@ -3,7 +3,7 @@ package wtf.beatrice.hidekobot.commands.completer;
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.Command;
import org.jetbrains.annotations.NotNull;
import wtf.beatrice.hidekobot.Configuration;
import wtf.beatrice.hidekobot.Cache;
import java.util.ArrayList;
import java.util.List;
@ -18,7 +18,7 @@ public class AvatarCompleter
List<Command.Choice> options = new ArrayList<>();
for(int res : Configuration.getSupportedAvatarResolutions())
for(int res : Cache.getSupportedAvatarResolutions())
{
String resString = String.valueOf(res);
String userInput = event.getFocusedOption().getValue();

View File

@ -5,7 +5,7 @@ import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import org.jetbrains.annotations.NotNull;
import wtf.beatrice.hidekobot.Configuration;
import wtf.beatrice.hidekobot.Cache;
public class AvatarCommand
{
@ -18,7 +18,7 @@ public class AvatarCommand
User user;
int resolution;
int[] acceptedSizes = Configuration.getSupportedAvatarResolutions();
int[] acceptedSizes = Cache.getSupportedAvatarResolutions();
OptionMapping userArg = event.getOption("user");
@ -54,7 +54,7 @@ public class AvatarCommand
// embed processing
{
embedBuilder.setColor(Configuration.getBotColor());
embedBuilder.setColor(Cache.getBotColor());
embedBuilder.setTitle("Profile picture");
embedBuilder.addField("User", "<@" + user.getId() + ">", false);

View File

@ -4,7 +4,7 @@ import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.Command;
import org.jetbrains.annotations.NotNull;
import wtf.beatrice.hidekobot.Configuration;
import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.HidekoBot;
import wtf.beatrice.hidekobot.utils.FormatUtil;
@ -20,14 +20,14 @@ public class BotInfoCommand
// defer reply because this might take a moment
event.deferReply().queue();
List<Command> registeredCommands = Configuration.getRegisteredCommands();
List<Command> registeredCommands = Cache.getRegisteredCommands();
EmbedBuilder embedBuilder = new EmbedBuilder();
// embed processing
{
embedBuilder.setColor(Configuration.getBotColor());
embedBuilder.setTitle(Configuration.getBotName());
embedBuilder.setColor(Cache.getBotColor());
embedBuilder.setTitle(Cache.getBotName());
// thumbnail
String botAvatarUrl = HidekoBot.getAPI().getSelfUser().getAvatarUrl();
@ -53,7 +53,7 @@ public class BotInfoCommand
embedBuilder.addField("Commands", commandsListBuilder.toString(), false);
// version field
embedBuilder.addField("Version", "v" + Configuration.getBotVersion(), true);
embedBuilder.addField("Version", "v" + Cache.getBotVersion(), true);
// jvm version field
String jvmVersion = ManagementFactory.getRuntimeMXBean().getVmVersion();
@ -68,7 +68,7 @@ public class BotInfoCommand
embedBuilder.addField("RAM Usage", ramMBFormatter.format(usedRamMB) + " MB", true);
// developer field
String developerMention = "<@" + Configuration.getBotMaintainerId() + ">";
String developerMention = "<@" + Cache.getBotMaintainerId() + ">";
embedBuilder.addField("Maintainer", developerMention, true);
// uptime field

View File

@ -12,7 +12,7 @@ import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.dv8tion.jda.api.interactions.components.buttons.Button;
import net.dv8tion.jda.api.requests.restaction.WebhookMessageEditAction;
import org.jetbrains.annotations.NotNull;
import wtf.beatrice.hidekobot.Configuration;
import wtf.beatrice.hidekobot.Cache;
import java.util.ArrayList;
import java.util.List;
@ -165,8 +165,8 @@ public class ClearChatCommand
.setActionRow(dismissButton)
.complete();
Configuration.getDatabaseManager().queueDisabling(message);
Configuration.getDatabaseManager().trackRanCommandReply(message, event.getUser());
Cache.getDatabaseManager().queueDisabling(message);
Cache.getDatabaseManager().trackRanCommandReply(message, event.getUser());
}
}).start();
@ -176,7 +176,7 @@ public class ClearChatCommand
public void dismissMessage(ButtonInteractionEvent event)
{
if(!(Configuration.getDatabaseManager().isUserTrackedFor(event.getUser().getId(), event.getMessageId())))
if(!(Cache.getDatabaseManager().isUserTrackedFor(event.getUser().getId(), event.getMessageId())))
{
event.reply("❌ You did not run this command!").setEphemeral(true).queue();
} else

View File

@ -8,7 +8,7 @@ import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.buttons.Button;
import org.jetbrains.annotations.NotNull;
import wtf.beatrice.hidekobot.Configuration;
import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.utils.RandomUtil;
import java.util.List;
@ -38,7 +38,7 @@ public class CoinFlipCommand
public void buttonReFlip(ButtonInteractionEvent event)
{
// check if the user interacting is the same one who ran the command
if(!(Configuration.getDatabaseManager().isUserTrackedFor(event.getUser().getId(), event.getMessageId())))
if(!(Cache.getDatabaseManager().isUserTrackedFor(event.getUser().getId(), event.getMessageId())))
{
event.reply("❌ You did not run this command!").setEphemeral(true).queue();
return;
@ -63,8 +63,8 @@ public class CoinFlipCommand
{
String replyMessageId = replyMessage.getId();
Configuration.getDatabaseManager().queueDisabling(replyMessage);
Configuration.getDatabaseManager().trackRanCommandReply(replyMessage, user);
Cache.getDatabaseManager().queueDisabling(replyMessage);
Cache.getDatabaseManager().trackRanCommandReply(replyMessage, user);
}
private String genRandom()

View File

@ -2,7 +2,7 @@ package wtf.beatrice.hidekobot.commands.slash;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import org.jetbrains.annotations.NotNull;
import wtf.beatrice.hidekobot.Configuration;
import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.HidekoBot;
import java.util.concurrent.Executors;
@ -13,7 +13,7 @@ public class DieCommand
public void runSlashCommand(@NotNull SlashCommandInteractionEvent event)
{
if(Configuration.getBotOwnerId() != event.getMember().getIdLong())
if(Cache.getBotOwnerId() != event.getMember().getIdLong())
{
event.reply("Sorry, only the bot owner can run this command!").setEphemeral(true).queue();
} else {

View File

@ -3,7 +3,7 @@ package wtf.beatrice.hidekobot.commands.slash;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import org.jetbrains.annotations.NotNull;
import wtf.beatrice.hidekobot.Configuration;
import wtf.beatrice.hidekobot.Cache;
public class HelpCommand
{
@ -17,7 +17,7 @@ public class HelpCommand
// embed processing
{
embedBuilder.setColor(Configuration.getBotColor());
embedBuilder.setColor(Cache.getBotColor());
embedBuilder.setTitle("Help");
}

View File

@ -9,7 +9,7 @@ import net.dv8tion.jda.api.interactions.components.buttons.Button;
import net.dv8tion.jda.api.requests.restaction.WebhookMessageEditAction;
import net.dv8tion.jda.api.requests.restaction.interactions.ReplyCallbackAction;
import org.jetbrains.annotations.NotNull;
import wtf.beatrice.hidekobot.Configuration;
import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.HidekoBot;
public class InviteCommand
@ -29,17 +29,17 @@ public class InviteCommand
//embed processing
{
embedBuilder.setColor(Configuration.getBotColor());
embedBuilder.setColor(Cache.getBotColor());
String avatarUrl = HidekoBot.getAPI().getSelfUser().getAvatarUrl();
if(avatarUrl != null) embedBuilder.setThumbnail(avatarUrl);
embedBuilder.setTitle("Invite");
embedBuilder.appendDescription("Click on the button below to invite " +
Configuration.getBotName() +
Cache.getBotName() +
" to your server!");
}
String inviteUrl = Configuration.getInviteUrl();
Button inviteButton = Button.link(inviteUrl, "Invite " + Configuration.getBotName())
String inviteUrl = Cache.getInviteUrl();
Button inviteButton = Button.link(inviteUrl, "Invite " + Cache.getBotName())
.withEmoji(Emoji.fromUnicode("\uD83C\uDF1F"));
WebhookMessageEditAction<Message> reply =

View File

@ -3,7 +3,7 @@ package wtf.beatrice.hidekobot.database;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.channel.ChannelType;
import wtf.beatrice.hidekobot.Configuration;
import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.utils.Logger;
import java.sql.*;
@ -83,6 +83,8 @@ public class DatabaseManager
*
*/
//todo: javadocs
public boolean initDb()
{
List<String> newTables = new ArrayList<>();
@ -225,9 +227,9 @@ public class DatabaseManager
guildId = message.getGuild().getId();
}
LocalDateTime expiryTime = LocalDateTime.now().plusSeconds(Configuration.getExpiryTimeSeconds());
LocalDateTime expiryTime = LocalDateTime.now().plusSeconds(Cache.getExpiryTimeSeconds());
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(Configuration.getExpiryTimestampFormat());
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(Cache.getExpiryTimestampFormat());
String expiryTimeFormatted = dateTimeFormatter.format(expiryTime);
String query = "INSERT INTO pending_disabled_messages " +

View File

@ -4,7 +4,7 @@ import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull;
import wtf.beatrice.hidekobot.Configuration;
import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.utils.Logger;
public class MessageListener extends ListenerAdapter
@ -35,12 +35,12 @@ public class MessageListener extends ListenerAdapter
{
MessageChannel channel = event.getChannel();
boolean verbose = Configuration.isVerbose();
boolean verbose = Cache.isVerbose();
String msg = verbose ? "off" : "on";
msg = "Turning verbosity " + msg + "!";
Configuration.setVerbose(!verbose);
Cache.setVerbose(!verbose);
channel.sendMessage(msg).queue();
logger.log(msg);

View File

@ -1,7 +1,7 @@
package wtf.beatrice.hidekobot.runnables;
import net.dv8tion.jda.api.JDA;
import wtf.beatrice.hidekobot.Configuration;
import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.HidekoBot;
import wtf.beatrice.hidekobot.utils.Logger;
@ -16,10 +16,10 @@ public class CommandsUpdateTask implements Runnable {
@Override
public void run() {
if(Configuration.isVerbose()) logger.log("Refreshing commands cache...");
if(Cache.isVerbose()) logger.log("Refreshing commands cache...");
JDA instance = HidekoBot.getAPI();
if(instance == null) return;
Configuration.setRegisteredCommands(instance.retrieveCommands().complete());
if(Configuration.isVerbose()) logger.log("Commands cache refreshed!");
Cache.setRegisteredCommands(instance.retrieveCommands().complete());
if(Cache.isVerbose()) logger.log("Commands cache refreshed!");
}
}

View File

@ -7,7 +7,7 @@ import net.dv8tion.jda.api.entities.channel.ChannelType;
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
import net.dv8tion.jda.api.interactions.components.LayoutComponent;
import net.dv8tion.jda.api.requests.RestAction;
import wtf.beatrice.hidekobot.Configuration;
import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.HidekoBot;
import wtf.beatrice.hidekobot.database.DatabaseManager;
import wtf.beatrice.hidekobot.utils.Logger;
@ -26,9 +26,9 @@ public class ExpiredMessageTask implements Runnable {
public ExpiredMessageTask()
{
String format = Configuration.getExpiryTimestampFormat();
String format = Cache.getExpiryTimestampFormat();
formatter = DateTimeFormatter.ofPattern(format);
databaseManager = Configuration.getDatabaseManager();
databaseManager = Cache.getDatabaseManager();
logger = new Logger(getClass());
}
@ -36,10 +36,10 @@ public class ExpiredMessageTask implements Runnable {
@Override
public void run() {
databaseManager = Configuration.getDatabaseManager();
databaseManager = Cache.getDatabaseManager();
if(databaseManager == null) return;
List<String> expiringMessages = Configuration.getDatabaseManager().getQueuedExpiringMessages();
List<String> expiringMessages = Cache.getDatabaseManager().getQueuedExpiringMessages();
if(expiringMessages == null || expiringMessages.isEmpty()) return;
LocalDateTime now = LocalDateTime.now();
@ -47,7 +47,7 @@ public class ExpiredMessageTask implements Runnable {
for(String messageId : expiringMessages)
{
if(Configuration.isVerbose()) logger.log("expired check: " + messageId);
if(Cache.isVerbose()) logger.log("expired check: " + messageId);
String expiryTimestamp = databaseManager.getQueuedExpiringMessageExpiryDate(messageId);
if(expiryTimestamp == null || expiryTimestamp.equals("")) // if missing timestamp
@ -62,7 +62,7 @@ public class ExpiredMessageTask implements Runnable {
LocalDateTime expiryDate = LocalDateTime.parse(expiryTimestamp, formatter);
if(now.isAfter(expiryDate))
{
if(Configuration.isVerbose()) logger.log("expired: " + messageId);
if(Cache.isVerbose()) logger.log("expired: " + messageId);
disableExpired(messageId);
}
}
@ -127,7 +127,7 @@ public class ExpiredMessageTask implements Runnable {
RestAction<Message> retrieveAction = textChannel.retrieveMessageById(messageId);
if(Configuration.isVerbose()) logger.log("cleaning up: " + messageId);
if(Cache.isVerbose()) logger.log("cleaning up: " + messageId);
retrieveAction.queue(

View File

@ -1,6 +1,6 @@
package wtf.beatrice.hidekobot.runnables;
import wtf.beatrice.hidekobot.Configuration;
import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.utils.Logger;
import java.io.IOException;
@ -21,10 +21,10 @@ public class HeartBeatTask implements Runnable
@Override
public void run()
{
String apiKey = Configuration.getHeartBeatApiKey();
String apiKey = Cache.getHeartBeatApiKey();
if(apiKey == null || apiKey.isEmpty()) return;
String urlString = Configuration.getFullHeartBeatLink();
String urlString = Cache.getFullHeartBeatLink();
try {
URL heartbeatUrl = new URL(urlString);
@ -38,7 +38,7 @@ public class HeartBeatTask implements Runnable
if(200 <= responseCode && responseCode < 300)
{
// only log ok response codes when verbosity is enabled
if(Configuration.isVerbose()) logger.log("Heartbeat response code: " + responseCode);
if(Cache.isVerbose()) logger.log("Heartbeat response code: " + responseCode);
}
else
{

View File

@ -1,6 +1,6 @@
package wtf.beatrice.hidekobot.utils;
import wtf.beatrice.hidekobot.Configuration;
import wtf.beatrice.hidekobot.Cache;
import java.time.Duration;
import java.time.LocalDateTime;
@ -18,7 +18,7 @@ public class FormatUtil
public static String getNiceUptime()
{
LocalDateTime now = LocalDateTime.now();
long uptimeSeconds = ChronoUnit.SECONDS.between(Configuration.getStartupTime(), now);
long uptimeSeconds = ChronoUnit.SECONDS.between(Cache.getStartupTime(), now);
Duration uptime = Duration.ofSeconds(uptimeSeconds);
long seconds = uptime.toSecondsPart();
long minutes = uptime.toMinutesPart();

View File

@ -7,7 +7,7 @@ import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.commands.build.Commands;
import wtf.beatrice.hidekobot.Configuration;
import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.HidekoBot;
import wtf.beatrice.hidekobot.listeners.MessageListener;
@ -128,6 +128,6 @@ public class SlashCommandUtil
// note that if this is the first time the bot runs after updating commands,
// this will probably still return the previous configuration because the discord api
// needs to propagate. this is why we also set up a command updater task (ExpiredMessageTask).
Configuration.setRegisteredCommands(jdaInstance.retrieveCommands().complete());
Cache.setRegisteredCommands(jdaInstance.retrieveCommands().complete());
}
}

View File

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