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

This commit is contained in:
2022-11-22 00:31:52 +01:00
parent 8faa9c4677
commit 656dff4b26
15 changed files with 16 additions and 16 deletions

View File

@@ -0,0 +1,50 @@
package wtf.beatrice.hidekobot.util;
import wtf.beatrice.hidekobot.Cache;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class FormatUtil
{
/**
* Generate a nicely formatted uptime String that omits unnecessary data
* (e.g. 0 days, 0 hours, 4 minutes, 32 seconds -> 4m 32s)
*
* @return the formatter String
*/
public static String getNiceUptime()
{
LocalDateTime now = LocalDateTime.now();
long uptimeSeconds = ChronoUnit.SECONDS.between(Cache.getStartupTime(), now);
Duration uptime = Duration.ofSeconds(uptimeSeconds);
long seconds = uptime.toSecondsPart();
long minutes = uptime.toMinutesPart();
long hours = uptime.toHoursPart();
long days = uptime.toDays();
StringBuilder uptimeStringBuilder = new StringBuilder();
if(days == 0)
{
if(hours == 0)
{
if(minutes == 0)
{} else {
uptimeStringBuilder.append(minutes).append("m ");
}
} else {
uptimeStringBuilder.append(hours).append("h ");
uptimeStringBuilder.append(minutes).append("m ");
}
} else {
uptimeStringBuilder.append(days).append("d ");
uptimeStringBuilder.append(hours).append("h ");
uptimeStringBuilder.append(minutes).append("m ");
}
uptimeStringBuilder.append(seconds).append("s ");
return uptimeStringBuilder.toString();
}
}

View File

@@ -0,0 +1,84 @@
package wtf.beatrice.hidekobot.util;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Logger
{
// cosmetic string to print on startup.
private String logo =
"██╗░░██╗██╗██████╗░███████╗██╗░░██╗░█████╗░\n" +
"██║░░██║██║██╔══██╗██╔════╝██║░██╔╝██╔══██╗\n" +
"███████║██║██║░░██║█████╗░░█████═╝░██║░░██║\n" +
"██╔══██║██║██║░░██║██╔══╝░░██╔═██╗░██║░░██║\n" +
"██║░░██║██║██████╔╝███████╗██║░╚██╗╚█████╔╝\n" +
"╚═╝░░╚═╝╚═╝╚═════╝░╚══════╝╚═╝░░╚═╝░╚════╝░";
// objects that we need to have for a properly formatted message
private String className;
private final String format = "[%date% %time%] [%class%] %message%";
private final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("YYYY-MM-dd");
private final DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
// when initializing a new logger, save variables in that instance
public Logger(Class logClass)
{
className = logClass.getSimpleName();
}
/**
* Logs a message to console, following a specific format.
*
* @param message the message to log
*/
public void log(String message)
{
LocalDateTime now = LocalDateTime.now();
String currentDate = dateFormatter.format(now);
String currentTime = timeFormatter.format(now);
logRaw(format
.replace("%date%", currentDate)
.replace("%time%", currentTime)
.replace("%class%", className)
.replace("%message%", message));
}
/**
* Logs a message to console, after delaying it.
*
* @param message the message to log
* @param delay the time to wait before logging, in seconds
*/
public void log(String message, int delay)
{
// create a new scheduled executor with an anonymous runnable...
//... after waiting <delay> seconds.
Executors.newSingleThreadScheduledExecutor().schedule(() -> log(message), delay, TimeUnit.SECONDS);
}
/**
* Prints a message to console without any formatting.
*
* @param message the message to log
*/
public void logRaw(String message)
{
System.out.println(message);
}
/**
* Returns ASCII art saying the bot name.
*
* @return a String containing the logo
*/
public String getLogo()
{
return logo;
}
}

View File

