This commit is contained in:
Tyler Murphy 2022-09-02 07:12:22 -04:00
parent 2bb0dcd0e2
commit 207b8857e8
15 changed files with 214 additions and 230 deletions

View file

@ -198,6 +198,7 @@ public class Responder extends ListenerAdapter {
.setTitle(":x: **Error**") .setTitle(":x: **Error**")
.setDescription(e.getCause().getMessage()); .setDescription(e.getCause().getMessage());
event.getHook().editOriginalEmbeds(builder.build()).queue(); event.getHook().editOriginalEmbeds(builder.build()).queue();
event.getHook().editOriginalComponents(new ArrayList<>()).queue();
} }
} }
@ -246,6 +247,7 @@ public class Responder extends ListenerAdapter {
.setTitle(":x: **Error**") .setTitle(":x: **Error**")
.setDescription(e.getCause().getMessage()); .setDescription(e.getCause().getMessage());
event.getHook().sendMessageEmbeds(builder.build()).queue(); event.getHook().sendMessageEmbeds(builder.build()).queue();
event.getHook().editOriginalComponents(new ArrayList<>()).queue();
} }
} }
@ -276,6 +278,7 @@ public class Responder extends ListenerAdapter {
.setColor(Color.RED) .setColor(Color.RED)
.setDescription(response.getMessage()); .setDescription(response.getMessage());
hook.sendMessageEmbeds(builder.build()).queue(); hook.sendMessageEmbeds(builder.build()).queue();
hook.editOriginalComponents(new ArrayList<>()).queue();
} else if(response.isDelete()) { } else if(response.isDelete()) {
hook.deleteOriginal().queue(); hook.deleteOriginal().queue();
} else { } else {

View file

@ -3,11 +3,11 @@ package net.tylermurphy.ken.command.main;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.tylermurphy.ken.Ken; import net.tylermurphy.ken.Ken;
import net.tylermurphy.ken.command.annotation.ButtonCallback; import net.tylermurphy.ken.command.annotation.ButtonCallback;
import net.tylermurphy.ken.command.annotation.Command; import net.tylermurphy.ken.command.annotation.Command;
import net.tylermurphy.ken.command.Response; import net.tylermurphy.ken.command.Response;
import net.tylermurphy.ken.util.Checks;
public class Help { public class Help {
@ -18,13 +18,12 @@ public class Help {
@ButtonCallback(name="help") @ButtonCallback(name="help")
public Response onButton(String id, Message message, Member sender){ public Response onButton(String id, Message message, Member sender){
int page;
try { Checks.hasPagedEmbed(message); }
catch (RuntimeException e) { return Response.error(e.getMessage()); }
int page = Integer.parseInt(message.getEmbeds().get(0).getFooter().getText().split("/")[0].substring(5));
int pages = pageEmbeds.length; int pages = pageEmbeds.length;
if (message != null && message.getEmbeds().size() > 0 && message.getEmbeds().get(0) != null) {
page = Integer.parseInt(message.getEmbeds().get(0).getFooter().getText().split("/")[0].substring(5));
} else {
page = 0;
}
if(id.equals("previous")) if(id.equals("previous"))
page = page - 1 < 1 ? pages : page - 1; page = page - 1 < 1 ? pages : page - 1;
else else

View file

@ -14,6 +14,7 @@ import net.tylermurphy.ken.command.annotation.Command;
import net.tylermurphy.ken.command.annotation.Option; import net.tylermurphy.ken.command.annotation.Option;
import net.tylermurphy.ken.command.annotation.Requirement; import net.tylermurphy.ken.command.annotation.Requirement;
import net.tylermurphy.ken.database.ModerationTable; import net.tylermurphy.ken.database.ModerationTable;
import net.tylermurphy.ken.database.UserTable;
import net.tylermurphy.ken.util.Checks; import net.tylermurphy.ken.util.Checks;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
@ -33,31 +34,15 @@ public class Ban {
Member target = (Member) args.get(0); Member target = (Member) args.get(0);
String reason = (String) args.get(1); String reason = (String) args.get(1);
boolean purge = (boolean) args.get(2); boolean purge = (boolean) args.get(2);
if(target == sender){
return Response.error("You are not allowed to do this to yourself"); try { Checks.hasPermission(sender, target); }
} catch (RuntimeException e) { return Response.error(e.getMessage()); }
Role low = Checks.getHighestRole(target);
Role high = Checks.getHighestRole(sender);
if(!Checks.getRolePermission(high, low)){
return Response.error("You need a higher role than the target");
}
Role self = Checks.getHighestRole(guild.getSelfMember());
if(!Checks.getRolePermission(self, low)){
return Response.error("I need a higher role than the target");
}
if(guild.getOwner() == target){
return Response.error("You cannot to this to the server owner");
}
try { try {
guild.retrieveBan(target).complete(); guild.retrieveBan(target).complete();
return Response.error("User is already banned from this server"); return Response.error("User is already banned from this server");
} catch (ErrorResponseException ignored) {} } catch (ErrorResponseException ignored) {}
ModerationTable table = Ken.getInstance().getDatabase().getModerationTable();
String data = table.getData(guild.getIdLong(), target.getUser().getIdLong());
JSONObject json = table.updateData(data);
try { try {
guild.removeTimeout(target).queue(); guild.removeTimeout(target).queue();
} catch (Exception ignored){} } catch (Exception ignored){}
@ -68,19 +53,19 @@ public class Ban {
return Response.error("Failed to ban user"); return Response.error("Failed to ban user");
} }
JSONObject status = json.getJSONObject("status"); ModerationTable table = Ken.getInstance().getDatabase().getModerationTable();
status.put("type", "ban"); UserTable userTable = Ken.getInstance().getDatabase().getUserTable();
status.put("reason", reason); JSONObject json = table.getData(guild.getIdLong(), target.getUser().getIdLong());
status.put("until", 0L);
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()).put("by", sender.getIdLong())); history.put(new JSONObject()
json.put("history", history); .put("type", "ban")
.put("reason", reason)
.put("date",new Date().getTime())
.put("by", sender.getIdLong())
);
table.setData(guild.getIdLong(), target.getUser().getIdLong(), json.toString()); table.setData(guild.getIdLong(), target.getUser().getIdLong(), history, "ban", 0L);
userTable.setData(target.getIdLong(), target.getUser().getName(), Integer.parseInt(target.getUser().getDiscriminator()));
Ken.getInstance().getDatabase().getUserTable().setData(target.getIdLong(), target.getUser().getName(), Integer.parseInt(target.getUser().getDiscriminator()));
PrivateChannel channel = target.getUser().openPrivateChannel().complete(); PrivateChannel channel = target.getUser().openPrivateChannel().complete();
if(channel != null){ if(channel != null){

View file

@ -11,12 +11,16 @@ import net.tylermurphy.ken.command.annotation.Command;
import net.tylermurphy.ken.command.annotation.Option; import net.tylermurphy.ken.command.annotation.Option;
import net.tylermurphy.ken.command.annotation.Requirement; import net.tylermurphy.ken.command.annotation.Requirement;
import net.tylermurphy.ken.database.ModerationTable; import net.tylermurphy.ken.database.ModerationTable;
import net.tylermurphy.ken.util.Checks;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
public class History { public class History {
@ -39,25 +43,25 @@ public class History {
} }
ModerationTable table = Ken.getInstance().getDatabase().getModerationTable(); ModerationTable table = Ken.getInstance().getDatabase().getModerationTable();
String data = table.getData(guild.getIdLong(), target); JSONObject json = table.getData(guild.getIdLong(), target);
JSONObject json = table.updateData(data);
JSONArray history = json.getJSONArray("history"); JSONArray history = json.getJSONArray("history");
int page = 1; return Response.success(generateEmbed(history, 1, username, discriminator)).addSecondaryButton("history", "previous", "Previous").addSecondaryButton("history", "next", "Next");
int pages = (history.length()-1)/4+1;
return Response.success(generateEmbed(history, page, username, discriminator)).addSecondaryButton("history", "previous", "Previous").addSecondaryButton("history", "next", "Next");
} }
@ButtonCallback(name="history") @ButtonCallback(name="history")
public Response onButton(String id, Message message, Guild guild){ public Response onButton(String id, Message message, Guild guild){
if(message == null || message.getEmbeds().size() < 1){
return Response.error("Message missing"); try { Checks.hasPagedEmbed(message); }
} catch (RuntimeException e) { return Response.error(e.getMessage()); }
MessageEmbed temp = message.getEmbeds().get(0); MessageEmbed temp = message.getEmbeds().get(0);
String username = temp.getDescription().substring(6).split("#")[0]; String description = temp.getDescription();
String discriminator = temp.getDescription().substring(6).split("#")[1]; assert description != null;
int stop = description.indexOf('\n');
if(stop == -1) stop = description.length();
String username = description.substring(6, stop).split("#")[0];
String discriminator = description.substring(6, stop).split("#")[1];
long target = Ken.getInstance().getDatabase().getUserTable().getData(username, Integer.parseInt(discriminator)); long target = Ken.getInstance().getDatabase().getUserTable().getData(username, Integer.parseInt(discriminator));
if(target == 0L || temp.getFooter() == null) { if(target == 0L || temp.getFooter() == null) {
@ -65,8 +69,7 @@ public class History {
} }
ModerationTable table = Ken.getInstance().getDatabase().getModerationTable(); ModerationTable table = Ken.getInstance().getDatabase().getModerationTable();
String data = table.getData(guild.getIdLong(), target); JSONObject json = table.getData(guild.getIdLong(), target);
JSONObject json = table.updateData(data);
JSONArray history = json.getJSONArray("history"); JSONArray history = json.getJSONArray("history");
int page = Integer.parseInt(temp.getFooter().getText().split("/")[0].substring(5)); int page = Integer.parseInt(temp.getFooter().getText().split("/")[0].substring(5));
@ -86,7 +89,7 @@ public class History {
.setDescription("User: "+username+"#"+discriminator) .setDescription("User: "+username+"#"+discriminator)
.setFooter("Page "+page+"/"+pages); .setFooter("Page "+page+"/"+pages);
if(history.length() < 1){ if(history.length() < 1){
builder.appendDescription("User has no moderation history"); builder.appendDescription("\nUser has no moderation history");
} else { } else {
for(int i =(page-1)*4; i<Math.min((page-1)*4+4, history.length()); i++){ for(int i =(page-1)*4; i<Math.min((page-1)*4+4, history.length()); i++){
builder.addField(parseStatus(history.getJSONObject(history.length()-i-1))); builder.addField(parseStatus(history.getJSONObject(history.length()-i-1)));
@ -96,23 +99,42 @@ public class History {
} }
private MessageEmbed.Field parseStatus(JSONObject status){ private MessageEmbed.Field parseStatus(JSONObject status){
SimpleDateFormat format = new SimpleDateFormat("MMM d, y h:ma zz");
StringBuilder builder = new StringBuilder();
String type = status.getString("type"); String type = status.getString("type");
String reason = "Reason: " + status.getString("reason");
String name = switch (type){ String name = switch (type){
case "ban" -> "Banned"; case "ban" -> "Banned";
case "temp-ban" -> "Temp banned"; case "tempban" -> "Temp banned";
case "unban" -> "Unbanned"; case "unban" -> "Unbanned";
case "kick" -> "Kicked"; case "kick" -> "Kicked";
case "mute" -> "Muted"; case "mute" -> "Muted";
case "unmute" -> "Unmuted"; case "unmute" -> "Unmuted";
default -> throw new RuntimeException("Unknown value: " + type); default -> throw new RuntimeException("Unknown value: " + type);
}; };
SimpleDateFormat format = new SimpleDateFormat("MMM d, y h:ma zz"); builder.append("Reason: ")
String date = status.has("until") ? .append(status.getString("reason"))
"Until: " + format.format(new Date(status.getLong("until"))) : .append("\n")
"Date: " + format.format(new Date(status.getLong("date"))); .append("Date: ")
String by = "By: <@"+status.getLong("by")+">"; .append(format.format(new Date(status.getLong("date"))))
return new MessageEmbed.Field(name, reason+"\n"+date+"\n"+by, false); .append("\n")
.append("By: <@")
.append(status.getLong("by"))
.append(">\n");
if(status.has("duration")){
Date end = new Date(status.getLong("duration"));
Date start = new Date(status.getLong("date"));
long diff = Math.abs(end.getTime() - start.getTime())+60000;
long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
long buffer = TimeUnit.MILLISECONDS.convert(days, TimeUnit.DAYS);
long hours = TimeUnit.HOURS.convert(diff-buffer, TimeUnit.MILLISECONDS);
builder.append("Duration: ");
if(days/30 > 0) builder.append(days/30).append("m");
if(days%30 > 0) builder.append(days%30).append("d");
if(hours > 0) builder.append(hours).append("h");
}
return new MessageEmbed.Field(name, builder.toString(), false);
} }
} }

View file

@ -14,6 +14,7 @@ import net.tylermurphy.ken.command.annotation.Command;
import net.tylermurphy.ken.command.annotation.Option; import net.tylermurphy.ken.command.annotation.Option;
import net.tylermurphy.ken.command.annotation.Requirement; import net.tylermurphy.ken.command.annotation.Requirement;
import net.tylermurphy.ken.database.ModerationTable; import net.tylermurphy.ken.database.ModerationTable;
import net.tylermurphy.ken.database.UserTable;
import net.tylermurphy.ken.util.Checks; import net.tylermurphy.ken.util.Checks;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
@ -31,31 +32,15 @@ public class Kick {
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);
if(target == sender){
return Response.error("You are not allowed to do this to yourself"); try { Checks.hasPermission(sender, target); }
} catch (RuntimeException e) { return Response.error(e.getMessage()); }
Role low = Checks.getHighestRole(target);
Role high = Checks.getHighestRole(sender);
if(!Checks.getRolePermission(high, low)){
return Response.error("You need a higher role than the target");
}
Role self = Checks.getHighestRole(guild.getSelfMember());
if(!Checks.getRolePermission(self, low)){
return Response.error("I need a higher role than the target");
}
if(guild.getOwner() == target){
return Response.error("You cannot to this to the server owner");
}
try { try {
guild.retrieveBan(target).complete(); guild.retrieveBan(target).complete();
return Response.error("User is currently banned and cannot be kicked"); return Response.error("User is currently banned and cannot be kicked");
} catch (ErrorResponseException ignored) {} } catch (ErrorResponseException ignored) {}
ModerationTable table = Ken.getInstance().getDatabase().getModerationTable();
String data = table.getData(guild.getIdLong(), target.getUser().getIdLong());
JSONObject json = table.updateData(data);
try { try {
guild.removeTimeout(target).queue(); guild.removeTimeout(target).queue();
} catch (Exception ignored){} } catch (Exception ignored){}
@ -66,19 +51,19 @@ public class Kick {
return Response.error("Failed to kick user"); return Response.error("Failed to kick user");
} }
JSONObject status = json.getJSONObject("status"); ModerationTable table = Ken.getInstance().getDatabase().getModerationTable();
status.put("type", "None"); UserTable userTable = Ken.getInstance().getDatabase().getUserTable();
status.put("reason", ""); JSONObject json = table.getData(guild.getIdLong(), target.getUser().getIdLong());
status.put("until", 0L);
json.put("status", status);
JSONArray history = json.getJSONArray("history"); JSONArray history = json.getJSONArray("history");
history.put(new JSONObject().put("type", "kick").put("reason", reason).put("date",new Date().getTime()).put("by", sender.getIdLong())); history.put(new JSONObject()
json.put("history", history); .put("type", "kick")
.put("reason", reason)
.put("date",new Date().getTime())
.put("by", sender.getIdLong())
);
table.setData(guild.getIdLong(), target.getUser().getIdLong(), json.toString()); table.setData(guild.getIdLong(), target.getUser().getIdLong(), history, "None", 0L);
userTable.setData(target.getIdLong(), target.getUser().getName(), Integer.parseInt(target.getUser().getDiscriminator()));
Ken.getInstance().getDatabase().getUserTable().setData(target.getIdLong(), target.getUser().getName(), Integer.parseInt(target.getUser().getDiscriminator()));
PrivateChannel channel = target.getUser().openPrivateChannel().complete(); PrivateChannel channel = target.getUser().openPrivateChannel().complete();
if(channel != null){ if(channel != null){

View file

@ -14,6 +14,7 @@ import net.tylermurphy.ken.command.annotation.Command;
import net.tylermurphy.ken.command.annotation.Option; import net.tylermurphy.ken.command.annotation.Option;
import net.tylermurphy.ken.command.annotation.Requirement; import net.tylermurphy.ken.command.annotation.Requirement;
import net.tylermurphy.ken.database.ModerationTable; import net.tylermurphy.ken.database.ModerationTable;
import net.tylermurphy.ken.database.UserTable;
import net.tylermurphy.ken.util.Checks; import net.tylermurphy.ken.util.Checks;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
@ -36,24 +37,14 @@ public class Mute {
Member target = (Member) args.get(0); Member target = (Member) args.get(0);
String timeString = (String) args.get(1); String timeString = (String) args.get(1);
String reason = (String) args.get(2); String reason = (String) args.get(2);
if(target == sender){
return Response.error("You are not allowed to do this to yourself"); try { Checks.hasPermission(sender, target); }
} catch (RuntimeException e) { return Response.error(e.getMessage()); }
Role low = Checks.getHighestRole(target);
Role high = Checks.getHighestRole(sender);
if(!Checks.getRolePermission(high, low)){
return Response.error("You need a higher role than the target");
}
Role self = Checks.getHighestRole(guild.getSelfMember());
if(!Checks.getRolePermission(self, low)){
return Response.error("I need a higher role than the target");
}
if(guild.getOwner() == target){
return Response.error("You cannot to this to the server owner");
}
if(target.isTimedOut()){ if(target.isTimedOut()){
return Response.error("User is already muted"); return Response.error("User is already muted");
} }
long time = Checks.convertTime(timeString); long time = Checks.convertTime(timeString);
if(time == 0L){ if(time == 0L){
return Response.error("Time to ban cannot be 0"); return Response.error("Time to ban cannot be 0");
@ -65,29 +56,26 @@ public class Mute {
SimpleDateFormat format = new SimpleDateFormat("MMM d, y h:ma zz"); SimpleDateFormat format = new SimpleDateFormat("MMM d, y h:ma zz");
String date = format.format(time); String date = format.format(time);
ModerationTable table = Ken.getInstance().getDatabase().getModerationTable();
String data = table.getData(guild.getIdLong(), target.getUser().getIdLong());
JSONObject json = table.updateData(data);
try { try {
guild.timeoutUntil(target, new Date(time).toInstant()).queue(); guild.timeoutUntil(target, new Date(time).toInstant()).queue();
} catch (Exception e){ } catch (Exception e){
return Response.error("Failed to mute user"); return Response.error("Failed to mute user");
} }
JSONObject status = json.getJSONObject("status"); ModerationTable table = Ken.getInstance().getDatabase().getModerationTable();
status.put("type", "mute"); UserTable userTable = Ken.getInstance().getDatabase().getUserTable();
status.put("reason", reason); JSONObject json = table.getData(guild.getIdLong(), target.getUser().getIdLong());
status.put("until", time);
json.put("status", status);
JSONArray history = json.getJSONArray("history"); JSONArray history = json.getJSONArray("history");
history.put(new JSONObject().put("type", "mute").put("reason", reason).put("date",new Date().getTime()).put("by", sender.getIdLong())); history.put(new JSONObject()
json.put("history", history); .put("type", "mute")
.put("reason", reason)
.put("date",new Date().getTime())
.put("by", sender.getIdLong())
.put("duration", time)
);
table.setData(guild.getIdLong(), target.getUser().getIdLong(), json.toString()); table.setData(guild.getIdLong(), target.getUser().getIdLong(), history, "mute", time);
userTable.setData(target.getIdLong(), target.getUser().getName(), Integer.parseInt(target.getUser().getDiscriminator()));
Ken.getInstance().getDatabase().getUserTable().setData(target.getIdLong(), target.getUser().getName(), Integer.parseInt(target.getUser().getDiscriminator()));
PrivateChannel channel = target.getUser().openPrivateChannel().complete(); PrivateChannel channel = target.getUser().openPrivateChannel().complete();
if(channel != null){ if(channel != null){

View file

@ -14,6 +14,7 @@ import net.tylermurphy.ken.command.annotation.Command;
import net.tylermurphy.ken.command.annotation.Option; import net.tylermurphy.ken.command.annotation.Option;
import net.tylermurphy.ken.command.annotation.Requirement; import net.tylermurphy.ken.command.annotation.Requirement;
import net.tylermurphy.ken.database.ModerationTable; import net.tylermurphy.ken.database.ModerationTable;
import net.tylermurphy.ken.database.UserTable;
import net.tylermurphy.ken.util.Checks; import net.tylermurphy.ken.util.Checks;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
@ -36,21 +37,10 @@ public class TempBan {
String timeString = (String) args.get(1); String timeString = (String) args.get(1);
String reason = (String) args.get(2); String reason = (String) args.get(2);
boolean purge = (boolean) args.get(3); boolean purge = (boolean) args.get(3);
if(target == sender){
return Response.error("You are not allowed to do this to yourself"); try { Checks.hasPermission(sender, target); }
} catch (RuntimeException e) { return Response.error(e.getMessage()); }
Role low = Checks.getHighestRole(target);
Role high = Checks.getHighestRole(sender);
if(!Checks.getRolePermission(high, low)){
return Response.error("You need a higher role than the target");
}
Role self = Checks.getHighestRole(guild.getSelfMember());
if(!Checks.getRolePermission(self, low)){
return Response.error("I need a higher role than the target");
}
if(guild.getOwner() == target){
return Response.error("You cannot to this to the server owner");
}
try { try {
guild.retrieveBan(target).complete(); guild.retrieveBan(target).complete();
return Response.error("User is already banned from this server"); return Response.error("User is already banned from this server");
@ -62,10 +52,6 @@ public class TempBan {
SimpleDateFormat format = new SimpleDateFormat("MMM d, y h:ma zz"); SimpleDateFormat format = new SimpleDateFormat("MMM d, y h:ma zz");
String date = format.format(time); String date = format.format(time);
ModerationTable table = Ken.getInstance().getDatabase().getModerationTable();
String data = table.getData(guild.getIdLong(), target.getUser().getIdLong());
JSONObject json = table.updateData(data);
try { try {
guild.removeTimeout(target).queue(); guild.removeTimeout(target).queue();
} catch (Exception ignored){} } catch (Exception ignored){}
@ -76,19 +62,20 @@ public class TempBan {
return Response.error("Failed to temp ban user"); return Response.error("Failed to temp ban user");
} }
JSONObject status = json.getJSONObject("status"); ModerationTable table = Ken.getInstance().getDatabase().getModerationTable();
status.put("type", "temp-ban"); UserTable userTable = Ken.getInstance().getDatabase().getUserTable();
status.put("reason", reason); JSONObject json = table.getData(guild.getIdLong(), target.getUser().getIdLong());
status.put("until", time);
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()).put("by", sender.getIdLong())); history.put(new JSONObject()
json.put("history", history); .put("type", "tempban")
.put("reason", reason)
.put("date",new Date().getTime())
.put("by", sender.getIdLong())
.put("duration", time)
);
table.setData(guild.getIdLong(), target.getUser().getIdLong(), json.toString()); table.setData(guild.getIdLong(), target.getUser().getIdLong(), history, "tempban", time);
userTable.setData(target.getIdLong(), target.getUser().getName(), Integer.parseInt(target.getUser().getDiscriminator()));
Ken.getInstance().getDatabase().getUserTable().setData(target.getIdLong(), target.getUser().getName(), Integer.parseInt(target.getUser().getDiscriminator()));
PrivateChannel channel = target.getUser().openPrivateChannel().complete(); PrivateChannel channel = target.getUser().openPrivateChannel().complete();
if(channel != null){ if(channel != null){

View file

@ -11,6 +11,7 @@ import net.tylermurphy.ken.command.annotation.Command;
import net.tylermurphy.ken.command.annotation.Option; import net.tylermurphy.ken.command.annotation.Option;
import net.tylermurphy.ken.command.annotation.Requirement; import net.tylermurphy.ken.command.annotation.Requirement;
import net.tylermurphy.ken.database.ModerationTable; import net.tylermurphy.ken.database.ModerationTable;
import net.tylermurphy.ken.database.UserTable;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
@ -28,12 +29,11 @@ public class UnBan {
public Response execute(Member sender, Guild guild, List<Object> args){ public Response execute(Member sender, Guild guild, List<Object> args){
String username = (String) args.get(0); String username = (String) args.get(0);
String discriminator = String.valueOf(args.get(1)); String discriminator = String.valueOf(args.get(1));
String reason = (String) args.get(2);
if(discriminator.length() != 4) { if(discriminator.length() != 4) {
return Response.error("Invalid discriminator"); return Response.error("Invalid discriminator");
} }
String reason = (String) args.get(2);
User target = null; User target = null;
for(Guild.Ban ban : guild.retrieveBanList()){ for(Guild.Ban ban : guild.retrieveBanList()){
@ -58,29 +58,25 @@ public class UnBan {
return Response.error("User is not banned from this server"); return Response.error("User is not banned from this server");
} }
ModerationTable table = Ken.getInstance().getDatabase().getModerationTable();
String data = table.getData(guild.getIdLong(), target.getIdLong());
JSONObject json = table.updateData(data);
try { try {
guild.unban(target).queue(); guild.unban(target).queue();
} catch (Exception e){ } catch (Exception e){
return Response.error("Failed to unban user"); return Response.error("Failed to unban user");
} }
JSONObject status = json.getJSONObject("status"); ModerationTable table = Ken.getInstance().getDatabase().getModerationTable();
status.put("type", "None"); UserTable userTable = Ken.getInstance().getDatabase().getUserTable();
status.put("reason", ""); JSONObject json = table.getData(guild.getIdLong(), target.getIdLong());
status.put("until", 0L);
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()).put("by", sender.getIdLong())); history.put(new JSONObject()
json.put("history", history); .put("type", "unban")
.put("reason", reason)
.put("date",new Date().getTime())
.put("by", sender.getIdLong())
);
table.setData(guild.getIdLong(), target.getIdLong(), json.toString()); table.setData(guild.getIdLong(), target.getIdLong(), history, "None", 0L);
userTable.setData(target.getIdLong(), target.getName(), Integer.parseInt(target.getDiscriminator()));
Ken.getInstance().getDatabase().getUserTable().setData(target.getIdLong(), target.getName(), Integer.parseInt(target.getDiscriminator()));
PrivateChannel channel = target.openPrivateChannel().complete(); PrivateChannel channel = target.openPrivateChannel().complete();
if(channel != null){ if(channel != null){

View file

@ -10,6 +10,7 @@ import net.tylermurphy.ken.command.annotation.Command;
import net.tylermurphy.ken.command.annotation.Option; import net.tylermurphy.ken.command.annotation.Option;
import net.tylermurphy.ken.command.annotation.Requirement; import net.tylermurphy.ken.command.annotation.Requirement;
import net.tylermurphy.ken.database.ModerationTable; import net.tylermurphy.ken.database.ModerationTable;
import net.tylermurphy.ken.database.UserTable;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
@ -35,29 +36,25 @@ public class UnMute {
return Response.error("User is not muted"); return Response.error("User is not muted");
} }
ModerationTable table = Ken.getInstance().getDatabase().getModerationTable();
String data = table.getData(guild.getIdLong(), target.getIdLong());
JSONObject json = table.updateData(data);
try { try {
guild.removeTimeout(target).queue(); guild.removeTimeout(target).queue();
} catch (Exception e){ } catch (Exception e){
return Response.error("Failed to unmute user"); return Response.error("Failed to unmute user");
} }
JSONObject status = json.getJSONObject("status"); ModerationTable table = Ken.getInstance().getDatabase().getModerationTable();
status.put("type", "None"); UserTable userTable = Ken.getInstance().getDatabase().getUserTable();
status.put("reason", ""); JSONObject json = table.getData(guild.getIdLong(), target.getUser().getIdLong());
status.put("until", 0L);
json.put("status", status);
JSONArray history = json.getJSONArray("history"); JSONArray history = json.getJSONArray("history");
history.put(new JSONObject().put("type", "unmute").put("reason", reason).put("date",new Date().getTime()).put("by", sender.getIdLong())); history.put(new JSONObject()
json.put("history", history); .put("type", "unmute")
.put("reason", reason)
.put("date",new Date().getTime())
.put("by", sender.getIdLong())
);
table.setData(guild.getIdLong(), target.getIdLong(), json.toString()); table.setData(guild.getIdLong(), target.getUser().getIdLong(), history, "None", 0L);
userTable.setData(target.getIdLong(), target.getUser().getName(), Integer.parseInt(target.getUser().getDiscriminator()));
Ken.getInstance().getDatabase().getUserTable().setData(target.getIdLong(), target.getUser().getName(), Integer.parseInt(target.getUser().getDiscriminator()));
PrivateChannel channel = target.getUser().openPrivateChannel().complete(); PrivateChannel channel = target.getUser().openPrivateChannel().complete();
if(channel != null){ if(channel != null){

View file

@ -12,6 +12,7 @@ import net.tylermurphy.ken.command.annotation.Command;
import net.tylermurphy.ken.command.Response; import net.tylermurphy.ken.command.Response;
import net.tylermurphy.ken.music.GuildMusicManager; import net.tylermurphy.ken.music.GuildMusicManager;
import net.tylermurphy.ken.music.PlayerManager; import net.tylermurphy.ken.music.PlayerManager;
import net.tylermurphy.ken.util.Checks;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -35,13 +36,12 @@ public class Queue {
PlayerManager playerManager = Ken.getInstance().getPlayerManager(); PlayerManager playerManager = Ken.getInstance().getPlayerManager();
GuildMusicManager musicManager = playerManager.getGuildMusicManager(guild); GuildMusicManager musicManager = playerManager.getGuildMusicManager(guild);
BlockingQueue<AudioTrack> queue = musicManager.scheduler.getQueue(); BlockingQueue<AudioTrack> queue = musicManager.scheduler.getQueue();
int page;
try { Checks.hasPagedEmbed(message); }
catch (RuntimeException e) { return Response.error(e.getMessage()); }
int page = Integer.parseInt(message.getEmbeds().get(0).getFooter().getText().split("/")[0].substring(5));
int pages = (queue.size()-1)/10+1; int pages = (queue.size()-1)/10+1;
if (message != null && message.getEmbeds().size() > 0 && message.getEmbeds().get(0) != null) {
page = Integer.parseInt(message.getEmbeds().get(0).getFooter().getText().split("/")[0].substring(5));
} else {
page = 0;
}
if(id.equals("previous")) if(id.equals("previous"))
page = page - 1 < 1 ? pages : page - 1; page = page - 1 < 1 ? pages : page - 1;
else else

View file

@ -12,6 +12,7 @@ import net.tylermurphy.ken.command.Response;
import net.tylermurphy.ken.command.annotation.ButtonCallback; import net.tylermurphy.ken.command.annotation.ButtonCallback;
import net.tylermurphy.ken.command.annotation.Command; import net.tylermurphy.ken.command.annotation.Command;
import net.tylermurphy.ken.command.annotation.Option; import net.tylermurphy.ken.command.annotation.Option;
import net.tylermurphy.ken.util.Checks;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
@ -51,13 +52,13 @@ public class nHentai {
@ButtonCallback(name="nhentai") @ButtonCallback(name="nhentai")
public Response onButton(String button_id, Message message){ public Response onButton(String button_id, Message message){
int page, id;
if (message != null && message.getEmbeds().size() > 0 && message.getEmbeds().get(0) != null) { try { Checks.hasPagedEmbed(message); }
page = Integer.parseInt(message.getEmbeds().get(0).getFooter().getText().split("/")[0].substring(5)); catch (RuntimeException e) { return Response.error(e.getMessage()); }
id = Integer.parseInt(message.getEmbeds().get(0).getDescription().substring(4));
} else { int page = Integer.parseInt(message.getEmbeds().get(0).getFooter().getText().split("/")[0].substring(5));
return Response.error("Embed is missing, please resend command"); int id = Integer.parseInt(message.getEmbeds().get(0).getDescription().substring(4));
}
Comic comic = cache.get(id); Comic comic = cache.get(id);
if(comic == null) comic = request(id+""); if(comic == null) comic = request(id+"");
if(comic == null) return Response.error("Failed to fetch comic data"); if(comic == null) return Response.error("Failed to fetch comic data");

View file

@ -7,6 +7,7 @@ import net.tylermurphy.ken.command.Response;
import net.tylermurphy.ken.command.annotation.ButtonCallback; import net.tylermurphy.ken.command.annotation.ButtonCallback;
import net.tylermurphy.ken.command.annotation.Command; import net.tylermurphy.ken.command.annotation.Command;
import net.tylermurphy.ken.command.annotation.SelectMenuCallback; import net.tylermurphy.ken.command.annotation.SelectMenuCallback;
import net.tylermurphy.ken.util.Checks;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
@ -32,13 +33,11 @@ public class Roles {
@ButtonCallback(name="roles") @ButtonCallback(name="roles")
public Response onButton(Guild guild, String id, Message message){ public Response onButton(Guild guild, String id, Message message){
int page;
if(message == null) return Response.delete(); try { Checks.hasPagedEmbed(message); }
if (message.getEmbeds().size() > 0 && message.getEmbeds().get(0) != null) { catch (RuntimeException e) { return Response.error(e.getMessage()); }
page = Integer.parseInt(message.getEmbeds().get(0).getFooter().getText().split("/")[0].substring(5));
} else { int page = Integer.parseInt(message.getEmbeds().get(0).getFooter().getText().split("/")[0].substring(5));
page = 1;
}
int pages = Ken.getInstance().getDatabase().getSelfRoleData().getPages(guild.getIdLong()); int pages = Ken.getInstance().getDatabase().getSelfRoleData().getPages(guild.getIdLong());
if(id.equals("previous")) if(id.equals("previous"))
page = page - 1 < 1 ? pages : page - 1; page = page - 1 < 1 ? pages : page - 1;

View file

@ -19,7 +19,8 @@ public class ModerationTable {
CREATE TABLE IF NOT EXISTS moderation_data ( CREATE TABLE IF NOT EXISTS moderation_data (
guild_id BIGINT NOT NULL, guild_id BIGINT NOT NULL,
user_id BIGINT NOT NULL, user_id BIGINT NOT NULL,
data TEXT NOT NULL, history TEXT NOT NULL,
status VARCHAR(10) NOT NULL,
until BIGINT NOT NULL, until BIGINT NOT NULL,
PRIMARY KEY (guild_id,user_id) PRIMARY KEY (guild_id,user_id)
);"""; );""";
@ -33,27 +34,39 @@ public class ModerationTable {
this.database = database; this.database = database;
} }
public String getData(long guildId, long userId){ public JSONObject getData(long guildId, long userId){
String sql = "SELECT * FROM moderation_data WHERE guild_id=? AND user_id=?"; String sql = "SELECT * FROM moderation_data WHERE guild_id=? AND user_id=?";
try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(1, guildId); statement.setLong(1, guildId);
statement.setLong(2, userId); statement.setLong(2, userId);
ResultSet rs = statement.executeQuery(); ResultSet rs = statement.executeQuery();
if(rs.next()) return rs.getString("data"); if(rs.next()) {
else return null; JSONObject data = new JSONObject();
data.put("history", new JSONArray(rs.getString("history")));
data.put("status", rs.getString("status"));
data.put("until", rs.getLong("until"));
return data;
} else {
JSONObject data = new JSONObject();
data.put("history", new JSONArray());
data.put("status", "None");
data.put("until", 0L);
return data;
}
} catch (SQLException e) { } catch (SQLException e) {
Ken.getInstance().getLogger().error("SQL Error: " + e.getMessage()); Ken.getInstance().getLogger().error("SQL Error: " + e.getMessage());
return null; return null;
} }
} }
public boolean setData(long guildId, long userId, String data) { public boolean setData(long guildId, long userId, JSONArray history, String status, long until) {
String sql = "INSERT OR REPLACE INTO moderation_data (guild_id, user_id, data, until) VALUES(?,?,?,?)"; String sql = "INSERT OR REPLACE INTO moderation_data (guild_id, user_id, history, status, until) VALUES(?,?,?,?,?)";
try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) { try(Connection connection = database.connect(); PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(1, guildId); statement.setLong(1, guildId);
statement.setLong(2, userId); statement.setLong(2, userId);
statement.setString(3, data); statement.setString(3, history.toString());
statement.setLong(4, new JSONObject(data).getJSONObject("status").getLong("until")); statement.setString(4, status);
statement.setLong(5, until);
return statement.executeUpdate() != 0; return statement.executeUpdate() != 0;
} catch (SQLException e) { } catch (SQLException e) {
Ken.getInstance().getLogger().error("SQL Error: " + e.getMessage()); Ken.getInstance().getLogger().error("SQL Error: " + e.getMessage());
@ -68,7 +81,7 @@ public class ModerationTable {
statement.setLong(1, date); statement.setLong(1, date);
ResultSet rs = statement.executeQuery(); ResultSet rs = statement.executeQuery();
while (rs.next()){ while (rs.next()){
String[] data = {String.valueOf(rs.getLong("guild_id")), String.valueOf(rs.getLong("user_id")), rs.getString("data")}; String[] data = {String.valueOf(rs.getLong("guild_id")), String.valueOf(rs.getLong("user_id")), rs.getString("history"), rs.getString("status"), String.valueOf(rs.getLong("until"))};
store.add(data); store.add(data);
} }
} catch (SQLException e) { } catch (SQLException e) {
@ -77,12 +90,4 @@ public class ModerationTable {
store.forEach(callback); store.forEach(callback);
} }
public JSONObject updateData(String data) {
JSONObject object = data == null ? new JSONObject() : new JSONObject(data);
if(!object.has("history")) object.put("history", new JSONArray());
if(!object.has("roles")) object.put("roles", new JSONArray());
if(!object.has("status")) object.put("status", new JSONObject().put("type","None").put("until", 0L).put("reason",""));
return object;
}
} }

View file

@ -1,6 +1,8 @@
package net.tylermurphy.ken.util; package net.tylermurphy.ken.util;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.Role;
import java.util.Calendar; import java.util.Calendar;
@ -9,6 +11,28 @@ import java.util.List;
public class Checks { public class Checks {
public static void hasPagedEmbed(Message message) {
if(message == null || message.getEmbeds().size() < 1)
throw new RuntimeException("Message is missing");
MessageEmbed temp = message.getEmbeds().get(0);
if(temp == null || temp.getDescription() == null || temp.getFooter() == null)
throw new RuntimeException("Embed is missing");
}
public static void hasPermission(Member sender, Member target) {
if(sender == target)
throw new RuntimeException("You are not allowed to do this to yourself");
Role low = Checks.getHighestRole(target);
Role high = Checks.getHighestRole(sender);
Role self = Checks.getHighestRole(sender.getGuild().getSelfMember());
if(!Checks.getRolePermission(high, low))
throw new RuntimeException("You need a higher role than the target");
if(!Checks.getRolePermission(self, low))
throw new RuntimeException("I need a higher role than the target");
if(sender.getGuild().getOwner() == target)
throw new RuntimeException("You cannot to this to the server owner");
}
public static Role getHighestRole(Member member) { public static Role getHighestRole(Member member) {
if(member == null) { if(member == null) {
return null; return null;

View file

@ -24,10 +24,10 @@ public class ModerationChecker {
Ken.getInstance().getDatabase().getModerationTable().callOverdue(new Date().getTime(), data -> { Ken.getInstance().getDatabase().getModerationTable().callOverdue(new Date().getTime(), data -> {
long guildId = Long.parseLong(data[0]); long guildId = Long.parseLong(data[0]);
long userId = Long.parseLong(data[1]); long userId = Long.parseLong(data[1]);
JSONObject json = new JSONObject(data[2]); JSONArray history = new JSONArray(data[2]);
JSONObject status = json.getJSONObject("status"); String status = data[3];
String type = status.getString("type"); long until = Long.parseLong(data[4]);
if(!type.equals("temp-ban")) return; if(!status.equals("tempban")) return;
Guild guild = Ken.getInstance().getGuildById(guildId); Guild guild = Ken.getInstance().getGuildById(guildId);
if(guild == null) return; if(guild == null) return;
List<Guild.Ban> bans = guild.retrieveBanList().complete(); List<Guild.Ban> bans = guild.retrieveBanList().complete();
@ -46,15 +46,8 @@ public class ModerationChecker {
.appendDescription("`Reason:` Ban period ended"); .appendDescription("`Reason:` Ban period ended");
channel.sendMessageEmbeds(builder.build()).queue(); channel.sendMessageEmbeds(builder.build()).queue();
} }
status.put("type", "None");
status.put("reason", "");
status.put("until", 0L);
JSONArray history = json.getJSONArray("history");
history.put(new JSONObject().put("type", "unban").put("reason", "Ban Period Ended").put("date",new Date().getTime()).put("by", guild.getSelfMember().getIdLong())); history.put(new JSONObject().put("type", "unban").put("reason", "Ban Period Ended").put("date",new Date().getTime()).put("by", guild.getSelfMember().getIdLong()));
json.put("history", history); Ken.getInstance().getDatabase().getModerationTable().setData(guildId, userId, history, "None", 0L);
json.put("status", status);
Ken.getInstance().getDatabase().getModerationTable().setData(guildId, userId, json.toString());
} catch (ErrorResponseException ignored) {} } catch (ErrorResponseException ignored) {}
}); });
} }