General Cleanup in preparation for 0.9

& bump version to 0.9.0-pre
This commit is contained in:
Anya 2022-05-16 18:50:46 -07:00
parent 2659a0ac52
commit d46bb83e5e
21 changed files with 181 additions and 190 deletions

View file

@ -7,7 +7,7 @@
<groupId>moe.oko</groupId> <groupId>moe.oko</groupId>
<artifactId>Kiafumi</artifactId> <artifactId>Kiafumi</artifactId>
<name>Kiafumi</name> <name>Kiafumi</name>
<version>0.8.0-pre</version> <version>0.9.0-pre</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<url>https://oko.moe/kiafumi.htm</url> <url>https://oko.moe/kiafumi.htm</url>

View file

@ -1,6 +1,7 @@
package moe.oko.Kiafumi; package moe.oko.Kiafumi;
import moe.oko.Kiafumi.command.*; import moe.oko.Kiafumi.command.CommandClass;
import moe.oko.Kiafumi.command.CommandRegistrar;
import moe.oko.Kiafumi.listener.MainListener; import moe.oko.Kiafumi.listener.MainListener;
import moe.oko.Kiafumi.model.KiafumiDB; import moe.oko.Kiafumi.model.KiafumiDB;
import moe.oko.Kiafumi.model.ServerManager; import moe.oko.Kiafumi.model.ServerManager;
@ -12,9 +13,9 @@ 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.requests.restaction.CommandCreateAction;
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;
@ -22,6 +23,7 @@ import org.simpleyaml.configuration.file.YamlConfiguration;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 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,7 +34,7 @@ import java.util.List;
/** /**
* Kiafumi Main Class * Kiafumi Main Class
* @author Kay, oko, Tiddy * @author Kay, oko, Tiddy
* @version 0.8.0-pre * @version 0.9.0-pre
* @apiNote Thanks to: * @apiNote Thanks to:
* | Maxopoly, Orinnari, ProgrammerDan, and more, for helping teach Kay how to code Java from scratch. * | Maxopoly, Orinnari, ProgrammerDan, and more, for helping teach Kay how to code Java from scratch.
* | Favna, and the HC Development community for encouraging the development core of HC. * | Favna, and the HC Development community for encouraging the development core of HC.
@ -49,6 +51,8 @@ public class Kiafumi {
public Logger logger = LoggerFactory.getLogger("Kiafumi"); public Logger logger = LoggerFactory.getLogger("Kiafumi");
public String footer = EmbedUI.BRAND + " 0.9.0-pre";
public static Kiafumi instance; public static Kiafumi instance;
public static JDA JDA; public static JDA JDA;
@ -62,15 +66,15 @@ public class Kiafumi {
public ServerManager serverManager; public ServerManager serverManager;
/** /**
* Main Class function, makes the classes work or some shit. * Main Class function.
* @param args - Arguments for program start. * @param args - Arguments for program start.
*/ */
public static void main(String[] args) { public static void main(String[] args) {
try { try {
Kiafumi kia = new Kiafumi(); var kia = new Kiafumi();
kia.start(); kia.start();
} catch (Exception ex) { } catch (Exception ex) {
System.out.println("Failed to start Kiafumi Instance, check your Java installation."); System.out.println("Failed to start Kiafumi, check your Java installation.");
ex.printStackTrace(); ex.printStackTrace();
} }
} }
@ -83,17 +87,15 @@ public class Kiafumi {
logger.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();
//Logger check
System.out.println("If no other messages are present, logger failed to instantiate.");
logger.info("Config load start..."); logger.info("Config load start...");
//Ensuring the configuration file is generated and/or exists. // Ensuring the configuration file is generated and/or exists.
if (!CONFIG_FILE.exists()) { if (!CONFIG_FILE.exists()) {
try (InputStream is = this.getClass().getClassLoader().getResourceAsStream("config.yml")) { try (InputStream is = this.getClass().getClassLoader().getResourceAsStream("config.yml")) {
//Save the default cfg // 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() + ")"); logger.warn("Failed to create the configuration file. Stopping. (" + CONFIG_FILE.getAbsolutePath() + ")");
@ -102,7 +104,7 @@ public class Kiafumi {
} }
} }
//Try to load configuration into our local friendly configuration API. // Try to load configuration into the configuration API.
try { try {
yamlConfiguration.load("config.yml"); yamlConfiguration.load("config.yml");
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
@ -113,27 +115,25 @@ public class Kiafumi {
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("Config loaded, proceeding."); logger.info("Fetched Kiafumi config.");
} else { } else {
logger.error("Failed to load configuration. Stopping process."); logger.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."); logger.info("Registering shutdown hook.");
Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); Runtime.getRuntime().addShutdownHook(new Thread(this::stop));
//We have the prefix as a static thing that can be referenced anywhere, this is for simplicity. // Initializes database and loads credentials.
//Initializes database and loads credentials.
database = config.createDb(); database = config.createDb();
serverManager = new ServerManager(); serverManager = new ServerManager();
//Makes our JDA instance. // Makes our JDA instance.
startDiscord(); startDiscord();
} }
@ -141,12 +141,12 @@ public class Kiafumi {
* Ran on program shutdown. * Ran on program shutdown.
*/ */
public void stop() { public void stop() {
EmbedBuilder build = new EmbedBuilder() var build = new EmbedBuilder()
.setColor(EmbedUI.FAILURE) .setColor(EmbedUI.FAILURE)
.setFooter(EmbedUI.BRAND) .setAuthor("Kiafumi", null, Kiafumi.JDA.getSelfUser().getAvatarUrl())
.setTimestamp(ZonedDateTime.now())
.setTitle("Offline") .setTitle("Offline")
.setDescription("Shutdown SIGINT Received."); .setFooter(footer)
.setTimestamp(ZonedDateTime.now());
JDA.getTextChannelById(config.getLogChannel()).sendMessageEmbeds(build.build()).queue(); JDA.getTextChannelById(config.getLogChannel()).sendMessageEmbeds(build.build()).queue();
if(database.saveServerInformation()) { if(database.saveServerInformation()) {
info("Successfully saved server information. Shutting down peacefully."); info("Successfully saved server information. Shutting down peacefully.");
@ -180,11 +180,11 @@ public class Kiafumi {
registerAllCommands(); registerAllCommands();
info("Loaded " + activeCommands.size() + " commands."); info("Loaded " + activeCommands.size() + " commands.");
EmbedBuilder eb = new EmbedBuilder() var eb = new EmbedBuilder()
.setColor(EmbedUI.SUCCESS) .setColor(EmbedUI.SUCCESS)
.setAuthor("Kiafumi", null, Kiafumi.JDA.getSelfUser().getAvatarUrl()) .setAuthor("Kiafumi", null, Kiafumi.JDA.getSelfUser().getAvatarUrl())
.setTitle("Online") .setTitle("Online")
.setFooter("Created by Oko, Laika, and Tiddy") .setFooter(footer)
.setTimestamp(ZonedDateTime.now()); .setTimestamp(ZonedDateTime.now());
JDA.getTextChannelById(config.getLogChannel()).sendMessageEmbeds(eb.build()).queue(); JDA.getTextChannelById(config.getLogChannel()).sendMessageEmbeds(eb.build()).queue();
} }
@ -193,12 +193,12 @@ public class Kiafumi {
* Quick method to register commands in all servers. * Quick method to register commands in all servers.
*/ */
private void registerAllCommands() { private void registerAllCommands() {
//Registers our slash commands // Registers slash commands.
for(Guild guild : JDA.getGuilds()) { for(Guild guild : JDA.getGuilds()) {
registerForGuild(guild); registerForGuild(guild);
} }
//Registers the event listeners for those commands. // Registers the event listeners for those commands.
for(CommandClass cmd : activeCommands) { for(CommandClass cmd : activeCommands) {
JDA.addEventListener(cmd); JDA.addEventListener(cmd);
} }
@ -209,16 +209,16 @@ public class Kiafumi {
* @param guild - guild to have commands provided to * @param guild - guild to have commands provided to
*/ */
public void registerForGuild(Guild guild) { public void registerForGuild(Guild guild) {
info("Registering commands for Guild[" + guild.getId() + "]"); info("Registering commands for guild [" + guild.getId() + "]");
int i = 0; int i = 0;
for(CommandClass cmd : activeCommands) { for(CommandClass cmd : activeCommands) {
for(CommandInfo ci : cmd.getSlashCommandInfo()) { for(CommandInfo ci : cmd.getSlashCommandInfo()) {
CommandCreateAction cca = guild.upsertCommand(ci.getName(), ci.getDescription()); var cca = guild.upsertCommand(ci.getName(), ci.getDescription());
i++; i++;
if(ci.hasSubCommands()) { if(ci.hasSubCommands()) {
for (String name : ci.getSubCommands().keySet()) { for (String name : ci.getSubCommands().keySet()) {
CommandInfo si = ci.getSubCommands().get(name); var si = ci.getSubCommands().get(name);
SubcommandData sd = new SubcommandData(si.getName(), si.getDescription()); var sd = new SubcommandData(si.getName(), si.getDescription());
for (String option : si.getOptions().keySet()) { for (String option : si.getOptions().keySet()) {
sd.addOption(si.getOptions().get(option), option, si.getOptionDescriptions().get(option), si.getOptionRequirements().get(option)); sd.addOption(si.getOptions().get(option), option, si.getOptionDescriptions().get(option), si.getOptionRequirements().get(option));
} }
@ -227,21 +227,21 @@ public class Kiafumi {
} }
if(ci.hasOptions()) { if(ci.hasOptions()) {
for(String name : ci.getOptions().keySet()) { for(String name : ci.getOptions().keySet()) {
//Any intelligent IDE will rage about the option not being used, it's added to the action then executed later, DO not edit this (please). // Any intelligent IDE will rage about the option not being used, it's added to the action then executed later, don't edit without reason.
cca.addOption(ci.getOptions().get(name), name, ci.getOptionDescriptions().get(name), ci.getOptionRequirements().get(name)); cca.addOption(ci.getOptions().get(name), name, ci.getOptionDescriptions().get(name), ci.getOptionRequirements().get(name));
} }
} }
//Push w/ modifications. // Push w/ modifications.
//commented for spam sake info("Command: " + ci.getName() + " registration on " + guild.getId() + " completed."); //info("Command: " + ci.getName() + " registration on " + guild.getId() + " completed.");
try { try {
cca.queue(); cca.queue();
} catch (Exception ex) { } catch (Exception ex) {
//Only time this *should* occur is in the event of a server not having the proper scope. // Only time this should occur is when a server does not have the proper scope.
error("Failed to queue command for RestAction, not printing stack to avoid console spam."); error("Failed to queue command for RestAction.");
} }
} }
} }
info("Registered " + i + " commands. On Guild[" + guild.getId() + "] \uD83D\uDC4D -> \uD83D\uDCA5"); info("Registered " + i + " commands for guild [" + guild.getId() + "]");
} }
/* /*
@ -258,9 +258,26 @@ public class Kiafumi {
instance.logger.error(str); instance.logger.error(str);
} }
//Gets the active database. /**
* 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 " + event.getName() + "." + (msg == null ? "" : msg));
}
public static void slashLog(SlashCommandInteractionEvent event) {
info("User[" + event.getUser().getName() + ":" + event.getUser().getId() + "] RAN " + event.getName() + ".");
}
public static void slashResponse(SlashCommandInteractionEvent event, String msg) {
info("User[" + event.getUser().getName() + ":" + event.getUser().getId() + "] CMD RESPONSE: " + msg);
}
// Gets the active database.
public KiafumiDB getDatabase() { return database; } public KiafumiDB getDatabase() { return database; }
//Gets active ServerManager // Gets active ServerManager
public ServerManager getServerManager() { return serverManager; } public ServerManager getServerManager() { return serverManager; }
} }

View file

@ -1,7 +1,6 @@
package moe.oko.Kiafumi; package moe.oko.Kiafumi;
import moe.oko.Kiafumi.model.KiafumiDB; import moe.oko.Kiafumi.model.KiafumiDB;
import org.simpleyaml.configuration.ConfigurationSection;
import org.simpleyaml.configuration.file.YamlConfiguration; import org.simpleyaml.configuration.file.YamlConfiguration;
import java.util.List; import java.util.List;
@ -15,7 +14,7 @@ import static moe.oko.Kiafumi.Kiafumi.info;
*/ */
public class KiafumiConfig { public class KiafumiConfig {
//Our nice YamlConfiguration class. // Setup
public YamlConfiguration configuration; public YamlConfiguration configuration;
/* /*
@ -66,22 +65,26 @@ public class KiafumiConfig {
*/ */
public boolean load() { public boolean load() {
try { try {
//Discord loaders var n = System.lineSeparator(); // newline
info("Starting Discord Configuration load"); info("Starting Discord configuration load");
ConfigurationSection discord = configuration.getConfigurationSection("discord");
token = discord.getString("token"); // Discord loaders
info("!!! DO NOT SHARE !!! Token - " + token); var discord = configuration.getConfigurationSection("discord");
token = discord.getString("token"); // This used to log the token into stdout ???
logChannel = discord.getString("logChannel"); logChannel = discord.getString("logChannel");
info("Logging Channel - " + logChannel);
ownerId = discord.getString("ownerId"); ownerId = discord.getString("ownerId");
info("Owner ID - " + ownerId);
mainGuild = discord.getString("mainGuild"); mainGuild = discord.getString("mainGuild");
info("Main Guild - " + mainGuild);
clientId = discord.getString("clientId"); clientId = discord.getString("clientId");
defaultInvitePermissionLevel = discord.getInt("invitePermissionLevel"); defaultInvitePermissionLevel = discord.getInt("invitePermissionLevel");
info("Invite link - " + assembleDefaultInvite()); // Log discord settings.
//Kia loaders info("Discord configuration:" +n+
ConfigurationSection main = configuration.getConfigurationSection("main"); "Log Channel: " + logChannel +n+
"Owner ID: " + ownerId +n+
"Primary Guild: " + mainGuild +n+
"Invite link: " + assembleDefaultInvite());
// Kiafumi loaders
var main = configuration.getConfigurationSection("main");
sharded = main.getBoolean("sharded"); sharded = main.getBoolean("sharded");
activityType = main.getString("activityType"); activityType = main.getString("activityType");
activityMsg = main.getString("activityMsg"); activityMsg = main.getString("activityMsg");
@ -90,19 +93,21 @@ public class KiafumiConfig {
gamePrevention = main.getBoolean("gamePrevention"); gamePrevention = main.getBoolean("gamePrevention");
gameCheckTime = main.getInt("gameCheckTime"); gameCheckTime = main.getInt("gameCheckTime");
gameToPrevent = main.getString("gameToPrevent"); gameToPrevent = main.getString("gameToPrevent");
//SQL loaders
ConfigurationSection sql = configuration.getConfigurationSection("sql"); // SQL loaders
var sql = configuration.getConfigurationSection("sql");
host = sql.getString("host"); host = sql.getString("host");
port = sql.getInt("port"); port = sql.getInt("port");
username = sql.getString("username"); username = sql.getString("username");
password = sql.getString("password"); password = sql.getString("password");
database = sql.getString("database"); database = sql.getString("database");
} catch(Exception ex) { } catch(Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
error("Failed to load configuration!"); error("Failed to load configuration!");
return false; return false;
} }
info("Configuration Loaded"); info("Configuration Loaded.");
return true; return true;
} }

View file

@ -46,30 +46,29 @@ public class CommandRegistrar {
*/ */
public List<CommandClass> getCommandClasses() { public List<CommandClass> getCommandClasses() {
try { try {
//todo have this check the classpath that we're under and have it scan *that* instead of hard-coding it to only be // TODO have this check the classpath that we're under and have it scan *that* instead of hard-coding it to only be moe.oko.Kiafumi path.
//moe.oko.Kiafumi path. var classes = findAllClassesContaining("moe.oko.Kiafumi.command");
Set<Class> classes = findAllClassesContaining("moe.oko.Kiafumi.command");
List<CommandClass> commands = new ArrayList<>(); List<CommandClass> commands = new ArrayList<>();
info("[CommandRegistrar]Found " + classes.size() + " classes containing moe.oko.Kiafumi.command in package class."); info("[CommandRegistrar] Discovered " + classes.size() + " classes containing moe.oko.Kiafumi.command in package class.");
for (Class clazz : classes) { for (Class clazz : classes) {
for (Constructor cnstr : clazz.getConstructors()) { for (Constructor cnstr : clazz.getConstructors()) {
try { try {
var obj = cnstr.newInstance(); //making an attempt. var obj = cnstr.newInstance(); // making an attempt.
if (obj instanceof CommandClass) { if (obj instanceof CommandClass) {
info("[CommandRegistrar]Instance found (" + cnstr.getName() + ")! Registering."); info("[CommandRegistrar] Registering class " + cnstr.getName());
commands.add((CommandClass) obj); commands.add((CommandClass) obj);
} }
} catch (InstantiationException ex) { } catch (InstantiationException ex) {
//Ignore, this is just us trying to load the CommandClass abstract class. We ignore it. // Ignore, this is just us trying to load the CommandClass abstract class.
} }
} }
} }
info("[CommandRegistrar]CommandClasses loaded [" + commands.size() + "]"); info("[CommandRegistrar] CommandClasses loaded [" + commands.size() + "]");
return commands; return commands;
} catch (IllegalAccessException | InvocationTargetException exception) { } catch (IllegalAccessException | InvocationTargetException exception) {
//Now we don't ignore, this is a core issue. // Now we don't ignore, this is a core issue.
exception.printStackTrace(); exception.printStackTrace();
error("[CommandRegistrar EEE_E_E_E_E_]fucky wucky in class loading."); error("[CommandRegistrar] Fatal failure in class loading.");
return null; return null;
} }
} }

View file

@ -13,13 +13,14 @@ 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;
/** /**
* Dreidel Dreidel... * Dreidel Dreidel...
* @author Tiddy * @author Tiddy
*/ */
public class DreidelCommand extends CommandClass { public class DreidelCommand extends CommandClass {
private boolean enabled = true; private final List<String> sides;
private List<String> sides;
public DreidelCommand() { public DreidelCommand() {
List<String> sides = new ArrayList<>(); List<String> sides = new ArrayList<>();
@ -30,9 +31,8 @@ public class DreidelCommand extends CommandClass {
this.sides = sides; this.sides = sides;
} }
@Override @Override
public boolean isEnabled() { return enabled; } public boolean isEnabled() { return true; }
@Override @Override
public String getName() { return "Dreidel"; } public String getName() { return "Dreidel"; }
@ -40,17 +40,18 @@ public class DreidelCommand extends CommandClass {
@Override @Override
public void newCommand(String name, SlashCommandInteractionEvent e) { public void newCommand(String name, SlashCommandInteractionEvent e) {
if ("dreidel".equals(name)) { if ("dreidel".equals(name)) {
slashLog(e);
e.deferReply().queue(); e.deferReply().queue();
EmbedBuilder eb = new EmbedBuilder() var eb = new EmbedBuilder()
.setColor(EmbedUI.INFO) .setColor(EmbedUI.INFO)
.setTitle("Spinning...") .setTitle("Spinning...")
.setDescription("*brrrrrrrrrrrrrr*") .setDescription("*brrrrrrrrrrrrrr*")
.setFooter(EmbedUI.BRAND) .setFooter(EmbedUI.BRAND)
.setTimestamp(ZonedDateTime.now()); .setTimestamp(ZonedDateTime.now());
e.getHook().sendMessageEmbeds(eb.build()).queue(); e.getHook().sendMessageEmbeds(eb.build()).queue();
Random rand = new Random(); var rand = new Random();
String result = sides.get(rand.nextInt(sides.size())); var result = sides.get(rand.nextInt(sides.size()));
EmbedBuilder eb1 = new EmbedBuilder() var eb1 = new EmbedBuilder()
.setColor(EmbedUI.INFO) .setColor(EmbedUI.INFO)
.setTitle("You rolled...") .setTitle("You rolled...")
.setDescription(result + "!") .setDescription(result + "!")
@ -63,8 +64,7 @@ public class DreidelCommand extends CommandClass {
@Override @Override
public List<CommandInfo> getSlashCommandInfo() { public List<CommandInfo> getSlashCommandInfo() {
List<CommandInfo> si = new ArrayList<>(); List<CommandInfo> si = new ArrayList<>();
CommandInfo ci = new CommandInfo("dreidel", "Spins a dreidel!", CommandType.COMMAND); si.add(new CommandInfo("dreidel", "Spins a dreidel!", CommandType.COMMAND));
si.add(ci);
return si; return si;
} }
} }

View file

@ -16,16 +16,16 @@ 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;
/** /**
* Random User Choice Command * Random User Choice Command
* Intended for when you want to roll the dice on who gets to join the LIMITED EDITION(tm) call
* @author Kay * @author Kay
*/ */
public class FightCommand extends CommandClass { public class FightCommand extends CommandClass {
private boolean enabled = false;
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return enabled; return true;
} }
@Override @Override
@ -36,6 +36,7 @@ public class FightCommand extends CommandClass {
@Override @Override
public void newCommand(String name, SlashCommandInteractionEvent e) { public void newCommand(String name, SlashCommandInteractionEvent e) {
if ("fight".equals(name)) { if ("fight".equals(name)) {
slashLog(e);
e.deferReply().queue(); e.deferReply().queue();
List<User> usersForRng = new ArrayList<>(); List<User> usersForRng = new ArrayList<>();
List<String> userNames = new ArrayList<>(); List<String> userNames = new ArrayList<>();
@ -43,17 +44,17 @@ public class FightCommand extends CommandClass {
usersForRng.add(option.getAsUser()); usersForRng.add(option.getAsUser());
userNames.add(option.getAsUser().getName()); userNames.add(option.getAsUser().getName());
} }
//Done, now roll // Done, now roll
EmbedBuilder eb = new EmbedBuilder() var eb = new EmbedBuilder()
.setColor(EmbedUI.INFO) .setColor(EmbedUI.INFO)
.setTitle("Match in progress...") .setTitle("Match in progress...")
.setDescription("*POW! KABLAM! SCHNARF!*") .setDescription("*POW! KABLAM! SCHNARF!*")
.setFooter(EmbedUI.BRAND) .setFooter(EmbedUI.BRAND)
.setTimestamp(ZonedDateTime.now()); .setTimestamp(ZonedDateTime.now());
e.getHook().sendMessageEmbeds(eb.build()).queue(); e.getHook().sendMessageEmbeds(eb.build()).queue();
Random rng = new Random(); var rng = new Random();
User pickedUser = usersForRng.get(rng.nextInt(usersForRng.size())); var pickedUser = usersForRng.get(rng.nextInt(usersForRng.size()));
EmbedBuilder eb1 = new EmbedBuilder() var eb1 = new EmbedBuilder()
.setColor(EmbedUI.INFO) .setColor(EmbedUI.INFO)
.setTitle("FATALITY!") .setTitle("FATALITY!")
.setDescription(pickedUser.getName() + " wins!") .setDescription(pickedUser.getName() + " wins!")
@ -67,7 +68,7 @@ public class FightCommand 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("fight", "MORTALLL KOMBATTTT", CommandType.COMMAND); var ci = new CommandInfo("fight", "MORTALLL KOMBATTTT", CommandType.COMMAND);
ci.addOption("value1", "first fighter", OptionType.USER, true); ci.addOption("value1", "first fighter", OptionType.USER, true);
ci.addOption("value2", "second fighter", OptionType.USER, true); ci.addOption("value2", "second fighter", OptionType.USER, true);
ci.addOption("value3", "third fighter", OptionType.USER, false); ci.addOption("value3", "third fighter", OptionType.USER, false);

View file

@ -14,6 +14,8 @@ 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;
/** /**
* Fetches the REAL date * Fetches the REAL date
* @author oko * @author oko
@ -31,6 +33,7 @@ public class SeptemberDateCommand extends CommandClass {
@Override @Override
public void newCommand(String name, SlashCommandInteractionEvent e) { public void newCommand(String name, SlashCommandInteractionEvent e) {
if ("sdate".equals(name)) { if ("sdate".equals(name)) {
slashLog(e);
e.deferReply().queue(); e.deferReply().queue();
var now = LocalDate.now(); var now = LocalDate.now();
@ -38,7 +41,7 @@ public class SeptemberDateCommand extends CommandClass {
// Create the Eternal September date // Create the Eternal September date
var sdate = ChronoUnit.DAYS.between(september, now); var sdate = ChronoUnit.DAYS.between(september, now);
EmbedBuilder eb = new EmbedBuilder() var eb = new EmbedBuilder()
.setColor(EmbedUI.INFO) .setColor(EmbedUI.INFO)
.setTitle("sdate") .setTitle("sdate")
.setDescription("Today is September, " + sdate + " 1993, the september that never ends") .setDescription("Today is September, " + sdate + " 1993, the september that never ends")
@ -51,8 +54,7 @@ public class SeptemberDateCommand 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("sdate", "Returns the Eternal September date.", CommandType.COMMAND); cil.add(new CommandInfo("sdate", "Returns the Eternal September date.", CommandType.COMMAND));
cil.add(ci);
return cil; return cil;
} }
} }

View file

@ -12,6 +12,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;
/** /**
* Helpful Avatar grabber command * Helpful Avatar grabber command
* @author oko * @author oko
@ -26,13 +28,14 @@ public class AvatarCommand extends CommandClass {
@Override @Override
public void newCommand(String name, SlashCommandInteractionEvent e) { public void newCommand(String name, SlashCommandInteractionEvent e) {
if ("avatar".equals(name)) { if ("avatar".equals(name)) {
slashLog(e);
e.deferReply().queue(); e.deferReply().queue();
final var user = e.getOptions().size() == 0 final var user = e.getOptions().size() == 0
? e.getUser() ? e.getUser()
: e.getOption("user").getAsUser(); : e.getOption("user").getAsUser();
EmbedBuilder eb = new EmbedBuilder() var eb = new EmbedBuilder()
.setColor(EmbedUI.INFO) .setColor(EmbedUI.INFO)
.setAuthor(user.getName() + "#" + user.getDiscriminator()) .setAuthor(user.getName() + "#" + user.getDiscriminator())
.setImage(user.getEffectiveAvatarUrl() + "?size=2048") .setImage(user.getEffectiveAvatarUrl() + "?size=2048")
@ -45,7 +48,7 @@ public class AvatarCommand 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("avatar", "Returns the avatar of the specified user.", CommandType.COMMAND); var ci = new CommandInfo("avatar", "Returns the avatar of the specified user.", CommandType.COMMAND);
ci.addOption("user", "User to fetch.", OptionType.USER, false); ci.addOption("user", "User to fetch.", OptionType.USER, false);
cil.add(ci); cil.add(ci);
return cil; return cil;

View file

@ -7,17 +7,15 @@ import moe.oko.Kiafumi.util.EmbedUI;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject;
import java.net.URI; 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.Kiafumi.error;
import static moe.oko.Kiafumi.util.EmbedUI.slashLog; import static moe.oko.Kiafumi.Kiafumi.slashLog;
import static moe.oko.Kiafumi.util.ResponseHandlers.STRING_RESPONSE_HANDLER; import static moe.oko.Kiafumi.util.ResponseHandlers.STRING_RESPONSE_HANDLER;
/** /**
@ -26,7 +24,7 @@ import static moe.oko.Kiafumi.util.ResponseHandlers.STRING_RESPONSE_HANDLER;
*/ */
public class CatCommand extends CommandClass { public class CatCommand extends CommandClass {
private final URI catUri = URI.create("https://api.thecatapi.com/v1/images/search"); private final URI catUrl = URI.create("https://api.thecatapi.com/v1/images/search");
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
@ -45,21 +43,21 @@ public class CatCommand extends CommandClass {
slashLog(e); slashLog(e);
e.deferReply().queue(); e.deferReply().queue();
CloseableHttpClient httpClient = HttpClients.createDefault(); var httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(catUri); var httpGet = new HttpGet(catUrl);
try { try {
String responseBody = httpClient.execute(httpGet, STRING_RESPONSE_HANDLER); var responseBody = httpClient.execute(httpGet, STRING_RESPONSE_HANDLER);
JSONArray array = new JSONArray(responseBody); var array = new JSONArray(responseBody);
JSONObject obj = array.getJSONObject(0); var obj = array.getJSONObject(0);
EmbedBuilder eb = new EmbedBuilder() var eb = new EmbedBuilder()
.setColor(EmbedUI.INFO) .setColor(EmbedUI.INFO)
.setTitle("mrow") .setTitle("meow")
.setImage(obj.getString("url")) .setImage(obj.getString("url"))
.setFooter(EmbedUI.BRAND); .setFooter(EmbedUI.BRAND);
e.getHook().sendMessageEmbeds(eb.build()).queue(); e.getHook().sendMessageEmbeds(eb.build()).queue();
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
error("It brokie..."); error("Error using CatCommand.");
} }
} }
} }

View file

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

View file

@ -28,9 +28,8 @@ import org.apache.commons.io.FileUtils;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
import java.util.List;
import static moe.oko.Kiafumi.util.EmbedUI.slashLog; import static moe.oko.Kiafumi.Kiafumi.slashLog;
/** /**
* Music Command * Music Command
@ -78,9 +77,9 @@ public class MusicCommand extends CommandClass {
if (!hasPlayer(e.getGuild()) || getPlayer(e.getGuild()).getPlayingTrack() == null) { // No song is playing if (!hasPlayer(e.getGuild()) || getPlayer(e.getGuild()).getPlayingTrack() == null) { // No song is playing
e.getHook().sendMessage("No song is playing.").queue(); e.getHook().sendMessage("No song is playing.").queue();
} else { } else {
AudioTrack track = getPlayer(e.getGuild()).getPlayingTrack(); var track = getPlayer(e.getGuild()).getPlayingTrack();
//Works //Works
EmbedBuilder eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.setColor(EmbedUI.SUCCESS); eb.setColor(EmbedUI.SUCCESS);
eb.setTitle("Track Info"); eb.setTitle("Track Info");
eb.setDescription("Currently Playing - " + track.getInfo().title); eb.setDescription("Currently Playing - " + track.getInfo().title);
@ -96,19 +95,19 @@ public class MusicCommand extends CommandClass {
if (!hasPlayer(e.getGuild()) || getTrackManager(e.getGuild()).getQueuedTracks().isEmpty()) { if (!hasPlayer(e.getGuild()) || getTrackManager(e.getGuild()).getQueuedTracks().isEmpty()) {
e.getHook().sendMessage("The queue is empty.").queue(); e.getHook().sendMessage("The queue is empty.").queue();
} else { } else {
StringBuilder sb = new StringBuilder(); var sb = new StringBuilder();
Set<AudioInfo> queue = getTrackManager(e.getGuild()).getQueuedTracks(); Set<AudioInfo> queue = getTrackManager(e.getGuild()).getQueuedTracks();
queue.forEach(audioInfo -> sb.append(buildQueueMessage(audioInfo))); queue.forEach(audioInfo -> sb.append(buildQueueMessage(audioInfo)));
String embedTitle = String.format(QUEUE_INFO, queue.size()); var embedTitle = String.format(QUEUE_INFO, queue.size());
if (sb.length() <= 1960) { if (sb.length() <= 1960) {
EmbedBuilder eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.setColor(EmbedUI.SUCCESS); eb.setColor(EmbedUI.SUCCESS);
eb.setTitle(embedTitle); eb.setTitle(embedTitle);
eb.addField("In Queue", "**>** " + sb.toString(), false); eb.addField("In Queue", "**>** " + sb.toString(), false);
e.getHook().sendMessageEmbeds(eb.build()).queue(); e.getHook().sendMessageEmbeds(eb.build()).queue();
} else { } else {
File qFile = new File("queue.txt"); var qFile = new File("queue.txt");
try { try {
FileUtils.write(qFile, sb.toString(), "UTF-8", false); FileUtils.write(qFile, sb.toString(), "UTF-8", false);
e.getHook().sendMessage("**Queue was too large to put into text, linked file below contains all songs queued.").queue(); e.getHook().sendMessage("**Queue was too large to put into text, linked file below contains all songs queued.").queue();
@ -190,7 +189,7 @@ public class MusicCommand extends CommandClass {
break; break;
case "play": case "play":
e.deferReply().queue(); e.deferReply().queue();
String input = e.getOption("url").getAsString(); var input = e.getOption("url").getAsString();
slashLog(e, "INPUT " + input); slashLog(e, "INPUT " + input);
if(input.contains("https://")) { if(input.contains("https://")) {
loadTrack(input, e.getMember(), e.getHook()); loadTrack(input, e.getMember(), e.getHook());
@ -240,8 +239,8 @@ public class MusicCommand extends CommandClass {
} }
private AudioPlayer createPlayer(Guild guild) { private AudioPlayer createPlayer(Guild guild) {
AudioPlayer nPlayer = myManager.createPlayer(); var nPlayer = myManager.createPlayer();
TrackManager manager = new TrackManager(nPlayer); var manager = new TrackManager(nPlayer);
nPlayer.addListener(manager); nPlayer.addListener(manager);
guild.getAudioManager().setSendingHandler(new AudioPlayerSendHandler(nPlayer)); guild.getAudioManager().setSendingHandler(new AudioPlayerSendHandler(nPlayer));
players.put(guild.getId(), new AbstractMap.SimpleEntry<>(nPlayer, manager)); players.put(guild.getId(), new AbstractMap.SimpleEntry<>(nPlayer, manager));
@ -268,7 +267,7 @@ public class MusicCommand extends CommandClass {
@Override @Override
public void trackLoaded(AudioTrack track) { public void trackLoaded(AudioTrack track) {
EmbedBuilder eb = new EmbedBuilder(); var eb = new EmbedBuilder();
eb.setColor(EmbedUI.SUCCESS); eb.setColor(EmbedUI.SUCCESS);
eb.setTitle(author.getEffectiveName() + " has loaded " + track.getInfo().title); eb.setTitle(author.getEffectiveName() + " has loaded " + track.getInfo().title);
eb.addField("Track Info", "Creator: " + track.getInfo().author + "\nLength: " + getTimestamp(track.getInfo().length), false); eb.addField("Track Info", "Creator: " + track.getInfo().author + "\nLength: " + getTimestamp(track.getInfo().length), false);
@ -328,8 +327,8 @@ public class MusicCommand extends CommandClass {
} }
private String buildQueueMessage(AudioInfo info) { private String buildQueueMessage(AudioInfo info) {
AudioTrackInfo trackInfo = info.getTrack().getInfo(); var trackInfo = info.getTrack().getInfo();
String title = trackInfo.title; var title = trackInfo.title;
long length = trackInfo.length; long length = trackInfo.length;
return "`[ " + getTimestamp(length) + " ]` " + title + "\n"; return "`[ " + getTimestamp(length) + " ]` " + title + "\n";
} }

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.util.EmbedUI.slashLog; import static moe.oko.Kiafumi.Kiafumi.slashLog;
/** /**
* Helpful Search Command (Uses DDG API) * Helpful Search Command (Uses DDG API)

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.util.EmbedUI.slashLog; import static moe.oko.Kiafumi.Kiafumi.slashLog;
public class HelpCommand extends CommandClass { public class HelpCommand extends CommandClass {
@Override @Override

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.util.EmbedUI.slashLog; import static moe.oko.Kiafumi.Kiafumi.slashLog;
/** /**
* Helpful User Information Command * Helpful User Information Command

View file

@ -4,15 +4,15 @@ import moe.oko.Kiafumi.Kiafumi;
import moe.oko.Kiafumi.command.CommandClass; import moe.oko.Kiafumi.command.CommandClass;
import moe.oko.Kiafumi.util.CommandInfo; import moe.oko.Kiafumi.util.CommandInfo;
import moe.oko.Kiafumi.util.CommandType; import moe.oko.Kiafumi.util.CommandType;
import moe.oko.Kiafumi.util.EmbedUI;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import moe.oko.Kiafumi.util.EmbedUI;
import java.time.ZonedDateTime; 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.util.EmbedUI.slashLog; import static moe.oko.Kiafumi.Kiafumi.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.util.EmbedUI.slashLog; import static moe.oko.Kiafumi.Kiafumi.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.util.EmbedUI.slashLog; import static moe.oko.Kiafumi.Kiafumi.slashLog;
import static moe.oko.Kiafumi.util.EmbedUI.slashResponse; import static moe.oko.Kiafumi.Kiafumi.slashResponse;
/** /**
* Permits modification of server settings, critical class to functionality. * Permits modification of server settings, critical class to functionality.

View file

@ -1,23 +1,19 @@
package moe.oko.Kiafumi.listener; package moe.oko.Kiafumi.listener;
import moe.oko.Kiafumi.Kiafumi; import moe.oko.Kiafumi.Kiafumi;
import moe.oko.Kiafumi.model.Server;
import moe.oko.Kiafumi.util.EmbedUI; import moe.oko.Kiafumi.util.EmbedUI;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
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.entities.TextChannel;
import net.dv8tion.jda.api.events.ReadyEvent; import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.events.guild.GuildJoinEvent; import net.dv8tion.jda.api.events.guild.GuildJoinEvent;
import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent; import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent;
import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent; import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.events.user.update.GenericUserPresenceEvent; import net.dv8tion.jda.api.events.user.update.GenericUserPresenceEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
@ -39,7 +35,7 @@ public class MainListener extends ListenerAdapter {
*/ */
@Override @Override
public void onGuildJoin(@NotNull GuildJoinEvent event) { public void onGuildJoin(@NotNull GuildJoinEvent event) {
//Automatically create our default information for the server if we don't have it already. // Automatically create our default information for the server if we don't have it already.
info("Joined a new guild, NAME: " + event.getGuild().getName() + " ID: " + event.getGuild().getId()); info("Joined a new guild, NAME: " + event.getGuild().getName() + " ID: " + event.getGuild().getId());
Kiafumi.instance.getServerManager().createNewDefaultServer(event.getGuild()); Kiafumi.instance.getServerManager().createNewDefaultServer(event.getGuild());
Kiafumi.instance.registerForGuild(event.getGuild()); Kiafumi.instance.registerForGuild(event.getGuild());
@ -50,24 +46,16 @@ public class MainListener extends ListenerAdapter {
*/ */
@Override @Override
public void onReady(@NotNull ReadyEvent event) { public void onReady(@NotNull ReadyEvent event) {
info("Received READY signal from Discord, bot is now logged in." + info("Received READY signal from Discord, bot is now logged in." + System.lineSeparator() +
" Guilds Active: " + event.getGuildAvailableCount() + " Guilds Unavailable: " + event.getGuildUnavailableCount()); " Guilds Active: " + event.getGuildAvailableCount() + " Guilds Unavailable: " + event.getGuildUnavailableCount());
} }
/**
* Slash Command Logging
*/
@Override
public void onSlashCommandInteraction(SlashCommandInteractionEvent event) {
//soontm
}
/** /**
* Quick Response for if someone pings me. * Quick Response for if someone pings me.
*/ */
public void onMessageReceived(MessageReceivedEvent event) { public void onMessageReceived(MessageReceivedEvent event) {
if(event.getMessage().getMentionedUsers().contains(Kiafumi.JDA.getSelfUser())) { if(event.getMessage().getMentionedUsers().contains(Kiafumi.JDA.getSelfUser())) {
EmbedBuilder eb = new EmbedBuilder() var eb = new EmbedBuilder()
.setColor(EmbedUI.INFO) .setColor(EmbedUI.INFO)
.setTitle("Hi, i'm Kiafumi!") .setTitle("Hi, i'm Kiafumi!")
.setDescription("I was summoned on October 6th 2017! My goal is to explore the metaverse and help people in it!") .setDescription("I was summoned on October 6th 2017! My goal is to explore the metaverse and help people in it!")
@ -82,15 +70,16 @@ public class MainListener extends ListenerAdapter {
* Game Prevention, is a global mechanic :^) * Game Prevention, is a global mechanic :^)
* @param event - GenericUserPresenceEvent event to be used. * @param event - GenericUserPresenceEvent event to be used.
*/ */
@Deprecated
@Override @Override
public void onGenericUserPresence(@NotNull GenericUserPresenceEvent event) { public void onGenericUserPresence(@NotNull GenericUserPresenceEvent event) {
if(Kiafumi.instance.config.isGamePreventionEnabled()) { if(Kiafumi.instance.config.isGamePreventionEnabled()) {
//Proceed. // Proceed.
if(event.getMember().getActivities().contains(Activity.playing(Kiafumi.instance.config.getGameToPrevent()))) { if(event.getMember().getActivities().contains(Activity.playing(Kiafumi.instance.config.getGameToPrevent()))) {
//THEY ARE PLAYING THE BIG BAD GAME!!!! WARN THE MIMMEDIATELYOYUITHTHHT // THEY ARE PLAYING THE BIG BAD GAME!!!! WARN THE MIMMEDIATELYOYUITHTHHT
event.getMember().getUser().openPrivateChannel().complete().sendMessage("**YOU ARE PLAYING THE BIG BAD GAME STOP STOP STOP** " + event.getMember().getUser().openPrivateChannel().complete().sendMessage("**YOU ARE PLAYING THE BIG BAD GAME STOP STOP STOP** " +
"(in " + Kiafumi.instance.config.getGameCheckTime() + " minutes i wll EVAPORATE you from every server i am IN.").queue(); "(in " + Kiafumi.instance.config.getGameCheckTime() + " minutes i wll EVAPORATE you from every server i am IN.").queue();
Timer timer = new Timer(); var timer = new Timer();
int timeInMilisToKill = (Kiafumi.instance.config.getGameCheckTime() * 60) * 1000; int timeInMilisToKill = (Kiafumi.instance.config.getGameCheckTime() * 60) * 1000;
timer.schedule(new TimerTask() { timer.schedule(new TimerTask() {
@Override @Override
@ -113,7 +102,7 @@ public class MainListener extends ListenerAdapter {
@Override @Override
public void onGuildMemberJoin(@NotNull GuildMemberJoinEvent event) { public void onGuildMemberJoin(@NotNull GuildMemberJoinEvent event) {
Server server = Kiafumi.instance.getServerManager().getOrCreateServer(event.getGuild()); var server = Kiafumi.instance.getServerManager().getOrCreateServer(event.getGuild());
if(server.getJoinRole() != null) { if(server.getJoinRole() != null) {
try { try {
event.getGuild().addRoleToMember(event.getMember(), event.getGuild().getRoleById(server.getJoinRole())).queue(); event.getGuild().addRoleToMember(event.getMember(), event.getGuild().getRoleById(server.getJoinRole())).queue();
@ -122,38 +111,38 @@ public class MainListener extends ListenerAdapter {
} }
} }
if(server.isWelcomeEnabled()) { if(server.isWelcomeEnabled()) {
TextChannel textChannel = event.getGuild().getTextChannelById(server.getWelcomeChannel()); var textChannel = event.getGuild().getTextChannelById(server.getWelcomeChannel());
if(textChannel == null) { if(textChannel == null) {
event.getGuild().getTextChannels().get(0).sendMessage("**Failed to send welcome message, as the welcome channel does not exist.**").queue(); event.getGuild().getTextChannels().get(0).sendMessage("**Failed to send welcome message, as the welcome channel does not exist.**").queue();
return; return;
} }
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("MM-dd-yyyy"); var dTF = DateTimeFormatter.ofPattern("MM-dd-yyyy");
//Ok, now we proceed. // Prepare embed.
EmbedBuilder embedBuilder = new EmbedBuilder() var embedBuilder = new EmbedBuilder()
.setColor(EmbedUI.SUCCESS) .setColor(EmbedUI.SUCCESS)
.setAuthor(event.getMember().getEffectiveName() + "#" + event.getMember().getUser().getDiscriminator() + " (" .setAuthor(event.getMember().getEffectiveName() + "#" + event.getMember().getUser().getDiscriminator() + " ("
+ event.getMember().getId() + ")", null, event.getUser().getAvatarUrl()).setFooter("User Joined").setTimestamp(OffsetDateTime.now()) + event.getMember().getId() + ")", null, event.getUser().getAvatarUrl()).setFooter("User Joined").setTimestamp(OffsetDateTime.now())
.setDescription(event.getMember().getAsMention() + " | **Joined Discord**: " + event.getMember().getTimeCreated().format(dTF)).setColor(Color.GREEN); .setDescription(event.getMember().getAsMention() + " | **Joined Discord**: " + event.getMember().getTimeCreated().format(dTF));
textChannel.sendMessageEmbeds(embedBuilder.build()).queue(); textChannel.sendMessageEmbeds(embedBuilder.build()).queue();
} }
} }
@Override @Override
public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) { public void onGuildMemberRemove(@NotNull GuildMemberRemoveEvent event) {
Server server = Kiafumi.instance.getServerManager().getOrCreateServer(event.getGuild()); var server = Kiafumi.instance.getServerManager().getOrCreateServer(event.getGuild());
if(server.isWelcomeEnabled()) { if(server.isWelcomeEnabled()) {
TextChannel textChannel = event.getGuild().getTextChannelById(server.getWelcomeChannel()); var textChannel = event.getGuild().getTextChannelById(server.getWelcomeChannel());
if(textChannel == null) { if(textChannel == null) {
event.getGuild().getTextChannels().get(0).sendMessage("**Failed to send leave message, as the welcome channel does not exist.**").queue(); event.getGuild().getTextChannels().get(0).sendMessage("**Failed to send leave message, as the welcome channel does not exist.**").queue();
return; return;
} }
//Ok, now we proceed. // Prepare embed.
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("MM-dd-yyyy"); var dTF = DateTimeFormatter.ofPattern("MM-dd-yyyy");
EmbedBuilder embedBuilder = new EmbedBuilder() var embedBuilder = new EmbedBuilder()
.setColor(EmbedUI.FAILURE) .setColor(EmbedUI.FAILURE)
.setAuthor(event.getMember().getEffectiveName() + "#" + event.getMember().getUser().getDiscriminator() + " (" .setAuthor(event.getMember().getEffectiveName() + "#" + event.getMember().getUser().getDiscriminator() + " ("
+ event.getMember().getId() + ")", null, event.getUser().getAvatarUrl()).setFooter("User Left").setTimestamp(OffsetDateTime.now()) + event.getMember().getId() + ")", null, event.getUser().getAvatarUrl()).setFooter("User Left").setTimestamp(OffsetDateTime.now())
.setDescription(event.getMember().getAsMention() + " | **Joined Server**: " + event.getMember().getTimeJoined().format(dTF)).setColor(Color.RED); .setDescription(event.getMember().getAsMention() + " | **Joined Server**: " + event.getMember().getTimeJoined().format(dTF));
textChannel.sendMessageEmbeds(embedBuilder.build()).queue(); textChannel.sendMessageEmbeds(embedBuilder.build()).queue();
} }
} }

View file

@ -63,7 +63,7 @@ public class ServerManager {
* @return - whether the function succeeded. * @return - whether the function succeeded.
*/ */
public boolean createNewDefaultServer(Guild guild) { public boolean createNewDefaultServer(Guild guild) {
info("Started default server creation for " + guild.getId()); info("Started default server creation for server " + guild.getId());
Server server = new Server(guild.getId()); Server server = new Server(guild.getId());
if(Kiafumi.instance.getDatabase().createServerInformation(guild)) { if(Kiafumi.instance.getDatabase().createServerInformation(guild)) {
info("New defaults persistent for " + server); info("New defaults persistent for " + server);

View file

@ -2,7 +2,7 @@ package moe.oko.Kiafumi.util;
/** /**
* Used to identify what type of Command is being used. * Used to identify what type of Command is being used.
* This is intended to prevent JDA errors. Which is does. * This is intended to prevent JDA errors.
*/ */
public enum CommandType { public enum CommandType {

View file

@ -1,12 +1,7 @@
package moe.oko.Kiafumi.util; package moe.oko.Kiafumi.util;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import javax.annotation.Nullable;
import java.awt.Color; import java.awt.Color;
import static moe.oko.Kiafumi.Kiafumi.info;
/** /**
* EmbedUI Class * EmbedUI Class
* @author oko * @author oko
@ -14,7 +9,7 @@ import static moe.oko.Kiafumi.Kiafumi.info;
public abstract class EmbedUI { public abstract class EmbedUI {
/** /**
* Shorthand reference for common EmbedBuilder colors & strings. * Shorthand reference for common EmbedBuilder colors & strings.
* I (oko) chose these colors based on the Pantone Color of the year. * I chose these colors based on the Pantone Color of the year.
*/ */
// Strings // Strings
@ -24,21 +19,4 @@ public abstract class EmbedUI {
public static final Color SUCCESS = new Color(136,176,75); public static final Color SUCCESS = new Color(136,176,75);
public static final Color FAILURE = new Color(255,111,97); public static final Color FAILURE = new Color(255,111,97);
public static final Color INFO = new Color(123,196,196); public static final Color INFO = new Color(123,196,196);
/**
* 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 " + event.getName() + "." + (msg == null ? "" : msg));
}
public static void slashLog(SlashCommandInteractionEvent event) {
info("User[" + event.getUser().getName() + ":" + event.getUser().getId() + "] RAN " + event.getName() + ".");
}
public static void slashResponse(SlashCommandInteractionEvent event, String msg) {
info("User[" + event.getUser().getName() + ":" + event.getUser().getId() + "] CMD RESPONSE: " + msg);
}
} }