This commit is contained in:
Tyler Murphy 2022-08-31 14:52:54 -04:00
parent 2839f973c3
commit 5a50f81abb
13 changed files with 148 additions and 41 deletions

View file

@ -2,23 +2,20 @@ package net.tylermurphy.ken.command;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.GuildMessageChannel; import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.interactions.InteractionHook; import net.dv8tion.jda.api.interactions.InteractionHook;
import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback;
import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.dv8tion.jda.api.interactions.components.ActionRow; import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.LayoutComponent; import net.dv8tion.jda.api.interactions.components.LayoutComponent;
import net.dv8tion.jda.api.interactions.components.buttons.Button; import net.dv8tion.jda.api.interactions.components.buttons.Button;
import net.dv8tion.jda.api.interactions.components.selections.SelectMenu; import net.dv8tion.jda.api.interactions.components.selections.SelectMenu;
import net.dv8tion.jda.api.requests.restaction.WebhookMessageCreateAction; import net.dv8tion.jda.api.requests.restaction.WebhookMessageCreateAction;
import net.dv8tion.jda.api.requests.restaction.interactions.ReplyCallbackAction;
import net.dv8tion.jda.api.utils.FileUpload; import net.dv8tion.jda.api.utils.FileUpload;
import net.tylermurphy.ken.Ken; import net.tylermurphy.ken.Ken;
import net.tylermurphy.ken.command.game.Claim; import net.tylermurphy.ken.command.game.Claim;
@ -94,8 +91,7 @@ public class Responder extends ListenerAdapter {
new UnBan(), new UnBan(),
new Mute(), new Mute(),
new UnMute(), new UnMute(),
new OpenServer(), new SetJoining(),
new CloseServer(),
new History(), new History(),
}; };
Arrays.stream(objects).forEach(register::register); Arrays.stream(objects).forEach(register::register);
@ -119,7 +115,7 @@ public class Responder extends ListenerAdapter {
EmbedBuilder builder = Ken.getInstance().getDefaultEmbed() EmbedBuilder builder = Ken.getInstance().getDefaultEmbed()
.appendDescription(":x: **Invalid Permissions**\n") .appendDescription(":x: **Invalid Permissions**\n")
.appendDescription("You require the "+ register.getPermission(invoke)+" permission to use this command."); .appendDescription("You require the "+ register.getPermission(invoke)+" permission to use this command.");
event.getHook().sendMessageEmbeds(builder.build()).queue(); event.replyEmbeds(builder.build()).setEphemeral(true).queue();
return; return;
} }
@ -154,7 +150,7 @@ public class Responder extends ListenerAdapter {
.setColor(Color.RED) .setColor(Color.RED)
.setTitle(":x: **Error**") .setTitle(":x: **Error**")
.setDescription(e.getCause() != null ? e.getCause().getMessage() : e.getMessage()); .setDescription(e.getCause() != null ? e.getCause().getMessage() : e.getMessage());
event.replyEmbeds(builder.build()).setEphemeral(true).queue(); event.getHook().sendMessageEmbeds(builder.build()).setEphemeral(true).queue();
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -317,4 +313,20 @@ public class Responder extends ListenerAdapter {
return args; return args;
} }
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
User user = event.getUser();
Ken.getInstance().getDatabase().getUserTable().setData(user.getIdLong(), user.getName(), Integer.parseInt(user.getDiscriminator()));
boolean setValue = false;
String value = Ken.getInstance().getDatabase().getGuildSettingsTable().getData(event.getGuild().getIdLong(), "closeServer");
if(value != null) setValue = Boolean.parseBoolean(value);
if(!setValue){
event.getGuild().kick(user, "Server is currently closed").queue();
}
}
public void onGuildMemberRemove(GuildMemberRemoveEvent event) {
User user = event.getUser();
Ken.getInstance().getDatabase().getUserTable().setData(user.getIdLong(), user.getName(), Integer.parseInt(user.getDiscriminator()));
}
} }

View file