@@ -0,0 +1,37 @@
package wtf.beatrice.hidekobot.util;
import java.util.Random;
public class RandomUtil
{
private static final Random random = new Random();
/**
* Returns a random integer picked in a range.
*
* @param min the minimum value (inclusive)
* @param max the maximum value (inclusive)
* @return a random number in range [min; max]
*/
public static int getRandomNumber(int min, int max)
{
if(min == max) return min; // dumbass
if(min > max) // swap em
{
min = min - max;
max = min + max;
min = max - min;
}
// find our range of randomness (eg. 5 -> 8 = 4), add +1 since we want to be inclusive at both sides
int difference = (max - min) + 1;
// find a number between 0 and our range (eg. 5 -> 8 = 0 -> 3)
int randomTemp = random.nextInt(difference);
// add the minimum value, so we are sure to be in the original range (0->5, 1->6, 2->7, 3->8)
return randomTemp + min;
}
}

View File

@@ -0,0 +1,133 @@
package wtf.beatrice.hidekobot.util;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.interactions.commands.Command;
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.Cache;
import wtf.beatrice.hidekobot.HidekoBot;
import wtf.beatrice.hidekobot.listeners.MessageListener;
import java.util.ArrayList;
import java.util.List;
public class SlashCommandUtil
{
private static final Logger logger = new Logger(MessageListener.class);
static List<CommandData> allCommands = new ArrayList<>()
{{
add(Commands.slash("avatar", "Get someone's profile picture.")
.addOption(OptionType.USER, "user", "User you want to grab the avatar of.")
.addOption(OptionType.INTEGER, "size", "The size of the returned image.", false, true));
add(Commands.slash("botinfo", "Get info about the bot."));
add(Commands.slash("die", "Stop the bot's process.")
.setDefaultPermissions(DefaultMemberPermissions.DISABLED));
add(Commands.slash("clear", "Clear the current channel's chat.")
.addOption(OptionType.INTEGER, "amount", "The amount of messages to delete.")
.setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.MESSAGE_MANAGE)));
add(Commands.slash("coinflip", "Flip a coin and get head or tails."));
add(Commands.slash("help", "Get general help on the bot."));
add(Commands.slash("invite", "Get an invite link for the bot."));
add(Commands.slash("ping", "Test if the bot is responsive."));
add(Commands.slash("say", "Make the bot say something.")
.addOption(OptionType.STRING, "text", "The message to send.", true, false)
.setDefaultPermissions(DefaultMemberPermissions.enabledFor(Permission.MESSAGE_MANAGE)));
}};
public static void updateSlashCommands(boolean force)
{
JDA jdaInstance = HidekoBot.getAPI();
// get all the already registered commands
List<Command> registeredCommands = jdaInstance.retrieveCommands().complete();
boolean update = false;
if(force)
{
update = true;
} else
{
// for each command that we have already registered...
for(Command currRegCmd : registeredCommands)
{
boolean found = false;
// iterate through all "recognized" commands
for(CommandData cmdData : allCommands)
{
// if we find the same command...
if(cmdData.getName().equals(currRegCmd.getName()))
{
// quit the loop since we found it.
found = true;
break;
}
}
// if no match was found, we need to send an updated command list because
// an old command was probably removed.
if(!found)
{
update = true;
// quit the loop since we only need to trigger this once.
break;
}
}
// if an update is not already queued...
if(!update)
{
// for each "recognized" valid command
for(CommandData currCmdData : allCommands)
{
boolean found = false;
// iterate through all already registered commands.
for(Command cmd : registeredCommands)
{
// if this command was already registered...
if(cmd.getName().equals(currCmdData.getName()))
{
// quit the loop since we found a match.
found = true;
break;
}
}
// if no match was found, we need to send an updated command list because
// a new command was probably added.
if(!found)
{
update = true;
// quit the loop since we only need to trigger this once.
break;
}
}
}
}
logger.log("Found " + registeredCommands.size() + " commands.");
if(update)
{
// send updated command list.
jdaInstance.updateCommands().addCommands(allCommands).queue();
logger.log("Commands updated. New total: " + allCommands.size() + ".");
}
// cache the registered commands.
// 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).
Cache.setRegisteredCommands(jdaInstance.retrieveCommands().complete());
}
}