Compare commits

...

6 commits

Author SHA1 Message Date
Anya 8074ae1971 Merge branch 'main' of https://fem.mint.lgbt/oko/kiafumi 2022-05-21 22:42:09 -07:00
Anya 9183d350df Retroactively add the class for the last commit 😳 2022-05-21 22:41:57 -07:00
Anya dfdd032a33 Implement LoggingManager
LoggingManager replaces the previous main class logging functionality.
It uses text blocks to add response templates for stdout.
2022-05-21 22:41:04 -07:00
Anya ff626019b0 Remove ModCommand 2022-05-21 20:21:03 -07:00
Anya ab72638a94 Reorganize SQL (BREAKING)
Removed welcomeEnabled & serverProtection
welcomeEnabled was removed due to its redundancy.
serverProtection was removed due to being out of scope.
2022-05-21 20:19:31 -07:00
Anya 67dafe50bb Convert some strings to text blocks
this is the coolest thing ive ever seen
2022-05-21 19:05:53 -07:00
22 changed files with 174 additions and 358 deletions

View file

@ -14,17 +14,13 @@ import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus; import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity; import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.entities.Guild; 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.interactions.commands.build.SubcommandData;
import net.dv8tion.jda.api.requests.GatewayIntent; import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.utils.ChunkingFilter; import net.dv8tion.jda.api.utils.ChunkingFilter;
import net.dv8tion.jda.api.utils.MemberCachePolicy; import net.dv8tion.jda.api.utils.MemberCachePolicy;
import net.dv8tion.jda.api.utils.cache.CacheFlag; import net.dv8tion.jda.api.utils.cache.CacheFlag;
import org.simpleyaml.configuration.file.YamlConfiguration; 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.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.InputStream; import java.io.InputStream;
@ -32,6 +28,8 @@ import java.nio.file.Files;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.util.List; import java.util.List;
import static moe.oko.Kiafumi.util.LoggingManager.*;
/** /**
* Kiafumi Main Class * Kiafumi Main Class
* @author Kay, oko, Tiddy * @author Kay, oko, Tiddy
@ -50,8 +48,6 @@ public class Kiafumi {
public YamlConfiguration yamlConfiguration = new YamlConfiguration(); public YamlConfiguration yamlConfiguration = new YamlConfiguration();
public Logger logger = LoggerFactory.getLogger("Kiafumi");
public String footer = EmbedUI.BRAND + " 0.9.0-pre"; public String footer = EmbedUI.BRAND + " 0.9.0-pre";
public static Kiafumi instance; public static Kiafumi instance;
@ -63,7 +59,6 @@ public class Kiafumi {
public KiafumiConfig config; public KiafumiConfig config;
public KiafumiDB database; public KiafumiDB database;
public ServerManager serverManager; public ServerManager serverManager;
/** /**
@ -85,8 +80,7 @@ public class Kiafumi {
*/ */
public void start() { public void start() {
instance = this; instance = this;
info("Starting Kiafumi.");
logger.info("Starting Kiafumi.");
// All commands to be loaded on startup! // All commands to be loaded on startup!
activeCommands = new CommandRegistrar().getCommandClasses(); activeCommands = new CommandRegistrar().getCommandClasses();
@ -97,7 +91,7 @@ public class Kiafumi {
// Save the default config // Save the default config
Files.copy(is, CONFIG_FILE.toPath()); Files.copy(is, CONFIG_FILE.toPath());
} catch (Exception ex) { } 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(); ex.printStackTrace();
return; return;
} }
@ -108,23 +102,23 @@ public class Kiafumi {
yamlConfiguration.load("config.yml"); yamlConfiguration.load("config.yml");
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
logger.warn("File not found, must've failed to create..."); warn("File not found, must've failed to create...");
} catch (Exception e) { } catch (Exception e) {
logger.warn("Ensure all values are inputted properly."); warn("Ensure all values are inputted properly.");
e.printStackTrace(); e.printStackTrace();
} }
// Initializes our configuration helper & ensures it loads properly. // Initializes our configuration helper & ensures it loads properly.
config = new KiafumiConfig(yamlConfiguration); config = new KiafumiConfig(yamlConfiguration);
if(config.load()) { if(config.load()) {
logger.info("Fetched Kiafumi config."); info("Fetched Kiafumi config.");
} else { } else {
logger.error("Failed to load configuration. Stopping process."); error("Failed to load configuration. Stopping process.");
Runtime.getRuntime().exit(0); Runtime.getRuntime().exit(0);
} }
// Registers the stop() function if the program is stopped. // 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)); Runtime.getRuntime().addShutdownHook(new Thread(this::stop));
// Initializes database and loads credentials. // Initializes database and loads credentials.
@ -250,34 +244,6 @@ public class Kiafumi {
debug("Registered " + i + " commands for guild [" + guild.getId() + "]"); 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. // Gets the active database.
public KiafumiDB getDatabase() { return database; } public KiafumiDB getDatabase() { return database; }

View file

@ -5,8 +5,8 @@ import org.simpleyaml.configuration.file.YamlConfiguration;
import java.util.List; import java.util.List;
import static moe.oko.Kiafumi.Kiafumi.error; import static moe.oko.Kiafumi.util.LoggingManager.error;
import static moe.oko.Kiafumi.Kiafumi.info; import static moe.oko.Kiafumi.util.LoggingManager.info;
/** /**
* KiafumiConfig class * KiafumiConfig class
@ -63,8 +63,6 @@ public class KiafumiConfig {
*/ */
public boolean load() { public boolean load() {
try { try {
var n = System.lineSeparator() + "\033[0m"; // newline
// Discord loaders // Discord loaders
var discord = configuration.getConfigurationSection("discord"); var discord = configuration.getConfigurationSection("discord");
token = discord.getString("token"); // This used to log the token into stdout ??? token = discord.getString("token"); // This used to log the token into stdout ???
@ -74,14 +72,15 @@ public class KiafumiConfig {
clientId = discord.getString("clientId"); clientId = discord.getString("clientId");
defaultInvitePermissionLevel = discord.getInt("invitePermissionLevel"); defaultInvitePermissionLevel = discord.getInt("invitePermissionLevel");
// Log discord settings in a neat table. // Log discord settings in a neat table.
info("Printing loaded discord configuration." +n+ info("""
"DISCORD CONFIGURATION" +n+ Printing loaded discord configuration.
"--------------------------------" +n+ DISCORD CONFIGURATION
"Log Channel: \033[0;34m" + logChannel +n+ --------------------------------
"Owner ID: \033[0;34m" + ownerId +n+ Log Channel: %s
"Primary Guild: \033[0;34m" + mainGuild +n+ Owner ID: %s
"Invite URL: \033[0;34m" + assembleDefaultInvite() +n+ Primary Guild: %s
"--------------------------------"); Invite URL: %s
--------------------------------""".formatted(logChannel, ownerId, mainGuild, assembleDefaultInvite()));
// Kiafumi loaders // Kiafumi loaders
var main = configuration.getConfigurationSection("main"); var main = configuration.getConfigurationSection("main");

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,111 +0,0 @@
package moe.oko.Kiafumi.command.moderation;
import moe.oko.Kiafumi.Kiafumi;
import moe.oko.Kiafumi.command.CommandClass;
import moe.oko.Kiafumi.model.Server;
import moe.oko.Kiafumi.util.CommandInfo;
import moe.oko.Kiafumi.util.CommandType;
import moe.oko.Kiafumi.util.EmbedUI;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import java.util.ArrayList;
import java.util.List;
import static moe.oko.Kiafumi.Kiafumi.slashLog;
/**
* For use on Guilds that tend to get TOS'd with ease. Also just basic server protection
* @author Kay
* (Requires Permission.ADMINISTRATOR to function properly)
*/
@Deprecated
public class ModCommand extends CommandClass {
@Override
public boolean isEnabled() {
return true;
}
@Override
public String getName() {
return "Moderation";
}
@Override
public void newCommand(String name, SlashCommandInteractionEvent e) {
if(e.getGuild() == null) { return; }
var server = Kiafumi.instance.getServerManager().getOrCreateServer(e.getGuild());
switch (name) {
case "mod":
slashLog(e);
e.deferReply(true).queue();
if(server.isServerProtected()) {
// Start check.
if(server.getModRole() != null) {
if(e.getMember().isOwner()) {
e.getHook().sendMessage("*Owners cannot run this command.*").queue();
return;
}
if(hasModRole(e.getMember(), server)) {
if(isAdmin(e.getMember())) {
// They already have the admin role... So we try removing our mod role in case thats it
removeModRole(e.getMember());
e.getHook().sendMessage("**Admin Mode Disabled.**").queue();
} else {
if(applyModRole(e.getMember())) {
e.getHook().sendMessage("**Admin Mode Enabled.**").queue();
}
}
}
return;
} else {
e.getHook().sendMessage("*This server does not have a moderator role set.*").queue();
return;
}
} else {
e.getHook().sendMessage("*This server does not have protection enabled. This command will not function.*").queue();
return;
}
}
}
public boolean isAdmin(Member member) {
return member.hasPermission(Permission.ADMINISTRATOR);
}
public boolean hasModRole(Member member, Server server) {
return member.getRoles().contains(Kiafumi.JDA.getRoleById(server.getModRole()));
}
public boolean applyModRole(Member member) {
if(member.getGuild().getRolesByName("senior citizen", true).get(0) != null) {
member.getGuild().addRoleToMember(member, member.getGuild().getRolesByName("senior citizen", true).get(0)).queue();
return true;
} else {
// Create, role doesn't exist
member.getGuild().createRole()
.setColor(EmbedUI.INFO)
.setName("senior citizen")
.setPermissions(Permission.ADMINISTRATOR)
.setMentionable(false)
.setHoisted(true)
.complete();
// should be created so rerun
return applyModRole(member);
}
}
public void removeModRole(Member member) {
if(member.getGuild().getRolesByName("senior citizen", true).get(0) != null) {
member.getGuild().removeRoleFromMember(member, member.getGuild().getRolesByName("senior citizen", true).get(0)).queue();
} // Role must've been deleted otherwise, :thinking:
}
@Override
public List<CommandInfo> getSlashCommandInfo() {
List<CommandInfo> cil = new ArrayList<>();
cil.add(new CommandInfo("mod", "Toggles administrative permissions you.", CommandType.COMMAND));
return cil;
}
}

View file

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

View file

@ -14,7 +14,7 @@ import java.time.ZonedDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; 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) * Helpful Search Command (Uses DDG API)

View file

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

View file

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

View file

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

View file

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

View file

@ -15,8 +15,8 @@ import java.time.ZonedDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static moe.oko.Kiafumi.Kiafumi.slashLog; import static moe.oko.Kiafumi.util.LoggingManager.slashLog;
import static moe.oko.Kiafumi.Kiafumi.slashResponse; import static moe.oko.Kiafumi.util.LoggingManager.slashResponse;
/** /**
* Permits modification of server settings, critical class to functionality. * 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 java.time.ZonedDateTime;
import static moe.oko.Kiafumi.Kiafumi.info; import static moe.oko.Kiafumi.util.LoggingManager.info;
/** /**
* Main Listener * Main Listener
@ -37,12 +37,12 @@ public class MainListener extends ListenerAdapter {
*/ */
@Override @Override
public void onReady(@NotNull ReadyEvent event) { public void onReady(@NotNull ReadyEvent event) {
var n = System.lineSeparator(); info("""
info("Received READY signal from Discord, bot is now logged in." +n+ Received READY signal from Discord, bot is now logged in.
"--------------------------------" +n+ --------------------------------
"Active Guilds: " + event.getGuildAvailableCount() +n+ Active Guilds: [%s]
"Guilds Unavailable: " + event.getGuildUnavailableCount() +n+ Guilds Unavailable: [%s]
"--------------------------------"); --------------------------------""".formatted(event.getGuildAvailableCount(), event.getGuildUnavailableCount()));
} }
/** /**

View file

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

View file

@ -8,7 +8,7 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import static moe.oko.Kiafumi.Kiafumi.*; import static moe.oko.Kiafumi.util.LoggingManager.*;
/** /**
* Kiafumi DB Class * Kiafumi DB Class
@ -17,17 +17,17 @@ import static moe.oko.Kiafumi.Kiafumi.*;
* @apiNote I HATE SQL I HATE SQL AAAAAAAAAAAAAA * @apiNote I HATE SQL I HATE SQL AAAAAAAAAAAAAA
*/ */
public class KiafumiDB { public class KiafumiDB {
//Our actual MySQL Connection, this is created on class construction. // Our actual MySQL Connection, this is created on class construction.
private Connection connection; private Connection connection;
//The prepared statement strings // The prepared statement strings
private final String CREATE_SERVERINFO_TABLE = "CREATE TABLE IF NOT EXISTS `serverInfo`" + private final String CREATE_SERVERINFO_TABLE = "CREATE TABLE IF NOT EXISTS `serverInfo`" +
"(`id` LONGTEXT NOT NULL,`welcomeEnabled` TINYINT NOT NULL,`welcomeChannel` LONGTEXT NULL, joinRole LONGTEXT NULL, `serverProtected` TINYINT NOT NULL, `modRole` LONGTEXT NULL);"; "(`id` LONGTEXT NOT NULL, `welcomeChannel` LONGTEXT NULL, `modChannel` LONGTEXT NULL, joinRole LONGTEXT NULL);";
private final String INSERT_SERVERINFO_DEFAULT = "INSERT INTO serverInfo(id,welcomeEnabled,welcomeChannel, joinRole, serverProtected, modRole) 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 SERVERINFO_EXISTS = "select * from serverInfo where id = ?";
private final String SERVER_INFO_LOAD = "select * from serverInfo"; private final String SERVER_INFO_LOAD = "select * from serverInfo";
//1 = welcomeEnabled, 2 = welcomeChannel, 3 = joinRole, 4 = serverProtected, 5 = Guild_ID (non-changeable) // 1 = welcomeChannel, 2 = modChannel , 3 = joinRole, 4 = Guild_ID (immutable)
private final String SERVER_INFO_MODIFY = "UPDATE `serverInfo` SET welcomeEnabled=?, welcomeChannel=?, joinRole=?,serverProtected=?, modRole=? WHERE id = ?"; private final String SERVER_INFO_MODIFY = "UPDATE `serverInfo` SET welcomeChannel=?, modChannel=?, joinRole=? WHERE id = ?";
/** /**
* KiafumiDB Config Constructor * KiafumiDB Config Constructor
@ -41,7 +41,7 @@ public class KiafumiDB {
try { try {
connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + db, username, password); connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + db, username, password);
} catch (Exception ex) { } catch (Exception ex) {
error("Failed to initialize the MySQL instance. Contact a developer."); error("Failed to initialize the MySQL instance.");
ex.printStackTrace(); ex.printStackTrace();
return; return;
} }
@ -81,11 +81,9 @@ public class KiafumiDB {
//Proceed with making defaults. //Proceed with making defaults.
PreparedStatement ps = connection.prepareStatement(INSERT_SERVERINFO_DEFAULT); PreparedStatement ps = connection.prepareStatement(INSERT_SERVERINFO_DEFAULT);
ps.setString(1, guild.getId()); ps.setString(1, guild.getId());
ps.setInt(2, 0); //default is false. ps.setNull(2, Types.LONGVARCHAR);
ps.setNull(3, Types.LONGVARCHAR); ps.setNull(3, Types.LONGVARCHAR);
ps.setNull(4, Types.LONGVARCHAR); ps.setNull(4, Types.LONGVARCHAR);
ps.setInt(5, 0); //Falseeeee
ps.setNull(6, Types.LONGVARCHAR);
ps.execute(); ps.execute();
return true; return true;
} catch (Exception ex) { } catch (Exception ex) {
@ -107,24 +105,10 @@ public class KiafumiDB {
while(rs.next()) { while(rs.next()) {
info("Starting new load for server: " + rs.getString(1)); info("Starting new load for server: " + rs.getString(1));
String id = rs.getString(1); String id = rs.getString(1);
boolean welcomeEnabled = false; String welcomeChannel = rs.getString(2);
switch(rs.getInt(2)) { String modChannel = rs.getString(3);
case 0:
welcomeEnabled = false;
case 1:
welcomeEnabled = true;
}
String welcomeChannel = rs.getString(3);
String joinRole = rs.getString(4); String joinRole = rs.getString(4);
boolean protectionEnabled = false; Server server = new Server(id, welcomeChannel, modChannel, joinRole);
switch(rs.getInt(5)) {
case 0:
protectionEnabled = false;
case 1:
protectionEnabled = true;
}
String modRole = rs.getString(6);
Server server = new Server(id, welcomeEnabled, welcomeChannel, joinRole, protectionEnabled, modRole);
debug("Loaded " + server + "from database."); debug("Loaded " + server + "from database.");
servers.add(server); servers.add(server);
} }
@ -144,19 +128,19 @@ public class KiafumiDB {
Collection<Server> servers = Kiafumi.instance.getServerManager().getServers(); Collection<Server> servers = Kiafumi.instance.getServerManager().getServers();
info("Starting save on " + servers.size() + " servers."); info("Starting save on " + servers.size() + " servers.");
try { try {
//1 = welcomeEnabled, 2 = welcomeChannel, 3 = joinRole, 4 = serverProtected, 5 = modRole 6 = Guild_ID (non-changeable) // 1 = welcomeChannel, 2 = modChannel, 3 = joinRole, 4 = Guild_ID (immutable)
PreparedStatement ps = connection.prepareStatement(SERVER_INFO_MODIFY); PreparedStatement ps = connection.prepareStatement(SERVER_INFO_MODIFY);
int i = 0; int i = 0;
for (Server server : servers) { for (Server server : servers) {
if(!server.isModified()) { continue; } //Skip, non modified server. if(!server.isModified()) { continue; } // Skip, unmodified server.
info("Starting save on modified " + server); info("Starting save on modified " + server);
if(server.isWelcomeEnabled()) {
ps.setInt(1, 1);
} else {
ps.setInt(1, 0);
}
if(server.getWelcomeChannel() != null) { if(server.getWelcomeChannel() != null) {
ps.setString(2, server.getWelcomeChannel()); ps.setString(1, server.getWelcomeChannel());
} else {
ps.setNull(1, Types.LONGVARCHAR);
}
if(server.getModChannel() != null) {
ps.setString(2, server.getModChannel());
} else { } else {
ps.setNull(2, Types.LONGVARCHAR); ps.setNull(2, Types.LONGVARCHAR);
} }
@ -165,17 +149,7 @@ public class KiafumiDB {
} else { } else {
ps.setNull(3, Types.LONGVARCHAR); ps.setNull(3, Types.LONGVARCHAR);
} }
if(server.isServerProtected()) { ps.setString(4, server.getId());
ps.setInt(4, 1);
} else {
ps.setInt(4, 0);
}
if(server.getModRole() != null) {
ps.setString(5, server.getModRole());
} else {
ps.setNull(5, Types.LONGVARCHAR);
}
ps.setString(6, server.getId());
ps.addBatch(); ps.addBatch();
i++; i++;
} }

View file

@ -11,18 +11,14 @@ import javax.annotation.Nullable;
* @implNote This class is where all server info is stored per-server, so be liberal with additions. * @implNote This class is where all server info is stored per-server, so be liberal with additions.
*/ */
public class Server { public class Server {
//Guild ID // Guild ID
private String id; private String id;
//Whether the welcome feature is enabled (Join/Leave Logs) // The channel for welcome logs to be posted to.
private boolean welcomeEnabled;
//If enabled, the channel for logs to be posted to.
private String welcomeChannel; private String welcomeChannel;
//The role to be assigned on join, if null ignored. // The role to be assigned on join, if null ignored.
private String joinRole; private String joinRole;
//TODO Whether the server has protections enabled (do protections)
private boolean serverProtected;
//Moderation role, used for /mod //Moderation role, used for /mod
private String modRole; private String modChannel;
//If the server has been modified in memory, for saving persistently. //If the server has been modified in memory, for saving persistently.
private boolean modified; private boolean modified;
@ -32,28 +28,22 @@ public class Server {
*/ */
public Server(String id) { public Server(String id) {
this.id = id; this.id = id;
this.welcomeEnabled = false;
this.welcomeChannel = null; this.welcomeChannel = null;
this.modChannel = null;
this.joinRole = null; this.joinRole = null;
this.serverProtected = false;
this.modRole = null;
this.modified = false; this.modified = false;
} }
/** /**
* Database Constructor * Database Constructor
* @param id - id of the server * @param id - id of the server
* @param welcomeEnabled - is welcome enabled for the server
* @param welcomeChannel - channel for welcome messages, if enabled * @param welcomeChannel - channel for welcome messages, if enabled
* @param serverProtected - is the server under protection rules. (/archive, /stop, etc.)
*/ */
public Server(String id, boolean welcomeEnabled, @Nullable String welcomeChannel, @Nullable String joinRole, boolean serverProtected, String modRole) { public Server(String id, @Nullable String welcomeChannel, @Nullable String joinRole, String modChannel) {
this.id = id; this.id = id;
this.welcomeEnabled = welcomeEnabled;
this.welcomeChannel = welcomeChannel; this.welcomeChannel = welcomeChannel;
this.modChannel = modChannel;
this.joinRole = joinRole; this.joinRole = joinRole;
this.serverProtected = serverProtected;
this.modRole = modRole;
this.modified = false; this.modified = false;
} }
@ -61,28 +51,17 @@ public class Server {
public String getJoinRole() { return joinRole; } public String getJoinRole() { return joinRole; }
public String getModRole() { return modRole; } public String getModChannel() { return modChannel; }
public boolean isWelcomeEnabled() {
return welcomeEnabled;
}
public String getWelcomeChannel() { public String getWelcomeChannel() {
return welcomeChannel; return welcomeChannel;
} }
public boolean isServerProtected() { return serverProtected; }
public void setJoinRole(String joinRole) { public void setJoinRole(String joinRole) {
this.modified = true; this.modified = true;
this.joinRole = joinRole; this.joinRole = joinRole;
} }
public void setWelcomeEnabled(boolean welcomeEnabled) {
this.modified = true;
this.welcomeEnabled = welcomeEnabled;
}
public void setWelcomeChannel(String welcomeChannel) { public void setWelcomeChannel(String welcomeChannel) {
this.modified = true; this.modified = true;
this.welcomeChannel = welcomeChannel; this.welcomeChannel = welcomeChannel;
@ -101,11 +80,10 @@ public class Server {
* @return - Options in a string that can be printed to discord. * @return - Options in a string that can be printed to discord.
*/ */
public String getOpts() { public String getOpts() {
return "welcomeEnabled - whether or not join/leave logs are enabled" + return """
"\nwelcomeChannel - the channel to send welcome messages to" + welcomeChannel - the channel to send welcome messages to
"\njoinRole - the role to apply to new members who join this guild" + modChannel - the channel to send moderation logs to
"\nserverProtected - Determines whether or not server protections are enabled." + joinRole - the role to apply to new members who join this guild""";
"\nmodRole - The moderator role for the /mod command (only works if protection enabled)";
} }
/** /**
@ -114,28 +92,12 @@ public class Server {
* @return - the value (if applicable) to return * @return - the value (if applicable) to return
*/ */
public String getOptionByString(String string) { public String getOptionByString(String string) {
switch(string.toLowerCase()) { return switch (string.toLowerCase()) {
case "welcomeenabled": case "joinrole" -> joinRole;
if(!welcomeEnabled) { case "welcomechannel" -> welcomeChannel;
return "False"; case "modchannel" -> modChannel;
} else { default -> "INVALID";
return "True"; };
}
case "joinrole":
return joinRole;
case "welcomechannel":
return welcomeChannel;
case "serverprotected":
if(!serverProtected) {
return "False";
} else {
return "True";
}
case "modrole":
return modRole;
default:
return "INVALID";
}
} }
/** /**
@ -145,21 +107,15 @@ public class Server {
*/ */
public String resetOptionByString(String name) { public String resetOptionByString(String name) {
switch(name.toLowerCase()) { switch(name.toLowerCase()) {
case "welcomeenabled":
welcomeEnabled = false;
return "Reset Join/Leave logs to default.";
case "joinrole": case "joinrole":
joinRole = null; joinRole = null;
return "Auto-role on join is now set to disabled (Default)."; return "Auto-role on join is now set to disabled (Default).";
case "welcomechannel": case "welcomechannel":
welcomeChannel = null; welcomeChannel = null;
return "Welcome channel is now unset."; return "Welcome channel is now unset.";
case "serverprotected": case "modchannel":
serverProtected = true; modChannel = null;
return "Server protection set to default."; return "Mod channel is now unset.";
case "modrole":
modRole = null;
return "Mod role is now unset.";
default: default:
return "INVALID SETTING"; return "INVALID SETTING";
} }
@ -172,18 +128,8 @@ public class Server {
* @return - whether the name and value were valid and the option was set. * @return - whether the name and value were valid and the option was set.
*/ */
public String setOptionByString(String name, String value) { public String setOptionByString(String name, String value) {
modified = true; //If this is being used just tell it it's been modified. modified = true; // If this is being used set it to modified.
switch (name.toLowerCase()) { switch (name.toLowerCase()) {
case "welcomeenabled":
if(value.equalsIgnoreCase("false")) {
welcomeEnabled = false;
return "Join/Leave logs are now disabled.";
} else if(value.equalsIgnoreCase("true")) {
welcomeEnabled = true;
return "Join/Leave logs are now enabled. Make sure you set the `welcomeChannel` setting.";
} else {
return "Bad Value, use either true or false";
}
case "joinrole": case "joinrole":
try { try {
if (Kiafumi.JDA.getRoleById(value) == null) { if (Kiafumi.JDA.getRoleById(value) == null) {
@ -206,23 +152,13 @@ public class Server {
} catch (Exception ex) { } catch (Exception ex) {
return "Bad Value"; return "Bad Value";
} }
case "serverprotected": case "modchannel":
if(value.equalsIgnoreCase("false")) {
serverProtected = false;
return "Server protection is now disabled.";
} else if(value.equalsIgnoreCase("true")) {
serverProtected = true;
return "Server protection is now enabled.";
} else {
return "Bad Value, use either true or false";
}
case "modrole":
try { try {
if(Kiafumi.JDA.getRoleById(value) == null) { if(Kiafumi.JDA.getRoleById(value) == null) {
return "That role ID is invalid."; return "That role ID is invalid.";
} else { } else {
modRole = value; modChannel = value;
return "Successfully set modRole ID to " + modRole; return "Successfully set modChannel ID to " + modChannel;
} }
} catch (Exception ex) { } catch (Exception ex) {
return "Bad Value"; return "Bad Value";
@ -234,7 +170,7 @@ public class Server {
@Override @Override
public String toString() { public String toString() {
return "Server{id=" + this.id + ",welcomeEnabled=" + welcomeEnabled + ",welcomeChannel="+welcomeChannel+ return "Server [id=" + this.id + ",welcomeChannel="+welcomeChannel+
",joinrole=" + joinRole +",serverProtected="+serverProtected+ ",modRole=" + modRole +"}"; ",joinrole=" + joinRole + ",modChannel=" + modChannel +"]";
} }
} }

View file

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

View file

@ -0,0 +1,48 @@
package moe.oko.Kiafumi.util;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
/**
* Logging Class
* Provides static logging & extensible template messages.
* @author oko
*/
public class LoggingManager {
private static final Logger logger = LoggerFactory.getLogger("Kiafumi");
// Static logging reference
public static void debug(String str) { logger.debug(str); }
public static void info(String str) { logger.info(str); }
public static void warn(String str) { logger.warn(str); }
public static void error(String str) { logger.error(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) {
var user = event.getUser();
info("""
User [%s:%s] ran command: "%s" %s"""
.formatted(user.getName(), user.getId(), event.getName(), msg == null ? "" : msg));
}
public static void slashLog(SlashCommandInteractionEvent event) {
var user = event.getUser();
info("""
User [%s:%s] ran command: "%s"."""
.formatted(user.getName(), user.getId(), event.getName()));
}
public static void slashResponse(SlashCommandInteractionEvent event, String msg) {
var user = event.getUser();
info("""
User [%s:%s] was provided response: "%s\"""".formatted(user.getName(), user.getId(), msg));
}
}