@ -40,13 +40,18 @@ public class Help {
.appendDescription( .appendDescription(
"These are all the commands that are included with "+name+"\n" + "These are all the commands that are included with "+name+"\n" +
"Read below to see what each command does, and what parameters the\n" + "Read below to see what each command does, and what parameters the\n" +
"command requires. Any questions? Join our [discord support server](https://discord.gg/"+supportServer+")" "command requires. Any questions? Join our [discord support server](https://discord.gg/"+supportServer+")\n"
), ),
Ken.getInstance().getDefaultEmbed() Ken.getInstance().getDefaultEmbed()
.setAuthor("Command List") .setAuthor("Command List")
.setTitle(":pen_ballpoint: **Main Commands**") .setTitle(":tools: **Admin Commands**")
.appendDescription("**/help** Gives a list of commands\n") .appendDescription("**/purge <amount>** Purges an amount of messages from a channel\n")
.appendDescription("**/purge <amount>** Purges an amount of messages from a channel\n"), .appendDescription("**/kick <user> <reason>** Kick a user from the server\n")
.appendDescription("**/tempban <user> <days> <hours> <reason> <delete>** Temp ban a user from the server\n")
.appendDescription("**/ban <user> <reason> <delete>** Bans a user from the server\n")
.appendDescription("**/unban <username> <discriminator>** Unbans a user from the server\n")
.appendDescription("**/history <username> <discriminator>** Gets users moderation history\n")
.appendDescription("**/setjoining <toggle>** Disable joining to the server\n"),
Ken.getInstance().getDefaultEmbed() Ken.getInstance().getDefaultEmbed()
.setAuthor("Command List") .setAuthor("Command List")
.setTitle(":musical_note: **Music Commands**") .setTitle(":musical_note: **Music Commands**")

View file

@ -65,7 +65,7 @@ public class Ban {
json.put("status", status); json.put("status", status);
JSONArray history = json.getJSONArray("history"); JSONArray history = json.getJSONArray("history");
history.put(new JSONObject().put("type", "ban").put("reason", reason).put("date",new Date().getTime())); history.put(new JSONObject().put("type", "ban").put("reason", reason).put("date",new Date().getTime()).put("by", sender.getIdLong()));
json.put("history", history); json.put("history", history);
table.setData(guild.getIdLong(), target.getUser().getIdLong(), json.toString()); table.setData(guild.getIdLong(), target.getUser().getIdLong(), json.toString());

View file

@ -1,4 +0,0 @@
package net.tylermurphy.ken.command.moderation;
public class CloseServer {
}

View file

@ -34,31 +34,30 @@ public class History {
long target = Ken.getInstance().getDatabase().getUserTable().getData(username, (int)args.get(1)); long target = Ken.getInstance().getDatabase().getUserTable().getData(username, (int)args.get(1));
if(target == 0L) { if(target == 0L) {
return Response.error("Unable to find this user"); return Response.error("Either the user is invalid or the user has no cached history");
} }
ModerationTable table = Ken.getInstance().getDatabase().getModerationTable(); ModerationTable table = Ken.getInstance().getDatabase().getModerationTable();
String data = table.getData(guild.getIdLong(), target); String data = table.getData(guild.getIdLong(), target);
JSONObject json = table.updateData(data); JSONObject json = table.updateData(data);
JSONObject status = json.getJSONObject("status");
JSONArray history = json.getJSONArray("history"); JSONArray history = json.getJSONArray("history");
StringBuilder historyString = new StringBuilder();
history.forEach(audit -> historyString.append(parseStatus((JSONObject) audit)));
EmbedBuilder builder = Ken.getInstance().getDefaultEmbed() EmbedBuilder builder = Ken.getInstance().getDefaultEmbed()
.setAuthor("Moderation History") .setAuthor("Moderation History");
.addField("Status", parseStatus(status), false)
.addField("History", historyString.toString(), false); if(history.length() < 1){
builder.appendDescription("User has no moderation history");
} else {
history.forEach(audit -> builder.addField(parseStatus((JSONObject) audit)));
}
return Response.success(builder.build()); return Response.success(builder.build());
} }
private String parseStatus(JSONObject status){ private MessageEmbed.Field parseStatus(JSONObject status){
String type = status.getString("type"); String type = status.getString("type");
String reason = "Reason: " + status.getString("reason"); String reason = "Reason: " + status.getString("reason");
if(type.equals("None")) return "User currently has no moderation actions against them";
String name = switch (type){ String name = switch (type){
case "ban" -> "Banned"; case "ban" -> "Banned";
case "temp-ban" -> "Temp banned"; case "temp-ban" -> "Temp banned";
@ -70,7 +69,8 @@ public class History {
String date = status.has("until") ? String date = status.has("until") ?
"Until: " + format.format(new Date(status.getLong("until"))) : "Until: " + format.format(new Date(status.getLong("until"))) :
"Date: " + format.format(new Date(status.getLong("date"))); "Date: " + format.format(new Date(status.getLong("date")));
return "**" + name + "**\n" + reason + "\n" + date + "\n"; String by = "By: <@"+status.getLong("by")+">";
return new MessageEmbed.Field(name, reason+"\n"+date+"\n"+by, false);
} }
} }

View file

@ -27,7 +27,7 @@ public class Kick {
@Command(name="kick", description="Kick a user") @Command(name="kick", description="Kick a user")
@Option(name="member", description="Member to kick", type= OptionType.USER, required=true) @Option(name="member", description="Member to kick", type= OptionType.USER, required=true)
@Option(name="reason", description="Reason to kick", type=OptionType.STRING, required=true) @Option(name="reason", description="Reason to kick", type=OptionType.STRING, required=true)
@Requirement(Permission.BAN_MEMBERS) @Requirement(Permission.KICK_MEMBERS)
public Response execute(Member sender, List<Object> args, Guild guild){ public Response execute(Member sender, List<Object> args, Guild guild){
Member target = (Member) args.get(0); Member target = (Member) args.get(0);
String reason = (String) args.get(1); String reason = (String) args.get(1);

View file

@ -1,4 +0,0 @@
package net.tylermurphy.ken.command.moderation;
public class OpenServer {
}

View file

@ -0,0 +1,34 @@
package net.tylermurphy.ken.command.moderation;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.tylermurphy.ken.Ken;
import net.tylermurphy.ken.command.Response;
import net.tylermurphy.ken.command.annotation.Command;
import net.tylermurphy.ken.command.annotation.Option;
import net.tylermurphy.ken.command.annotation.Requirement;
import java.util.List;
public class SetJoining {
@Command(name="setjoining", description="Set if the server is closed for joining")
@Option(name="toggle", description="Set to False to block new joiners", type=OptionType.BOOLEAN, required=true)
@Requirement(Permission.KICK_MEMBERS)
public Response execute(Guild guild, List<Object> args){
boolean toggle = (boolean) args.get(0);
boolean setValue = false;
String value = Ken.getInstance().getDatabase().getGuildSettingsTable().getData(guild.getIdLong(), "closeServer");
if(value != null) setValue = Boolean.parseBoolean(value);
if(toggle == setValue){
return Response.error("Server is already set to " + (toggle ? "open" : "closed"));
}
boolean success = Ken.getInstance().getDatabase().getGuildSettingsTable().setData(guild.getIdLong(), "closeServer", String.valueOf(Boolean.valueOf(toggle)));
if(success) {
return Response.error("Set the server to " + (toggle ? "open" : "closed"));
} else {
return Response.error("Failed to save the change to the database");
}
}
}

View file

@ -87,7 +87,7 @@ public class TempBan {
json.put("status", status); json.put("status", status);
JSONArray history = json.getJSONArray("history"); JSONArray history = json.getJSONArray("history");
history.put(new JSONObject().put("type", "temp-ban").put("reason", reason).put("date",new Date().getTime())); history.put(new JSONObject().put("type", "temp-ban").put("reason", reason).put("date",new Date().getTime()).put("by", sender.getIdLong()));
json.put("history", history); json.put("history", history);
table.setData(guild.getIdLong(), target.getUser().getIdLong(), json.toString()); table.setData(guild.getIdLong(), target.getUser().getIdLong(), json.toString());

View file

@ -69,7 +69,7 @@ public class UnBan {
json.put("status", status); json.put("status", status);
JSONArray history = json.getJSONArray("history"); JSONArray history = json.getJSONArray("history");
history.put(new JSONObject().put("type", "unban").put("reason", reason).put("date",new Date().getTime())); history.put(new JSONObject().put("type", "unban").put("reason", reason).put("date",new Date().getTime()).put("by", sender.getIdLong()));
json.put("history", history); json.put("history", history);
table.setData(guild.getIdLong(), target.getIdLong(), json.toString()); table.setData(guild.getIdLong(), target.getIdLong(), json.toString());

View file

@ -15,6 +15,7 @@ public class Database {
private final EconomyTable economyTable; private final EconomyTable economyTable;
private final ModerationTable moderationTable; private final ModerationTable moderationTable;
private final UserTable userTable; private final UserTable userTable;
private final GuildSettingsTable guildSettingsTable;
public Database(){ public Database(){
if(Ken.getInstance().getConfig().getBoolean("database.sqlite")) { if(Ken.getInstance().getConfig().getBoolean("database.sqlite")) {
@ -26,6 +27,7 @@ public class Database {
economyTable = new EconomyTable(this); economyTable = new EconomyTable(this);
moderationTable = new ModerationTable(this); moderationTable = new ModerationTable(this);
userTable = new UserTable(this); userTable = new UserTable(this);
guildSettingsTable = new GuildSettingsTable(this);
} }
public SelfRoleTable getSelfRoleData(){ public SelfRoleTable getSelfRoleData(){
@ -40,6 +42,8 @@ public class Database {
public UserTable getUserTable() { return userTable; } public UserTable getUserTable() { return userTable; }
public GuildSettingsTable getGuildSettingsTable() { return guildSettingsTable; }
protected Connection connect() throws SQLException { protected Connection connect() throws SQLException {
return connection.connect(); return connection.connect();
} }

View file

@ -0,0 +1,57 @@
package net.tylermurphy.ken.database;
import net.tylermurphy.ken.Ken;
import java.sql.*;
public class GuildSettingsTable {
private final Database database;
public GuildSettingsTable(Database database){
String sql = """
CREATE TABLE IF NOT EXISTS guild_settings_data (
guild_id BIGINT NOT NULL,
key VARCHAR(64) NOT NULL,
value VARCHAR(24) NOT NULL,
PRIMARY KEY (guild_id,key)
);""";
try(Connection connection = database.connect(); Statement statement = connection.createStatement()) {
statement.executeUpdate(sql);
} catch (SQLException e) {
Ken.getInstance().getLogger().error("SQL Error: " + e.getMessage());
}
this.database = database;
}
public String getData(long guildId, String key){
String sql = "SELECT * FROM guild_settings_data WHERE guild_id=? AND key=?";
try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(1, guildId);
statement.setString(2, key);
ResultSet rs = statement.executeQuery();
if(rs.next()) return rs.getString("value");
else return null;
} catch (SQLException e) {
Ken.getInstance().getLogger().error("SQL Error: " + e.getMessage());
return null;
}
}
public boolean setData(long guildId, String key, String value){
String sql = "INSERT OR REPLACE INTO guild_settings_data (guild_id, key, value) VALUES(?,?,?)";
try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(1, guildId);
statement.setString(2, key);
statement.setString(3, value);
return statement.executeUpdate() != 0;
} catch (SQLException e) {
Ken.getInstance().getLogger().error("SQL Error: " + e.getMessage());
return false;
}
}
}

View file

@ -1,8 +1,8 @@
package net.tylermurphy.ken.database; package net.tylermurphy.ken.database;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.User;
import net.tylermurphy.ken.Ken; import net.tylermurphy.ken.Ken;
import org.json.JSONObject;
import java.sql.*; import java.sql.*;
@ -17,7 +17,7 @@ public class UserTable {
user_id BIGINT NOT NULL, user_id BIGINT NOT NULL,
username VARCHAR(64) NOT NULL, username VARCHAR(64) NOT NULL,
discriminator INT NOT NULL, discriminator INT NOT NULL,
PRIMARY KEY (user_id) PRIMARY KEY (username,discriminator)
);"""; );""";
try(Connection connection = database.connect(); Statement statement = connection.createStatement()) { try(Connection connection = database.connect(); Statement statement = connection.createStatement()) {
@ -31,7 +31,10 @@ public class UserTable {
public long getData(String username, int discriminator){ public long getData(String username, int discriminator){
User cache = Ken.getInstance().getUserByName(username, String.valueOf(discriminator)); User cache = Ken.getInstance().getUserByName(username, String.valueOf(discriminator));
if(cache != null) return cache.getIdLong(); if(cache != null){
setData(cache.getIdLong(), username, discriminator);
return cache.getIdLong();
}
String sql = "SELECT * FROM user_data WHERE username=? AND discriminator=?"; String sql = "SELECT * FROM user_data WHERE username=? AND discriminator=?";
try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, username); statement.setString(1, username);