Added database, polls wrapper, & more.

This commit is contained in:
Malcom Green
2017-05-29 18:31:22 -04:00
parent 3e41476f37
commit 752db67c6b
19 changed files with 746 additions and 358 deletions

View File

@@ -8,7 +8,8 @@ import me.savvy.rixa.commands.general.ServerInfoCommand;
import me.savvy.rixa.commands.handlers.CommandExec;
import me.savvy.rixa.commands.handlers.CommandHandler;
import me.savvy.rixa.commands.mod.DeleteMessagesCommand;
import me.savvy.rixa.commands.mod.PurgeCommand;
import me.savvy.rixa.commands.mod.PurgeMessagesCommand;
import me.savvy.rixa.database.DatabaseManager;
import me.savvy.rixa.events.BotEvent;
import me.savvy.rixa.events.MessageEvent;
import me.savvy.rixa.modules.reactions.handlers.ReactionManager;
@@ -22,8 +23,11 @@ import net.dv8tion.jda.core.exceptions.RateLimitedException;
import net.dv8tion.jda.core.hooks.AnnotatedEventManager;
import javax.security.auth.login.LoginException;
import java.io.*;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
@@ -32,34 +36,17 @@ import java.util.logging.Logger;
public class Rixa {
private static List<JDA> shardsList;
private static DatabaseManager dbManager;
private static long timeUp;
private static Rixa instance; // String search = event.getMessage().getContent().substring(event.getMessage().getContent().indexOf(" ") + 1);
private static Map<String, String> config;
public static void main(String[] args) throws LoginException, InterruptedException, RateLimitedException {
public static void main(String[] args) {
instance = new Rixa();
shardsList = new LinkedList<>();
int shards = 3;
for(int i = 0; i < shards; i++) {
Logger.getLogger("Rixa").info("Loading shard #" + i);
JDABuilder jda = new JDABuilder(AccountType.BOT)
.setToken("MjkxNTM5Njg2NTEyNTI1MzMy.DAZKfQ.kIHSmuCJHhklyC3gBAi0c_VKp-w")
.setEventManager(new AnnotatedEventManager())
.addEventListener(new MessageEvent())
.addEventListener(new BotEvent())
.setGame(Game.of("Rixa 1.0 | In Dev", "http://rixa.io"))
.setAutoReconnect(true)
.setStatus(OnlineStatus.ONLINE)
.setAudioEnabled(true)
.useSharding(i, shards);
shardsList.add(jda.buildBlocking());
getInstance().getLogger().info("Shard #" + i + " has been loaded");
}
timeUp = System.currentTimeMillis();
register(new CommandExec[] {
new InfoCommand(), new ServerInfoCommand(), new HelpCommand(),
new DeleteMessagesCommand(), new PingCommand(), new PurgeCommand(),
new BatchMoveCommand() });
ReactionManager.registerReaction(new HelpReaction());
config = new HashMap<>();
populateConfiguration();
load();
}
private static void register(CommandExec commandExecs[]) {
@@ -79,4 +66,69 @@ public class Rixa {
public Logger getLogger() {
return Logger.getLogger("Rixa");
}
private static void load() {
if(!config.containsKey("TOKEN")) {
getInstance().getLogger().severe("Could not find \"TOKEN\" in config.text! Shutting down...");
System.exit(0);
}
dbManager = new DatabaseManager(config.get("SQL_HOSTNAME"), config.get("SQL_PORT"), config.get("SQL_DATABASE"), config.get("SQL_USER"), config.get("SQL_PASSWORD"));
dbManager.createTable();
try {
int shards = 3;
for(int i = 0; i < shards; i++) {
Logger.getLogger("Rixa").info("Loading shard #" + i);
JDABuilder jda = new JDABuilder(AccountType.BOT)
.setToken(config.get("TOKEN"))
.setEventManager(new AnnotatedEventManager())
.addEventListener(new MessageEvent())
.addEventListener(new BotEvent());
if(config.containsKey("GAME")) {
jda.setGame(Game.of(config.get("GAME")));
}
jda.setAutoReconnect(true)
.setStatus(OnlineStatus.ONLINE)
.setAudioEnabled(true)
.useSharding(i, shards);
shardsList.add(jda.buildBlocking());
getInstance().getLogger().info("Shard #" + i + " has been loaded");
}
} catch (LoginException | InterruptedException | RateLimitedException e) {
e.printStackTrace();
}
timeUp = System.currentTimeMillis();
register(new CommandExec[] {
new InfoCommand(), new ServerInfoCommand(), new HelpCommand(),
new DeleteMessagesCommand(), new PingCommand(), new PurgeMessagesCommand(),
new BatchMoveCommand() });
ReactionManager.registerReaction(new HelpReaction());
}
public DatabaseManager getDbManager() {
return dbManager;
}
public void setDbManager(DatabaseManager dbManager) {
this.dbManager = dbManager;
}
private static void populateConfiguration() {
FileReader fileReader = null;
try {
fileReader = new FileReader(new File("config.txt"));
} catch (FileNotFoundException e) {
getInstance().getLogger().severe("Could not find file \"config.text\"! Shutting down...");
System.exit(0);
}
BufferedReader br = new BufferedReader(fileReader);
String line = null;
try {
while ((line = br.readLine()) != null) {
String[] s = line.split(":");
config.put(s[0], s[1]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@@ -13,6 +13,7 @@ import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.core.exceptions.PermissionException;
import java.awt.*;
import java.util.Collections;
import java.util.List;
/**
@@ -37,13 +38,17 @@ public class BatchMoveCommand implements CommandExec {
Role old_role = event.getMessage().getMentionedRoles().get(0);
Role new_role = event.getMessage().getMentionedRoles().get(1);
List<Member> userWithRole = event.getGuild().getMembersWithRoles(old_role);
if(userWithRole.size() == 0) {
new MessageBuilder("There are no users with the role " + old_role.getAsMention()).setColor(old_role.getColor()).queue(event.getChannel());
return;
}
new MessageBuilder("Moving **" + userWithRole.size() + "** users with role: " + old_role.getAsMention()
+ " to " + new_role.getAsMention()).setColor(old_role.getColor()).queue(event.getChannel());
int success = 0;
for(Member member: userWithRole) {
try {
event.getGuild().getController().removeRolesFromMember(member, old_role).queue();
event.getGuild().getController().addRolesToMember(member, new_role).queue();
event.getGuild().getController().modifyMemberRoles
(member, Collections.singletonList(new_role), Collections.singletonList(old_role)).queue();
success++;
} catch(PermissionException ex) {
new MessageBuilder("I do not have permission to modify " + member.getAsMention() + "'s role").setColor(Color.RED).queue(event.getChannel());

View File

@@ -22,7 +22,7 @@ import java.util.List;
/**
* Created by Timber on 5/23/2017.
*/
public class PurgeCommand implements CommandExec {
public class PurgeMessagesCommand implements CommandExec {
@Override
@Command(mainCommand = "purge",

View File

@@ -0,0 +1,128 @@
package me.savvy.rixa.database;
import me.savvy.rixa.Rixa;
import me.savvy.rixa.database.mysql.mysql.MySQL;
import me.savvy.rixa.enums.Result;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseManager {
private Connection connection = null;
private MySQL MYSQL = null;
public DatabaseManager(String hostName, String port, String databaseName, String userName, String password) {
MYSQL = new MySQL(hostName, port, databaseName, userName, password);
}
public Connection getConnection() {
return connection;
}
public void createTable() {
try {
connection = MYSQL.openConnection();
Rixa.getInstance().getLogger().info("Mysql database connected");
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
try {
PreparedStatement ps = connection.prepareStatement(
"CREATE TABLE IF NOT EXISTS `core` (`guild_id` varchar(255) NOT NULL, `guild_name` varchar(255) NOT NULL, PRIMARY KEY (`guild_id`));");
ps.executeUpdate();
} catch (SQLException e) {
Rixa.getInstance().getLogger().severe("Could not check if table exists, stopping server.");
e.printStackTrace();
// Redirect to 500
}
}
private void checkConnection() {
try {
if(!MYSQL.checkConnection()) {
connection = MYSQL.openConnection();
}
} catch(ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public Result executeUpdate(PreparedStatement ps) {
checkConnection();
try {
ps.executeUpdate();
return Result.SUCCESS;
} catch(SQLException e) {
e.printStackTrace();
return Result.ERROR;
}
}
public Object getObject(String string, String objToGet) throws SQLException {
checkConnection();
PreparedStatement ps = connection.prepareStatement(string);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return rs.getString(objToGet);
} else {
return null;
}
}
public ResultSet executeQuery(String query) {
checkConnection();
try {
PreparedStatement ps = connection.prepareStatement(query);
return ps.executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
}
return null;
}
public int getCount(String table) {
checkConnection();
ResultSet rs;
try {
PreparedStatement ps = connection.prepareStatement("SELECT count(*) FROM '" + table + "';");
rs = ps.executeQuery();
if (rs.next()) {
return rs.getInt(1);
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return 0;
}
public Result checkExists(String string) {
checkConnection();
try {
PreparedStatement ps = connection.prepareStatement(string);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
return Result.TRUE;
}else {
return Result.FALSE;
}
} catch (SQLException e) {
e.printStackTrace();
return Result.ERROR;
}
}
public Result insert(String string) {
checkConnection();
PreparedStatement ps;
try {
ps = connection.prepareStatement(string);
ps.executeUpdate();
return Result.SUCCESS;
} catch (SQLException e) {
e.printStackTrace();
return Result.ERROR;
}
}
}

View File

@@ -0,0 +1,126 @@
package me.savvy.rixa.database.mysql;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Abstract Database class, serves as a base for any connection method (MySQL,
* SQLite, etc.)
*
* @author -_Husky_-
* @author tips48
*/
public abstract class Database {
protected Connection connection;
/**
* Creates a new Database
*
*/
protected Database() {
this.connection = null;
}
/**
* Opens a connection with the database
*
* @return Opened connection
* @throws SQLException
* if the connection can not be opened
* @throws ClassNotFoundException
* if the driver cannot be found
*/
public abstract Connection openConnection() throws SQLException,
ClassNotFoundException;
/**
* Checks if a connection is open with the database
*
* @return true if the connection is open
* @throws SQLException
* if the connection cannot be checked
*/
public boolean checkConnection() throws SQLException {
return connection != null && !connection.isClosed();
}
/**
* Gets the connection with the database
*
* @return Connection with the database, null if none
*/
public Connection getConnection() {
return connection;
}
/**
* Closes the connection with the database
*
* @return true if successful
* @throws SQLException
* if the connection cannot be closed
*/
public boolean closeConnection() throws SQLException {
if (connection == null) {
return false;
}
connection.close();
return true;
}
/**
* Executes a SQL Query<br>
*
* If the connection is closed, it will be opened
*
* @param query
* Query to be run
* @return the results of the query
* @throws SQLException
* If the query cannot be executed
* @throws ClassNotFoundException
* If the driver cannot be found; see {@link #openConnection()}
*/
public ResultSet querySQL(String query) throws SQLException,
ClassNotFoundException {
if (!checkConnection()) {
openConnection();
}
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(query);
return result;
}
/**
* Executes an Update SQL Query<br>
* See {@link Statement#executeUpdate(String)}<br>
* If the connection is closed, it will be opened
*
* @param query
* Query to be run
* @return Result Code, see {@link Statement#executeUpdate(String)}
* @throws SQLException
* If the query cannot be executed
* @throws ClassNotFoundException
* If the driver cannot be found; see {@link #openConnection()}
*/
public int updateSQL(String query) throws SQLException,
ClassNotFoundException {
if (!checkConnection()) {
openConnection();
}
Statement statement = connection.createStatement();
int result = statement.executeUpdate(query);
return result;
}
}

View File

@@ -0,0 +1,81 @@
package me.savvy.rixa.database.mysql.mysql;
import me.savvy.rixa.database.mysql.Database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Connects to and uses a MySQL database
*
* @author -_Husky_-
* @author tips48
*/
public class MySQL extends Database {
private final String user;
private final String database;
private final String password;
private final String port;
private final String hostname;
/**
* Creates a new MySQL instance
*
* @param hostname
* Name of the host
* @param port
* Port number
* @param username
* Username
* @param password
* Password
*/
public MySQL(String hostname, String port, String username,
String password) {
this(hostname, port, null, username, password);
}
/**
* Creates a new MySQL instance for a specific database
*
* @param hostname
* Name of the host
* @param port
* Port number
* @param database
* Database name
* @param username
* Username
* @param password
* Password
*/
public MySQL(String hostname, String port, String database,
String username, String password) {
this.hostname = hostname;
this.port = port;
this.database = database;
this.user = username;
this.password = password;
}
@Override
public Connection openConnection() throws SQLException,
ClassNotFoundException {
if (checkConnection()) {
return connection;
}
String connectionURL = "jdbc:mysql://"
+ this.hostname + ":" + this.port;
if (database != null) {
connectionURL = connectionURL + "/" + this.database;
}
Class.forName("com.mysql.jdbc.Driver");
// Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(connectionURL,
this.user, this.password);
return connection;
}
}

View File

@@ -0,0 +1,12 @@
package me.savvy.rixa.enums;
/**
* Created by Timber on 1/24/2017.
*/
public enum Result {
SUCCESS,
TRUE,
FALSE,
ERROR;
}

View File

@@ -20,8 +20,12 @@ public class BotEvent {
@SubscribeEvent
public void onReady(ReadyEvent event) {
Rixa.getInstance().getLogger().info("Successfully loaded...");
event.getJDA().getGuilds().forEach(RixaGuild::new);
try {
Rixa.getInstance().getLogger().info("Successfully loaded...");
event.getJDA().getGuilds().forEach(RixaGuild::new);
} catch (Exception e) {
e.printStackTrace();
}
}
@SubscribeEvent

View File

@@ -1,11 +1,62 @@
package me.savvy.rixa.extras.polls;
import me.savvy.rixa.utils.MessageBuilder;
import net.dv8tion.jda.core.EmbedBuilder;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Timber on 5/23/2017.
*/
public class Poll {
public Poll() {
private String name, description;
private List<String> options;
public Poll(String name) {
this.name = name;
options = new ArrayList<>();
}
public String getTitle() {
return name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<String> getOptions() {
return options;
}
public boolean addOption(String s) {
if(options.size() == 10) {
return false;
}
options.add(s);
return true;
}
public String removeOption(int i) {
if(options.size() <= 10) {
return options.remove(i);
}
return "";
}
public EmbedBuilder getBuilder(Color color) {
MessageBuilder messageBuilder = new MessageBuilder(description).setTitle("Polls");
for (int i = 0; i < options.size(); i++) {
messageBuilder.addField("Option " + i, options.get(i), true);
}
messageBuilder.setColor(color);
return messageBuilder.getBuilder();
}
}

View File

@@ -8,4 +8,6 @@ public interface RixaModule {
String getName();
String getDescription();
boolean isEnabled();
}

View File

@@ -15,4 +15,9 @@ public class LevelsModule implements RixaModule {
public String getDescription() {
return "";
}
@Override
public boolean isEnabled() {
return false;
}
}

View File

@@ -15,4 +15,9 @@ public class MusicModule implements RixaModule {
public String getDescription() {
return "";
}
@Override
public boolean isEnabled() {
return false;
}
}

View File

@@ -31,6 +31,11 @@ public class MessageBuilder {
return this;
}
public MessageBuilder addField(String name, String value, boolean inLine) {
builder.addField(name, value, inLine);
return this;
}
public EmbedBuilder getBuilder() {
return builder;
}