Implement LoggingManager

LoggingManager replaces the previous main class logging functionality.
It uses text blocks to add response templates for stdout.
This commit is contained in:
Anya 2022-05-21 22:41:04 -07:00
parent ff626019b0
commit dfdd032a33
20 changed files with 69 additions and 104 deletions

View File

@ -14,17 +14,13 @@ import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.utils.ChunkingFilter;
import net.dv8tion.jda.api.utils.MemberCachePolicy;
import net.dv8tion.jda.api.utils.cache.CacheFlag;
import org.simpleyaml.configuration.file.YamlConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
@ -32,6 +28,8 @@ import java.nio.file.Files;
import java.time.ZonedDateTime;
import java.util.List;
import static moe.oko.Kiafumi.util.LoggingManager.*;
/**
* Kiafumi Main Class
* @author Kay, oko, Tiddy
@ -50,8 +48,6 @@ public class Kiafumi {
public YamlConfiguration yamlConfiguration = new YamlConfiguration();
public Logger logger = LoggerFactory.getLogger("Kiafumi");
public String footer = EmbedUI.BRAND + " 0.9.0-pre";
public static Kiafumi instance;
@ -63,7 +59,6 @@ public class Kiafumi {
public KiafumiConfig config;
public KiafumiDB database;
public ServerManager serverManager;
/**
@ -85,8 +80,7 @@ public class Kiafumi {
*/
public void start() {
instance = this;
logger.info("Starting Kiafumi.");
info("Starting Kiafumi.");
// All commands to be loaded on startup!
activeCommands = new CommandRegistrar().getCommandClasses();
@ -97,7 +91,7 @@ public class Kiafumi {
// Save the default config
Files.copy(is, CONFIG_FILE.toPath());
} catch (Exception ex) {
logger.warn("Failed to create the configuration file. Stopping. (" + CONFIG_FILE.getAbsolutePath() + ")");
warn("Failed to create the configuration file. Stopping. (" + CONFIG_FILE.getAbsolutePath() + ")");
ex.printStackTrace();
return;
}
@ -108,23 +102,23 @@ public class Kiafumi {
yamlConfiguration.load("config.yml");
} catch (FileNotFoundException e) {
e.printStackTrace();
logger.warn("File not found, must've failed to create...");
warn("File not found, must've failed to create...");
} catch (Exception e) {
logger.warn("Ensure all values are inputted properly.");
warn("Ensure all values are inputted properly.");
e.printStackTrace();
}
// Initializes our configuration helper & ensures it loads properly.
config = new KiafumiConfig(yamlConfiguration);
if(config.load()) {
logger.info("Fetched Kiafumi config.");
info("Fetched Kiafumi config.");
} else {
logger.error("Failed to load configuration. Stopping process.");
error("Failed to load configuration. Stopping process.");
Runtime.getRuntime().exit(0);
}
// Registers the stop() function if the program is stopped.
logger.info("Registering shutdown hook.");
info("Registering shutdown hook.");
Runtime.getRuntime().addShutdownHook(new Thread(this::stop));
// Initializes database and loads credentials.
@ -250,34 +244,6 @@ public class Kiafumi {
debug("Registered " + i + " commands for guild [" + guild.getId() + "]");
}
/*
Static logger references.
*/
public static void info(String str) {
instance.logger.info(str);
}
public static void error(String str) {
instance.logger.error(str);
}
public static void debug(String str) { instance.logger.debug(str); }
/**
* Used for logging commands with ease to console via a static method.
* @param event - the event ran
* @param msg - Any message to append with this.
*/
public static void slashLog(SlashCommandInteractionEvent event, @Nullable String msg) {
info("User [" + event.getUser().getName() + ":" + event.getUser().getId() + "] ran command: \"" + event.getName() + "\" " + (msg == null ? "" : msg));
}
public static void slashLog(SlashCommandInteractionEvent event) {
info("User [" + event.getUser().getName() + ":" + event.getUser().getId() + "] ran command: \"" + event.getName() + "\".");
}
public static void slashResponse(SlashCommandInteractionEvent event, String msg) {
info("User [" + event.getUser().getName() + ":" + event.getUser().getId() + "] was provided response: \"" + msg + "\"");
}
// Gets the active database.
public KiafumiDB getDatabase() { return database; }

View File

@ -5,8 +5,8 @@ import org.simpleyaml.configuration.file.YamlConfiguration;
import java.util.List;
import static moe.oko.Kiafumi.Kiafumi.error;
import static moe.oko.Kiafumi.Kiafumi.info;
import static moe.oko.Kiafumi.util.LoggingManager.error;
import static moe.oko.Kiafumi.util.LoggingManager.info;
/**
* KiafumiConfig class
@ -80,8 +80,7 @@ public class KiafumiConfig {
Owner ID: %s
Primary Guild: %s
Invite URL: %s
--------------------------------
""".formatted(logChannel, ownerId, mainGuild, assembleDefaultInvite()));
--------------------------------""".formatted(logChannel, ownerId, mainGuild, assembleDefaultInvite()));
// Kiafumi loaders
var main = configuration.getConfigurationSection("main");

View File

@ -9,9 +9,9 @@ import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static moe.oko.Kiafumi.Kiafumi.error;
import static moe.oko.Kiafumi.Kiafumi.info;
import static moe.oko.Kiafumi.Kiafumi.debug;
import static moe.oko.Kiafumi.util.LoggingManager.error;
import static moe.oko.Kiafumi.util.LoggingManager.info;
import static moe.oko.Kiafumi.util.LoggingManager.debug;
/**
* CommandRegistrar Class

View File

@ -13,7 +13,7 @@ import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import static moe.oko.Kiafumi.Kiafumi.slashLog;
import static moe.oko.Kiafumi.util.LoggingManager.slashLog;
/**
* Dreidel Dreidel...

View File

@ -16,7 +16,7 @@ import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import static moe.oko.Kiafumi.Kiafumi.slashLog;
import static moe.oko.Kiafumi.util.LoggingManager.slashLog;
/**
* Random User Choice Command

View File

@ -14,7 +14,7 @@ import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import static moe.oko.Kiafumi.Kiafumi.slashLog;
import static moe.oko.Kiafumi.util.LoggingManager.slashLog;
/**
* Fetches the REAL date

View File

@ -12,7 +12,7 @@ import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import static moe.oko.Kiafumi.Kiafumi.slashLog;
import static moe.oko.Kiafumi.util.LoggingManager.slashLog;
/**
* Helpful Avatar grabber command

View File

@ -14,8 +14,8 @@ import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import static moe.oko.Kiafumi.Kiafumi.error;
import static moe.oko.Kiafumi.Kiafumi.slashLog;
import static moe.oko.Kiafumi.util.LoggingManager.error;
import static moe.oko.Kiafumi.util.LoggingManager.slashLog;
import static moe.oko.Kiafumi.util.ResponseHandlers.STRING_RESPONSE_HANDLER;
/**

View File

@ -28,7 +28,7 @@ import java.io.File;
import java.io.IOException;
import java.util.*;
import static moe.oko.Kiafumi.Kiafumi.slashLog;
import static moe.oko.Kiafumi.util.LoggingManager.slashLog;
/**
* Music Command

View File

@ -14,7 +14,7 @@ import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import static moe.oko.Kiafumi.Kiafumi.slashLog;
import static moe.oko.Kiafumi.util.LoggingManager.slashLog;
/**
* Helpful Search Command (Uses DDG API)

View File

@ -12,12 +12,12 @@ import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import static moe.oko.Kiafumi.Kiafumi.slashLog;
import static moe.oko.Kiafumi.util.LoggingManager.slashLog;
public class HelpCommand extends CommandClass {
@Override
public boolean isEnabled() {
return true; //perma-enabled
return true;
}
@Override
@ -30,12 +30,12 @@ public class HelpCommand extends CommandClass {
if ("help".equalsIgnoreCase(name)) {
slashLog(e);
e.deferReply().queue();
//We assemble a help string, this is our description for our embed.
StringBuilder sb = new StringBuilder();
// We assemble a help string, this is our description for our embed.
var sb = new StringBuilder();
for(CommandClass cc : Kiafumi.instance.activeCommands) {
for(CommandInfo ci : cc.getSlashCommandInfo()) {
String cname = ci.getName();
String cdesc= ci.getDescription();
var cname = ci.getName();
var cdesc= ci.getDescription();
sb.append("**").append(cname).append("** - __").append(cdesc).append("__\n");
if(ci.hasOptions()) {
for (String opt : ci.getOptions().keySet()) {
@ -49,7 +49,7 @@ public class HelpCommand extends CommandClass {
}
if(ci.hasSubCommands()) {
for (String subc : ci.getSubCommands().keySet()) {
CommandInfo subCommand = ci.getSubCommands().get(subc);
var subCommand = ci.getSubCommands().get(subc);
sb.append("-> **").append(subc).append("** *").append(subCommand.getDescription()).append("*\n");
if (subCommand.hasOptions()) {
for (String opt : subCommand.getOptions().keySet()) {
@ -80,7 +80,7 @@ public class HelpCommand extends CommandClass {
@Override
public List<CommandInfo> getSlashCommandInfo() {
List<CommandInfo> cil = new ArrayList<>();
CommandInfo ci = new CommandInfo("help", "Displays all enabled commands this bot has.", CommandType.COMMAND);
var ci = new CommandInfo("help", "Displays all enabled commands this bot has.", CommandType.COMMAND);
cil.add(ci);
return cil;
}

View File

@ -14,7 +14,7 @@ import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import static moe.oko.Kiafumi.Kiafumi.slashLog;
import static moe.oko.Kiafumi.util.LoggingManager.slashLog;
/**
* Helpful User Information Command

View File

@ -12,7 +12,7 @@ import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import static moe.oko.Kiafumi.Kiafumi.slashLog;
import static moe.oko.Kiafumi.util.LoggingManager.slashLog;
/**
* Helpful Invite Command

View File

@ -14,7 +14,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Random;
import static moe.oko.Kiafumi.Kiafumi.slashLog;
import static moe.oko.Kiafumi.util.LoggingManager.slashLog;
/**
* Helpful Ping Command

View File

@ -15,8 +15,8 @@ import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import static moe.oko.Kiafumi.Kiafumi.slashLog;
import static moe.oko.Kiafumi.Kiafumi.slashResponse;
import static moe.oko.Kiafumi.util.LoggingManager.slashLog;
import static moe.oko.Kiafumi.util.LoggingManager.slashResponse;
/**
* Permits modification of server settings, critical class to functionality.

View File

@ -11,7 +11,7 @@ import org.jetbrains.annotations.NotNull;
import java.time.ZonedDateTime;
import static moe.oko.Kiafumi.Kiafumi.info;
import static moe.oko.Kiafumi.util.LoggingManager.info;
/**
* Main Listener
@ -42,8 +42,7 @@ public class MainListener extends ListenerAdapter {
--------------------------------
Active Guilds: [%s]
Guilds Unavailable: [%s]
--------------------------------
""".formatted(event.getGuildAvailableCount(), event.getGuildUnavailableCount()));
--------------------------------""".formatted(event.getGuildAvailableCount(), event.getGuildUnavailableCount()));
}
/**

View File

@ -14,9 +14,9 @@ import org.jetbrains.annotations.NotNull;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import static moe.oko.Kiafumi.Kiafumi.debug;
import static moe.oko.Kiafumi.Kiafumi.info;
import static moe.oko.Kiafumi.Kiafumi.error;
import static moe.oko.Kiafumi.util.LoggingManager.debug;
import static moe.oko.Kiafumi.util.LoggingManager.info;
import static moe.oko.Kiafumi.util.LoggingManager.error;
/**
* Skynet Listener
@ -30,34 +30,36 @@ public class SkynetListener extends ListenerAdapter {
/**
* Join/Leave logging
* Requires the server to configure welcomeEnabled & welcomeChannel (optionally joinRole).
* Requires the server to configure welcomeChannel (optionally joinRole).
*/
@Override
public void onGuildMemberJoin(@NotNull GuildMemberJoinEvent event) {
var server = Kiafumi.instance.getServerManager().getOrCreateServer(event.getGuild());
var guild = event.getGuild();
var server = Kiafumi.instance.getServerManager().getOrCreateServer(guild);
var member = event.getMember();
info("User [" + event.getUser().getName() + ":" + event.getUser().getId() + "] joined guild [" + guild.getName() + ':' + guild.getId() + "].");
if(server.getJoinRole() != null) {
try {
event.getGuild().addRoleToMember(event.getMember(), event.getGuild().getRoleById(server.getJoinRole())).queue();
guild.addRoleToMember(member, guild.getRoleById(server.getJoinRole())).queue();
} catch(Exception ex) {
error("Failed to apply welcome role to " + event.getMember().getEffectiveName() + ", as the role does not exist.");
error("Failed to apply welcome role to " + member.getEffectiveName() + ", as the role does not exist.");
}
}
if(server.isWelcomeEnabled()) {
info("User [" + event.getUser().getName() + ":" + event.getUser().getId() + "] joined guild [" + event.getGuild().getName() + ':' + event.getGuild().getId() + "].");
if(server.getWelcomeChannel() != null) {
// Fetch the welcome channel from settings.
TextChannel textChannel;
try {
textChannel = event.getGuild().getTextChannelById(server.getWelcomeChannel());
textChannel = guild.getTextChannelById(server.getWelcomeChannel());
} catch (Exception ex) {
error("Failed to send join message to guild " + event.getGuild().getId() + " as the welcome channel was not found.");
error("Failed to send join message to guild " + guild.getId() + " as the welcome channel was not found.");
return;
}
// Prepare embed.
var eb = new EmbedBuilder()
.setColor(EmbedUI.SUCCESS)
.setAuthor(event.getMember().getEffectiveName() + "#" + event.getMember().getUser().getDiscriminator() + " ("
+ event.getMember().getId() + ")", null, event.getUser().getAvatarUrl())
.setDescription(event.getMember().getAsMention() + " | **Joined Discord**: " + event.getMember().getTimeCreated().format(dTF))
.setAuthor(member.getEffectiveName() + "#" + member.getUser().getDiscriminator() + " ("
+ member.getId() + ")", null, event.getUser().getAvatarUrl()) // Url cannot be member.
.setDescription(member.getAsMention() + " | **Joined Discord**: " + member.getTimeCreated().format(dTF))
.setFooter("User Joined")
.setTimestamp(OffsetDateTime.now());
textChannel.sendMessageEmbeds(eb.build()).queue();
@ -67,23 +69,25 @@ public class SkynetListener extends ListenerAdapter {
@Override
public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) {
info("User [" + event.getUser().getName() + ":" + event.getUser().getId() + "] left guild [" + event.getGuild().getName() + ':' + event.getGuild().getId() + "].");
var server = Kiafumi.instance.getServerManager().getOrCreateServer(event.getGuild());
if(server.isWelcomeEnabled()) {
var guild = event.getGuild();
info("User [" + event.getUser().getName() + ":" + event.getUser().getId() + "] left guild [" + guild.getName() + ':' + guild.getId() + "].");
var server = Kiafumi.instance.getServerManager().getOrCreateServer(guild);
if(server.getWelcomeChannel() != null) {
// Fetch the welcome channel from settings.
TextChannel textChannel;
var member = event.getMember();
try {
textChannel = event.getGuild().getTextChannelById(server.getWelcomeChannel());
textChannel = guild.getTextChannelById(server.getWelcomeChannel());
} catch (Exception ex) {
error("Failed to send leave message to guild " + event.getGuild().getId() + " as the welcome channel was not found.");
error("Failed to send leave message to guild " + guild.getId() + " as the welcome channel was not found.");
return;
}
// Prepare embed.
var eb = new EmbedBuilder()
.setColor(EmbedUI.FAILURE)
.setAuthor(event.getMember().getEffectiveName() + "#" + event.getMember().getUser().getDiscriminator() + " ("
+ event.getMember().getId() + ")", null, event.getUser().getAvatarUrl())
.setDescription(event.getMember().getAsMention() + " | **Joined Server**: " + event.getMember().getTimeJoined().format(dTF))
.setAuthor(member.getEffectiveName() + "#" + member.getUser().getDiscriminator() + " ("
+ member.getId() + ")", null, event.getUser().getAvatarUrl()) // Url cannot be member.
.setDescription(member.getAsMention() + " | **Joined Server**: " + member.getTimeJoined().format(dTF))
.setFooter("User Left")
.setTimestamp(OffsetDateTime.now());
textChannel.sendMessageEmbeds(eb.build()).queue();

View File

@ -8,7 +8,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static moe.oko.Kiafumi.Kiafumi.*;
import static moe.oko.Kiafumi.util.LoggingManager.*;
/**
* Kiafumi DB Class
@ -23,7 +23,7 @@ public class KiafumiDB {
// The prepared statement strings
private final String CREATE_SERVERINFO_TABLE = "CREATE TABLE IF NOT EXISTS `serverInfo`" +
"(`id` LONGTEXT NOT NULL, `welcomeChannel` LONGTEXT NULL, `modChannel` LONGTEXT NULL, joinRole LONGTEXT NULL);";
private final String INSERT_SERVERINFO_DEFAULT = "INSERT INTO serverInfo(id, welcomeChannel, modChannel, joinRole) values (?,?,?,?,?, ?)";
private final String INSERT_SERVERINFO_DEFAULT = "INSERT INTO serverInfo(id, welcomeChannel, modChannel, joinRole) values (?,?,?,?)";
private final String SERVERINFO_EXISTS = "select * from serverInfo where id = ?";
private final String SERVER_INFO_LOAD = "select * from serverInfo";
// 1 = welcomeChannel, 2 = modChannel , 3 = joinRole, 4 = Guild_ID (immutable)
@ -81,11 +81,9 @@ public class KiafumiDB {
//Proceed with making defaults.
PreparedStatement ps = connection.prepareStatement(INSERT_SERVERINFO_DEFAULT);
ps.setString(1, guild.getId());
ps.setInt(2, 0); //default is false.
ps.setNull(2, Types.LONGVARCHAR);
ps.setNull(3, Types.LONGVARCHAR);
ps.setNull(4, Types.LONGVARCHAR);
ps.setInt(5, 0); //Falseeeee
ps.setNull(6, Types.LONGVARCHAR);
ps.execute();
return true;
} catch (Exception ex) {

View File

@ -83,8 +83,7 @@ public class Server {
return """
welcomeChannel - the channel to send welcome messages to
modChannel - the channel to send moderation logs to
joinRole - the role to apply to new members who join this guild
""";
joinRole - the role to apply to new members who join this guild""";
}
/**

View File

@ -7,7 +7,7 @@ import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import static moe.oko.Kiafumi.Kiafumi.*;
import static moe.oko.Kiafumi.util.LoggingManager.*;
/**
* ServerManager Class