Added shutdown method (must create command), Added MySQL table creation statements

This commit is contained in:
Savvy 2017-09-26 17:10:17 -04:00
parent 7bdb704523
commit e9514daf6f
10 changed files with 463 additions and 9 deletions

View File

@ -19,6 +19,7 @@ import me.savvy.rixa.commands.mod.DeleteMessagesCommand;
import me.savvy.rixa.commands.mod.MuteCommand;
import me.savvy.rixa.commands.mod.PurgeMessagesCommand;
import me.savvy.rixa.commands.mod.RaidModeCommand;
import me.savvy.rixa.data.database.sql.other.DatabaseTables;
import me.savvy.rixa.data.filemanager.ConfigManager;
import me.savvy.rixa.data.filemanager.LanguageManager;
import me.savvy.rixa.events.BotEvent;
@ -40,6 +41,7 @@ import net.dv8tion.jda.core.hooks.AnnotatedEventManager;
import javax.security.auth.login.LoginException;
import java.io.File;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executors;
@ -86,14 +88,11 @@ public class Rixa {
getInstance().setExecutorService(Executors.newSingleThreadScheduledExecutor());
database = Database.options()
.type("mysql")
.hostname(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("hostName")), Integer.valueOf(config.getJsonObject().getJSONObject("sql").getInt("portNumber")))
.hostname(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("hostName")), config.getJsonObject().getJSONObject("sql").getInt("portNumber"))
.database(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("databaseName")))
.auth(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("userName")), String.valueOf(config.getJsonObject().getJSONObject("sql").getString("password")))
.build();
Update update = new Update("CREATE TABLE IF NOT EXISTS `core` (`guild_id` varchar(255) NOT NULL, `guild_name` varchar(255) NOT NULL, PRIMARY KEY (`guild_id`));");
database.send(update);
Update modules = new Update("CREATE TABLE IF NOT EXISTS `modules` (`guild_id` varchar(255) NOT NULL, `levels` varchar(255) NOT NULL, `enabled` INT(11) NOT NULL, PRIMARY KEY (`guild_id`));");
database.send(modules);
Arrays.stream(DatabaseTables.values()).forEach(databaseTables -> database.send(new Update(databaseTables.getQuery())));
getInstance().setLanguageManager(new LanguageManager(new File("Rixa/languages/language.json")));
try {
int shards = 5;
@ -155,4 +154,14 @@ public class Rixa {
return Logger.getLogger("Rixa");
}
public void exit() {
try {
database.close();
getShardsList().forEach(JDA::shutdown);
Thread.sleep(5000);
System.exit(0);
} catch (InterruptedException ex) {
getLogger().severe("Could not shutdown Rixa instance.");
}
}
}

View File

@ -0,0 +1,79 @@
package me.savvy.rixa.commands.admin;
import me.savvy.rixa.commands.handlers.Command;
import me.savvy.rixa.commands.handlers.CommandExec;
import me.savvy.rixa.commands.handlers.CommandType;
import me.savvy.rixa.guild.RixaGuild;
import me.savvy.rixa.utils.MessageBuilder;
import net.dv8tion.jda.core.entities.ChannelType;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import java.util.HashMap;
import java.util.Map;
public class RoleRewardsCommand implements CommandExec {
@Command(
description = "View Role Rewards.",
type = CommandType.ADMIN,
channelType = ChannelType.TEXT,
usage = "%prolerewards", mainCommand = "rolerewards",
aliases = {"rolereward", "rw"})
public void execute(GuildMessageReceivedEvent event) {
RixaGuild rixaGuild = RixaGuild.getGuild(event.getGuild());
String[] args = event.getMessage().getContent().split(" ");
// ?rw <add/remove/list> [level] [role]
switch (args.length) {
case 4:
if (!isInt(args[2])) {
new MessageBuilder(event.getMember().getAsMention() + ", incorrect usage try [" + args[0] + " <add/remove/list> [level] [role].").
setColor(event.getMember().getColor()).queue(event.getChannel());
return;
}
if (rixaGuild.getLevelsModule().getRoleRewards().containsKey(Integer.parseInt(args[2]))) {
new MessageBuilder(event.getMember().getAsMention() + ", incorrect usage try [" + args[0] + " <add/remove/list> [level] [role].").
setColor(event.getMember().getColor()).queue(event.getChannel());
return;
}
switch (args[1].toLowerCase()) {
case "add":
break;
case "remove":
break;
default:
new MessageBuilder(event.getMember().getAsMention() + ", incorrect usage try [" + args[0] + " <add/remove/list> [level] [role].").
setColor(event.getMember().getColor()).queue(event.getChannel());
break;
}
break;
case 2:
switch(args[1].toLowerCase()) {
case "list":
Map<Integer, String> rewards = new HashMap<>();
rixaGuild.getLevelsModule().getRoleRewards().forEach((integer, s) -> {
});
break;
default:
new MessageBuilder(event.getMember().getAsMention() + ", incorrect usage try [" + args[0] + " <add/remove/list> [level] [role].").
setColor(event.getMember().getColor()).queue(event.getChannel());
break;
}
break;
default:
new MessageBuilder(event.getMember().getAsMention() + ", incorrect usage try [" + args[0] + " <add/remove/list> [level] [role].").
setColor(event.getMember().getColor()).queue(event.getChannel());
break;
}
}
private boolean isInt(String s) {
try {
Integer.parseInt(s);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
}

View File

@ -0,0 +1,61 @@
package me.savvy.rixa.commands.owner;
import me.savvy.rixa.Rixa;
import me.savvy.rixa.commands.handlers.Command;
import me.savvy.rixa.commands.handlers.CommandExec;
import me.savvy.rixa.commands.handlers.CommandType;
import me.savvy.rixa.enums.Result;
import me.savvy.rixa.utils.MessageBuilder;
import net.dv8tion.jda.core.entities.ChannelType;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class CheckGuildCommand implements CommandExec {
@Override
@Command(mainCommand = "checkguild",
description = "Update Rixa's database!",
channelType = ChannelType.TEXT,
showInHelp = false,
type = CommandType.BOT_OWNER,
aliases = { "cg", "checkg", "guildcheck", "gc"})
public void execute(GuildMessageReceivedEvent event) {
if (!event.getAuthor().getId().equalsIgnoreCase("202944101333729280")) {
new MessageBuilder(event.getMember().getAsMention() + ", you do not have permission for this command.")
.setColor(event.getMember().getColor()).queue(event.getChannel());
return;
}
new MessageBuilder(event.getAuthor().getAsMention() + ", updating guild!").setColor(event.getMember().getColor()).queue(event.getChannel());
int updated = 0;
for (Member member: event.getGuild().getMembers()) {
if (member.getUser().getId().equalsIgnoreCase(event.getAuthor().getId())) continue;
try {
if (!(checkExists(member.getUser().getId()))) {
PreparedStatement ps = Rixa.getDbManager().getConnection().prepareStatement("INSERT INTO `user` (`user_id`, `user_name`, `avatar_hash`) VALUES (?, ?, ?)");
ps.setString(1, member.getUser().getId());
ps.setString(2, member.getUser().getName());
ps.setString(3, member.getUser().getAvatarId());
Rixa.getDbManager().executeUpdate(ps);
updated++;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
new MessageBuilder(event.getAuthor().getAsMention() + ", successfully updated " + updated + " out of " +
event.getGuild().getMembers().size() + " users in database.").setColor(event.getMember().getColor()).queue(event.getChannel());
}
private boolean checkExists(String userId) {
Result r = Result.ERROR;
try {
r = Rixa.getDbManager().checkExists("SELECT `user_id` FROM `user` WHERE `user_id` = '" + userId + "';");
} catch (SQLException e) {
e.printStackTrace();
}
return r == Result.TRUE;
}
}

View File

@ -0,0 +1,79 @@
package me.savvy.rixa.commands.owner;
import me.savvy.rixa.Rixa;
import me.savvy.rixa.commands.handlers.Command;
import me.savvy.rixa.commands.handlers.CommandExec;
import me.savvy.rixa.commands.handlers.CommandType;
import me.savvy.rixa.data.database.sql.DatabaseManager;
import me.savvy.rixa.enums.Result;
import me.savvy.rixa.utils.MessageBuilder;
import net.dv8tion.jda.core.entities.ChannelType;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CleanGuildCommand implements CommandExec {
@Override
@Command(mainCommand = "cleanguilds",
description = "Clean Inactive Guilds From Rixa's Database!",
channelType = ChannelType.TEXT,
showInHelp = false,
type = CommandType.BOT_OWNER)
public void execute(GuildMessageReceivedEvent event) {
if (!event.getAuthor().getId().equalsIgnoreCase("202944101333729280")) {
new MessageBuilder(event.getMember().getAsMention() + ", you do not have permission for this command.")
.setColor(event.getMember().getColor()).queue(event.getChannel());
return;
}
new MessageBuilder("Cleaning...").setColor(event.getMember().getColor()).queue(event.getChannel());
int cleaned = 0;
DatabaseManager dbManager = Rixa.getDbManager();
ResultSet rs = dbManager.executeQuery("SELECT * FROM `core`;");
try {
while (rs.next()) {
if (event.getJDA().getGuildById(rs.getString("guild_id")) == null) {
cleaned++;
String id = rs.getString("guild_id");
//`core`, `levels`, `settings`, `music`, `modules`, `permissions`
if (checkExists("core", id))
dbManager.executeUpdate("DELETE FROM `core` WHERE `guild_id` = " + id);
if (checkExists("levels", id))
dbManager.executeUpdate("DELETE FROM `levels` WHERE `guild_id` = " + id);
if (checkExists("settings", id))
dbManager.executeUpdate("DELETE FROM `settings` WHERE `guild_id` = " + id);
if (checkExists("music", id))
dbManager.executeUpdate("DELETE FROM `music` WHERE `guild_id` = " + id);
if (checkExists("modules", id))
dbManager.executeUpdate("DELETE FROM `modules` WHERE `guild_id` = " + id);
if (checkExists("permissions", id))
dbManager.executeUpdate("DELETE FROM `permissions` WHERE `guild_id` = " + id);
}
}
rs.getStatement().close();
rs.close();
new MessageBuilder(event.getAuthor().getAsMention() + ", successfully cleaned " + cleaned + " guilds from the database").setColor(event.getMember().getColor()).queue(event.getChannel());
} catch (SQLException e) {
e.printStackTrace();
}
}
private boolean checkExists(String table, String guildId) {
/*Result r = Result.ERROR;
try {
r = Rixa.getDbManager().checkExists("SELECT `" + guildId + "` FROM `" + table + "` WHERE `guild_id` = '" + guildId + "';");
} catch (SQLException e) {
e.printStackTrace();
}
return r == Result.TRUE;*/
return true;
}
}

View File

@ -0,0 +1,6 @@
package me.savvy.rixa.data.database;
public interface Data {
}

View File

@ -0,0 +1,98 @@
package me.savvy.rixa.data.database.sql;
import me.savvy.rixa.Rixa;
import java.sql.*;
public class SQLBuilder {
private String userName, password, port, databaseName, hostName;
private Connection connection;
public SQLBuilder(String userName, String password, String port, String databaseName, String hostName) {
this.userName = userName;
this.password = password;
this.port = port;
this.databaseName = databaseName;
this.hostName = hostName;
}
public PreparedStatement getPreparedStatement(String query) throws SQLException {
return getConnection().prepareStatement(query);
}
public SQLBuilder executeUpdate(PreparedStatement preparedStatement) throws SQLException {
preparedStatement.executeUpdate();
return this;
}
public SQLBuilder executeUpdate(String query) throws SQLException {
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.executeUpdate();
stmt.close();
return this;
}
public ResultSet executeQuery(PreparedStatement preparedStatement) throws SQLException {
return preparedStatement.executeQuery();
}
public Object getObject(PreparedStatement preparedStatement, String objectToGet) throws SQLException {
Object result = null;
ResultSet results = preparedStatement.executeQuery();
if (results.next()) {
result = results.getObject(objectToGet);
}
results.close();
return result;
}
public String getString(PreparedStatement preparedStatement, String stringToGet) throws SQLException {
return String.valueOf(getObject(preparedStatement, stringToGet));
}
public Integer getInteger(PreparedStatement preparedStatement, String intToGet) throws SQLException {
return (int) getObject(preparedStatement, intToGet);
}
public boolean getBoolean(PreparedStatement preparedStatement, String booleanToGet) throws SQLException {
return (boolean) getObject(preparedStatement, booleanToGet);
}
public Connection getConnection() {
if (connection == null) {
connect();
}
return connection;
}
private SQLBuilder connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
Rixa.getInstance().getLogger().severe("Could not find JDBC Driver");
e.printStackTrace();
return this;
}
try {
connection = DriverManager.getConnection
(String.format("jdbc:mysql://%s:%s/%s", this.hostName, this.port, this.databaseName),
this.userName, this.password);
} catch (SQLException ex) {
ex.printStackTrace();
}
return this;
}
public void closeConnection() {
try {
if ((getConnection() != null) && (!getConnection().isClosed())) {
getConnection().close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,57 @@
package me.savvy.rixa.data.database.sql.other;
public enum DatabaseTables {
CORE("CREATE TABLE `core` ( `id` int(11) NOT NULL AUTO_INCREMENT, `guild_id` varchar(255) NOT NULL, `guild_name` varchar(255) NOT NULL," +
" `description` text, `enlisted` tinyint(1) NOT NULL DEFAULT '0', `icon` varchar(255) DEFAULT NULL, `link` varchar(255) DEFAULT NULL," +
" `keywords` text, `creation_date` varchar(255) NOT NULL DEFAULT 'N/A', `guild_region` varchar(255) NOT NULL DEFAULT 'N/A'," +
" `guild_owner` varchar(255) NOT NULL DEFAULT 'N/A'\n" +
"), PRIMARY KEY(`id`);"),
LEVELS("CREATE TABLE `levels` ( `id` int(11) NOT NULL AUTO_INCREMENT, `guild_id` varchar(255) NOT NULL, `user_id` varchar(255) NOT NULL," +
" `experience` int(90) NOT NULL\n" +
"), PRIMARY KEY(`id`);"),
MODULES("CREATE TABLE `modules` ( `guild_id` varchar(255) DEFAULT NULL, `levels` tinyint(1) NOT NULL DEFAULT '1'\n" +
")"),
MUSIC("CREATE TABLE `music` ( `guild_id` varchar(255) NOT NULL, `music_role` varchar(255) NOT NULL DEFAULT 'default_value'," +
" `skip_amount` int(5) NOT NULL DEFAULT '0', `max_playlist_amount` int(5) NOT NULL DEFAULT '100', `enabled` tinyint(1) NOT NULL DEFAULT '0'\n" +
"), PRIMARY KEY(`id`), UNIQUE KEY (`guild_id`);"),
PERMISSIONS("CREATE TABLE `permissions` ( `role_id` varchar(255) NOT NULL, `guild_id` varchar(255) NOT NULL, `MUTE` tinyint(1) NOT NULL DEFAULT '0'," +
" `ADD_ROLE` tinyint(1) NOT NULL DEFAULT '0', `REMOVE_ROLE` tinyint(1) NOT NULL DEFAULT '0', `CLEAR_CHAT` tinyint(1) NOT NULL DEFAULT '0'," +
" `ACCESS_CONFIG` tinyint(1) NOT NULL DEFAULT '0', `PM_MESSAGE` tinyint(1) NOT NULL DEFAULT '0', `KICK_MEMBER` tinyint(1) NOT NULL DEFAULT '0'," +
" `BAN_MEMBER` tinyint(1) NOT NULL DEFAULT '0', `TOGGLE_RAIDMODE` tinyint(4) NOT NULL DEFAULT '0'\n" +
")"),
POLLS("CREATE TABLE `polls` ( `id` int(9) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `description` text," +
" `option_1` varchar(255) DEFAULT NULL, `option_2` varchar(255) DEFAULT NULL, `option_3` varchar(255) DEFAULT NULL," +
" `option_4` varchar(255) DEFAULT NULL, `option_5` varchar(255) DEFAULT NULL, `option_6` varchar(255) DEFAULT NULL," +
" `option_7` varchar(255) DEFAULT NULL, `option_8` varchar(255) DEFAULT NULL, `option_9` varchar(255) DEFAULT NULL," +
" `option_10` varchar(255) DEFAULT NULL\n" +
"), PRIMARY KEY(`id`);"),
ROLE_REWARDS("CREATE TABLE `role_rewards` ( `guild_id` varchar(255) NOT NULL, `level` int(9) NOT NULL, `role_id` varchar(255) NOT NULL\n" +
"), PRIMARY KEY(`guild_id`);"),
SETTINGS("CREATE TABLE `settings` ( `guild_id` varchar(255) NOT NULL, `log_enabled` tinyint(1) NOT NULL, `log_channel` varchar(255) NOT NULL," +
" `joinMessage` text NOT NULL, `quitMessage` text NOT NULL, `greetings` varchar(255) NOT NULL, `farewell` varchar(255) NOT NULL," +
" `prefix` varchar(5) NOT NULL, `joinPm` text NOT NULL, `joinVerification` tinyint(1) NOT NULL, `defaultRole` varchar(255) NOT NULL, `muteRole` varchar(255) NOT NULL\n" +
")"),
TWITTER("CREATE TABLE `twitter` (`guild_id` varchar(255) NOT NULL, `consumer_key` varchar(255) NOT NULL, `consumer_secret` varchar(255) NOT NULL, " +
"`access_key` varchar(255) NOT NULL, `access_secret` varchar(255) NOT NULL, `tweet_channel` varchar(255) NOT NULL, `updates_channel` varchar(255) NOT NULL)"),
USER("CREATE TABLE `user` (`user_id` varchar(255) NOT NULL, `user_name` varchar(255) NOT NULL, `avatar_hash` varchar(255) DEFAULT 'N/A'), UNIQUE KEY(`id`);"); // USER is mostly used for http://rixa.io.
private String query;
DatabaseTables(String s) {
query = s;
}
public String getQuery() {
return query;
}
}

View File

@ -0,0 +1,62 @@
package me.savvy.rixa.events;
import me.savvy.rixa.Rixa;
import net.dv8tion.jda.core.events.guild.update.GuildUpdateIconEvent;
import net.dv8tion.jda.core.events.guild.update.GuildUpdateNameEvent;
import net.dv8tion.jda.core.events.guild.update.GuildUpdateOwnerEvent;
import net.dv8tion.jda.core.events.guild.update.GuildUpdateRegionEvent;
import net.dv8tion.jda.core.hooks.SubscribeEvent;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class GuildEvent {
@SubscribeEvent
public void onNameUpdate(GuildUpdateNameEvent event) {
try {
PreparedStatement ps = Rixa.getDbManager().getConnection().prepareStatement("UPDATE `core` SET `guild_name` = ? WHERE `core`.`guild_id` = ?;");
ps.setString(1, event.getGuild().getName());
ps.setString(2, event.getGuild().getId());
Rixa.getDbManager().executeUpdate(ps);
} catch (SQLException e) {
e.printStackTrace();
}
}
@SubscribeEvent
public void onIconUpdate(GuildUpdateIconEvent event) {
try {
PreparedStatement ps = Rixa.getDbManager().getConnection().prepareStatement("UPDATE `core` SET `icon` = ? WHERE `core`.`guild_id` = ?;");
ps.setString(1, event.getGuild().getIconId());
ps.setString(2, event.getGuild().getId());
Rixa.getDbManager().executeUpdate(ps);
} catch (SQLException e) {
e.printStackTrace();
}
}
@SubscribeEvent
public void onOwnerUpdate(GuildUpdateOwnerEvent event) {
try {
PreparedStatement ps = Rixa.getDbManager().getConnection().prepareStatement("UPDATE `core` SET `guild_owner` = ? WHERE `core`.`guild_id` = ?;");
ps.setString(1, event.getGuild().getOwner().getUser().getName());
ps.setString(2, event.getGuild().getId());
Rixa.getDbManager().executeUpdate(ps);
} catch (SQLException e) {
e.printStackTrace();
}
}
@SubscribeEvent
public void onRegionUpdate(GuildUpdateRegionEvent event) {
try {
PreparedStatement ps = Rixa.getDbManager().getConnection().prepareStatement("UPDATE `core` SET `guild_region` = ? WHERE `core`.`guild_id` = ?;");
ps.setString(1, event.getGuild().getRegion().getName());
ps.setString(2, event.getGuild().getId());
Rixa.getDbManager().executeUpdate(ps);
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,4 @@
package me.savvy.rixa.modules.economy;
public class Economy {
}

View File

@ -84,8 +84,7 @@ public class LevelsModule implements RixaModule {
.append("`")
.append(i + start + 1/*(page > 1) ? ((i + 1) * 10) : i + 1*/)
.append(")` ")
.append(
user.getUser().getName())
.append(user.getUser().getName())
.append("#").append(user.getUser().getDiscriminator())
.append(" (Lvl. ").append(user.getLevel()).append(")")
.append("\n");
@ -132,8 +131,8 @@ public class LevelsModule implements RixaModule {
insert();
}
String query = "SELECT `levels` FROM `modules` WHERE `guild_id` = ?;";
PreparedStatement ps = null;
ResultSet rs = null;
PreparedStatement ps;
ResultSet rs;
try {
ps = Rixa.getDatabase().getConnection().get().prepareStatement(query);
ps.setString(1, getRixaGuild().getGuild().getId());