Compare commits

..

4 Commits

Author SHA1 Message Date
2b29cd535b Make addCommand method accessible to inherited classes 2022-06-22 22:08:03 -04:00
07db7b7abd Slight bug fixes with module loading 2022-06-22 00:56:00 -04:00
41c1d28bcc Modules! 2022-06-22 00:19:46 -04:00
716c6c139b Stuff 2022-05-25 22:31:29 -04:00
35 changed files with 834 additions and 170 deletions

View File

@@ -0,0 +1,8 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="AutoCloseableResource" enabled="true" level="WARNING" enabled_by_default="true">
<option name="METHOD_MATCHER_CONFIG" value="java.util.Formatter,format,java.io.Writer,append,com.google.common.base.Preconditions,checkNotNull,org.hibernate.Session,close,java.io.PrintWriter,printf,java.io.PrintStream,printf,java.net.URLClassLoader,newInstance" />
</inspection_tool>
</profile>
</component>

5
.idea/misc.xml generated
View File

@@ -7,9 +7,4 @@
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK"> <component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" /> <output url="file://$PROJECT_DIR$/out" />
</component> </component>
<component name="SwUserDefinedSpecifications">
<option name="specTypeByUrl">
<map />
</option>
</component>
</project> </project>

View File

@@ -1,13 +1,14 @@
plugins { plugins {
id 'java' id 'java'
id 'application' id 'application'
id 'maven-publish'
id 'com.github.johnrengelman.shadow' version '5.2.0' id 'com.github.johnrengelman.shadow' version '5.2.0'
} }
mainClassName = 'net.nevet5gi.buzzbot.Bot' mainClassName = 'net.nevet5gi.buzzbot.Bot'
group 'net.nevet5gi' group 'net.nevet5gi'
version '0.3.0' version '0.5.2'
sourceCompatibility = JavaVersion.VERSION_17 sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17
@@ -29,7 +30,7 @@ repositories {
dependencies { dependencies {
implementation 'net.dv8tion:JDA:4.4.0_350' implementation 'net.dv8tion:JDA:4.4.0_350'
implementation 'ch.qos.logback:logback-classic:1.2.11' implementation 'ch.qos.logback:logback-classic:1.2.11'
implementation 'me.duncte123:botCommons:2.3.8' //implementation 'me.duncte123:botCommons:2.3.8'
implementation 'com.google.code.gson:gson:2.9.0' implementation 'com.google.code.gson:gson:2.9.0'
implementation 'me.carleslc.Simple-YAML:Simple-Yaml:1.7.2' implementation 'me.carleslc.Simple-YAML:Simple-Yaml:1.7.2'
implementation 'mysql:mysql-connector-java:8.0.29' implementation 'mysql:mysql-connector-java:8.0.29'
@@ -37,3 +38,24 @@ dependencies {
} }
compileJava.options.encoding = 'UTF-8' compileJava.options.encoding = 'UTF-8'
apply plugin: 'maven-publish'
publishing {
publications{
publish(MavenPublication) {
artifact("nexus/BuzzBot-$version" + ".jar") {
extension 'jar'
}
}
}
repositories {
maven {
name 'nexus'
url "https://repo.nevets.tech/repository/maven-releases/"
credentials {
username System.getenv('nexusUser')
password System.getenv('nexusPass')
}
}
}
}

View File

@@ -3,32 +3,56 @@ package net.nevet5gi.buzzbot;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity; import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.utils.cache.CacheFlag; import net.dv8tion.jda.api.utils.cache.CacheFlag;
import net.nevet5gi.buzzbot.commands.utils.CommandManager; import net.nevet5gi.buzzbot.commands.utils.CommandManager;
import net.nevet5gi.buzzbot.modules.BuzzyModule;
import net.nevet5gi.buzzbot.modules.ModuleLoader;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.security.auth.login.LoginException; import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.EnumSet; import java.util.EnumSet;
public class Bot { public class BuzzBot {
//TODO Make shutdown sequence
public static JDA jda; public static JDA jda;
private static final Logger LOGGER = LoggerFactory.getLogger(Bot.class); private static final Logger LOGGER = LoggerFactory.getLogger(BuzzBot.class);
public static final ArrayList<ListenerAdapter> PLUGIN_LISTENERS = new ArrayList<>();
private static ArrayList<BuzzyModule> modules;
public static void main(String[] args) { public static void main(String[] args) {
Config.loadConfig(); Config.loadConfig();
try {
modules = ModuleLoader.loadModules();
} catch (IOException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
System.out.println("Have fun with this stack trace ;)");
e.printStackTrace();
modules = new ArrayList<>();
}
try { try {
jda = JDABuilder.createDefault(Config.getConfig().getString("bot.token")) JDABuilder builder = JDABuilder.createDefault(Config.getConfig().getString("bot.token"))
.disableCache(EnumSet.of( .disableCache(EnumSet.of(
CacheFlag.CLIENT_STATUS, CacheFlag.CLIENT_STATUS,
CacheFlag.ACTIVITY, CacheFlag.ACTIVITY,
CacheFlag.EMOTE CacheFlag.EMOTE
)) ))
.enableCache(CacheFlag.VOICE_STATE) .enableCache(CacheFlag.VOICE_STATE);
.addEventListeners(new Listener())
.build(); for (ListenerAdapter listener : PLUGIN_LISTENERS) {
builder.addEventListeners(listener);
}
jda = builder.build();
CommandManager.registerSlashCommands(); CommandManager.registerSlashCommands();
for (BuzzyModule module : modules) {
module.onEnable(jda);
}
getActivity(); getActivity();
LOGGER.info("BuzzBot finished loading!"); LOGGER.info("BuzzBot finished loading!");
} catch (LoginException e) { } catch (LoginException e) {
@@ -53,5 +77,9 @@ public class Bot {
jda.getPresence().setActivity(Activity.playing("with myself!")); jda.getPresence().setActivity(Activity.playing("with myself!"));
} }
} }
public static void addListener(ListenerAdapter listener) {
PLUGIN_LISTENERS.add(listener);
}
} }

View File

@@ -1,5 +0,0 @@
package net.nevet5gi.buzzbot;
public class Group {
}

View File

@@ -2,6 +2,7 @@ package net.nevet5gi.buzzbot;
import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.ReadyEvent; import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.events.guild.GuildJoinEvent;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageUpdateEvent; import net.dv8tion.jda.api.events.message.guild.GuildMessageUpdateEvent;
@@ -9,6 +10,7 @@ import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.nevet5gi.buzzbot.commands.utils.CommandManager; import net.nevet5gi.buzzbot.commands.utils.CommandManager;
import net.nevet5gi.buzzbot.database.SqlDB; import net.nevet5gi.buzzbot.database.SqlDB;
import net.nevet5gi.buzzbot.functions.ProfanityFilter; import net.nevet5gi.buzzbot.functions.ProfanityFilter;
import net.nevet5gi.buzzbot.objects.GuildData;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -29,6 +31,19 @@ public class Listener extends ListenerAdapter {
LOGGER.info("BuzzBot is ready: " + event.getJDA().getSelfUser().getAsTag()); LOGGER.info("BuzzBot is ready: " + event.getJDA().getSelfUser().getAsTag());
} }
@Override
public void onGuildJoin(@Nonnull GuildJoinEvent event) {
GuildData guild = new GuildData();
guild.setName(event.getGuild().getName());
guild.setId(event.getGuild().getIdLong());
guild.setGroup("master");
guild.setProfanityLevel(0);
SqlDB sql = new SqlDB();
sql.addGuild(guild);
sql.close();
}
@Override @Override
public void onGuildMessageReceived(@Nonnull GuildMessageReceivedEvent event) { public void onGuildMessageReceived(@Nonnull GuildMessageReceivedEvent event) {
User user = event.getAuthor(); User user = event.getAuthor();
@@ -41,14 +56,16 @@ public class Listener extends ListenerAdapter {
if (profanityFilter.containsProfanity(raw, "strong")) { if (profanityFilter.containsProfanity(raw, "strong")) {
SqlDB sql = new SqlDB(); SqlDB sql = new SqlDB();
int profanityLevel = sql.getGuildData(event.getGuild().getIdLong()).getProfanityLevel(); int profanityLevel = sql.getGuildData(event.getGuild().getIdLong()).getProfanityLevel();
sql.close();
switch (profanityLevel) { switch (profanityLevel) {
case 1: case 1 -> {
if (profanityFilter.containsProfanity(raw, "mild")) profanityFilter.handle(event); if (profanityFilter.containsProfanity(raw, "mild")) profanityFilter.handle(event);
case 2: }
case 2 -> {
if (profanityFilter.containsProfanity(raw, "moderate")) profanityFilter.handle(event); if (profanityFilter.containsProfanity(raw, "moderate")) profanityFilter.handle(event);
case 3: }
profanityFilter.handle(event); case 3 -> profanityFilter.handle(event);
} }
} }
@@ -64,14 +81,18 @@ public class Listener extends ListenerAdapter {
if (profanityFilter.containsProfanity(raw, "strong")) { if (profanityFilter.containsProfanity(raw, "strong")) {
SqlDB sql = new SqlDB(); SqlDB sql = new SqlDB();
int profanityLevel = sql.getGuildData(event.getGuild().getIdLong()).getProfanityLevel(); int profanityLevel = sql.getGuildData(event.getGuild().getIdLong()).getProfanityLevel();
sql.close();
switch (profanityLevel) { switch (profanityLevel) {
case 1: case 1:
if (profanityFilter.containsProfanity(raw, "mild")) profanityFilter.handleEdit(event); if (profanityFilter.containsProfanity(raw, "mild")) profanityFilter.handleEdit(event);
break;
case 2: case 2:
if (profanityFilter.containsProfanity(raw, "moderate")) profanityFilter.handleEdit(event); if (profanityFilter.containsProfanity(raw, "moderate")) profanityFilter.handleEdit(event);
break;
case 3: case 3:
profanityFilter.handleEdit(event); profanityFilter.handleEdit(event);
break;
} }
} }
} }

View File

@@ -4,8 +4,8 @@ import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.utils.cache.CacheFlag; import net.dv8tion.jda.api.utils.cache.CacheFlag;
import net.nevet5gi.buzzbot.database.SqlDB; import net.nevet5gi.buzzbot.database.SqlDB;
import net.nevet5gi.buzzbot.modules.ModuleLoader;
import net.nevet5gi.buzzbot.objects.BanData; import net.nevet5gi.buzzbot.objects.BanData;
import net.nevet5gi.buzzbot.objects.GuildData;
import javax.security.auth.login.LoginException; import javax.security.auth.login.LoginException;
import java.sql.Date; import java.sql.Date;
@@ -17,11 +17,28 @@ import java.util.EnumSet;
public class Test { public class Test {
private static JDA jda; private static JDA jda;
public static void main(String[] args) { public static void main(String[] args) {
Config.loadConfig(); Config.loadConfig();
initJda(); //initJda();
jda.retrieveUserById(712116155388526693L).queue(user -> { System.out.println(Integer.parseInt(user.getDiscriminator())); }); ModuleLoader.getModules();
// String role = "helper_id";
// String roleId = "234098234";
// String guildId = "34958735345345345";
//
// String sql = "UPDATE guild_settings SET " + role + " = " + roleId + " WHERE guild_id = " + guildId;
//
// System.out.println(sql);
//GuildData guild = new GuildData();
//guild.setName("Certified Tater");
//guild.setId(948704397569958038L);
//guild.setGroup("developer");
//guild.setProfanityLevel(0);
//SqlDB sql = new SqlDB();
//sql.addGuild(guild);
//sqlTest(); //sqlTest();
} }
@@ -45,14 +62,15 @@ public class Test {
private static void sqlTest() { private static void sqlTest() {
SqlDB db = new SqlDB(); SqlDB db = new SqlDB();
BanData ban = new BanData(972924565361695745L, "nevetS", Date.valueOf(LocalDate.now()), Time.valueOf(LocalTime.now()), true, 0, "Reason", "test3", 865368792980914186L, "DevHQ", 824071914673668138L); BanData ban = new BanData(972924565361695745L, "nevetS", Date.valueOf(LocalDate.now()), Time.valueOf(LocalTime.now()), "reason", true, 0, "test3", 865368792980914186L, "DevHQ", 824071914673668138L);
db.insertBan(ban, "masterbanlist"); db.insertBan(ban, "masterbanlist");
db.close();
SqlDB db2 = new SqlDB(); SqlDB db2 = new SqlDB();
BanData qban = db2.queryBan(972924565361695745L, "masterbanlist"); BanData qban = db2.queryBan(972924565361695745L, "masterbanlist");
db2.close();
System.out.println(qban.getUserName()); System.out.println(qban.getUserName());
System.out.println(qban.getDate()); System.out.println(qban.getDate());
System.out.println(qban.getBanReason());
} }
} }

View File

@@ -1,6 +1,6 @@
package net.nevet5gi.buzzbot.commands; package net.nevet5gi.buzzbot.commands;
import net.nevet5gi.buzzbot.Bot; import net.nevet5gi.buzzbot.BuzzBot;
import net.nevet5gi.buzzbot.commands.utils.CommandContext; import net.nevet5gi.buzzbot.commands.utils.CommandContext;
import net.nevet5gi.buzzbot.commands.utils.ICommand; import net.nevet5gi.buzzbot.commands.utils.ICommand;
import net.nevet5gi.buzzbot.database.SqlDB; import net.nevet5gi.buzzbot.database.SqlDB;
@@ -61,22 +61,23 @@ public class BanCmd implements ICommand {
sb.append(" "); sb.append(" ");
} }
} }
ban.setBanReason(sb.toString().trim()); ban.setReason(sb.toString().trim());
if (ban.getBanLength() == 0) { if (ban.getBanLength() == 0) {
ctx.getChannel().sendMessage("<@" + ctx.getMessage().getAuthor().getId() + "> permanently banned <@" + ban.getUserId() + ">. Reason: " + ban.getBanReason()).queue(); ctx.getChannel().sendMessage("<@" + ctx.getMessage().getAuthor().getId() + "> permanently banned <@" + ban.getUserId() + ">. Reason: " + ban.getReason()).queue();
} else { } else {
ctx.getChannel().sendMessage("<@" + ctx.getMessage().getAuthor().getId() + "> banned <@" + ban.getUserId() + "> for " + ban.getBanLength() + " hours. Reason: " + ban.getBanReason()).queue(); ctx.getChannel().sendMessage("<@" + ctx.getMessage().getAuthor().getId() + "> banned <@" + ban.getUserId() + "> for " + ban.getBanLength() + " hours. Reason: " + ban.getReason()).queue();
} }
Bot.jda.retrieveUserById(ban.getUserId()).queue(user -> { ban.setUserName(user.getName()); }); BuzzBot.jda.retrieveUserById(ban.getUserId()).queue(user -> { ban.setUserName(user.getName()); });
ban.setModId(ctx.getMessage().getAuthor().getIdLong()); ban.setModId(ctx.getMessage().getAuthor().getIdLong());
ban.setModName(ctx.getMessage().getAuthor().getName()); ban.setModName(ctx.getMessage().getAuthor().getName());
ban.setServerId(ctx.getGuild().getIdLong()); ban.setServerId(ctx.getGuild().getIdLong());
ban.setServerName(ctx.getGuild().getName()); ban.setServerName(ctx.getGuild().getName());
SqlDB db = new SqlDB(); SqlDB sql = new SqlDB();
db.insertBan(ban, "master_ban_list"); sql.insertBan(ban, "master_ban_record");
sql.close();
//ctx.getEvent().getGuild().ban(cmdf, 1 , "").submit(); //ctx.getEvent().getGuild().ban(cmdf, 1 , "").submit();
//ctx.getMessage().reply("yes ban"); //ctx.getMessage().reply("yes ban");
@@ -87,6 +88,11 @@ public class BanCmd implements ICommand {
return "ban"; return "ban";
} }
@Override
public int getPermissionLevel() {
return 3;
}
@Override @Override
public String getHelp() { public String getHelp() {
return "Bans the specified user"; return "Bans the specified user";

View File

@@ -2,12 +2,13 @@ package net.nevet5gi.buzzbot.commands;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.nevet5gi.buzzbot.Config; import net.nevet5gi.buzzbot.Config;
import net.nevet5gi.buzzbot.commands.utils.CommandContext; import net.nevet5gi.buzzbot.commands.utils.CommandContext;
import net.nevet5gi.buzzbot.commands.utils.ICommand; import net.nevet5gi.buzzbot.commands.utils.ICommand;
import net.nevet5gi.buzzbot.commands.utils.ISlashCommand;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
@@ -15,26 +16,25 @@ import java.net.http.HttpClient;
import java.net.http.HttpRequest; import java.net.http.HttpRequest;
import java.net.http.HttpResponse; import java.net.http.HttpResponse;
public class PandaCmd implements ICommand { public class BeeCmd implements ICommand, ISlashCommand {
public static String url; public static String url;
@Override @Override
public void handle(CommandContext ctx) { public void handle(CommandContext ctx) {
try { getHttpConnection(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } try { getHttpConnection(); } catch (IOException | InterruptedException e) { e.printStackTrace(); }
EmbedBuilder eb = new EmbedBuilder(); EmbedBuilder eb = new EmbedBuilder();
ctx.getChannel().sendTyping().queue();
eb.setImage(url.replace("\"","")); eb.setImage(url.replace("\"",""));
ctx.getChannel().sendMessageEmbeds(eb.build()).queue(); ctx.getChannel().sendMessageEmbeds(eb.build()).queue();
} }
@Override @Override
public String getName() { public String getName() {
return "panda"; return "bee";
} }
@Override @Override
public String getHelp() { public String getHelp() {
return "Sends a picture of a panda!\n" + return "Sends a picture of a bee!\n" +
"Usage: `" + Config.getConfig().getString("bot.prefix") + "panda`"; "Usage: `" + Config.getConfig().getString("bot.prefix") + "bee`";
} }
public static void getHttpConnection() throws IOException, InterruptedException { public static void getHttpConnection() throws IOException, InterruptedException {
@@ -42,23 +42,36 @@ public class PandaCmd implements ICommand {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.GET() .GET()
.header("accept", "application/json") .header("accept", "application/json")
.uri(URI.create("https://some-random-api.ml/img/panda")) .uri(URI.create("https://api.nevets.tech/bee"))
.build(); .build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString()) client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body) .thenApply(HttpResponse::body)
.thenApply(PandaCmd::parse) .thenApply(BeeCmd::parse)
.join(); .join();
} }
public static String parse(String response) { public static String parse(String response) {
String mod = "[ " + response + " ]"; JsonElement je = new Gson().fromJson(response, JsonElement.class);
JsonArray ja = new Gson().fromJson(mod, JsonArray.class); url = je.getAsJsonObject().get("link").toString();
for (int i = 0; i < ja.getAsJsonArray().size(); i++) {
JsonElement jo = ja.get(i);
url = jo.getAsJsonObject().get("link").toString();
}
return null; return null;
} }
@Override
public void handleSlash(CommandContext ctx) {
try { getHttpConnection(); } catch (IOException | InterruptedException e) { e.printStackTrace(); }
EmbedBuilder eb = new EmbedBuilder();
eb.setImage(url.replace("\"",""));
ctx.getHook().sendMessageEmbeds(eb.build()).queue();
}
@Override
public String getDescription() {
return "Responds with a picture of a bee!";
}
@Override
public CommandData getCommandData() {
return new CommandData(this.getName(), this.getDescription());
}
} }

View File

@@ -2,13 +2,16 @@ package net.nevet5gi.buzzbot.commands;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.interactions.commands.Command;
import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.nevet5gi.buzzbot.Config; import net.nevet5gi.buzzbot.Config;
import net.nevet5gi.buzzbot.commands.utils.*; import net.nevet5gi.buzzbot.commands.utils.*;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public class HelpCmd implements ICommand, ISlashCommand { public class HelpCmd implements ICommand, ISlashCommand {
@@ -106,9 +109,21 @@ public class HelpCmd implements ICommand, ISlashCommand {
@Override @Override
public @NotNull CommandData getCommandData() { public @NotNull CommandData getCommandData() {
List<Command.Choice> choices = new ArrayList<>();
for (ICommand cmd : manager.getCommands()) {
choices.add(new Command.Choice(cmd.getName(), cmd.getName()));
}
for (ISlashCommand cmd : manager.getSlashCommands()) {
choices.add(new Command.Choice(cmd.getName(), cmd.getName()));
}
OptionData option = new OptionData(OptionType.STRING, "command", "Gives info on specified command", false);
option.addChoices(choices);
return new CommandData(this.getName(), this.getDescription()) return new CommandData(this.getName(), this.getDescription())
.addOption(OptionType.STRING, "command", "Gives info on this command", false); .addOptions(option);
} }
@Override @Override

View File

@@ -14,6 +14,11 @@ public class MuteCmd implements ICommand {
return "mute"; return "mute";
} }
@Override
public int getPermissionLevel() {
return 2;
}
@Override @Override
public String getHelp() { public String getHelp() {
return "Mutes the specified user"; return "Mutes the specified user";

View File

@@ -1,17 +1,18 @@
package net.nevet5gi.buzzbot.commands; package net.nevet5gi.buzzbot.commands;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.nevet5gi.buzzbot.BuzzBot;
import net.nevet5gi.buzzbot.Config; import net.nevet5gi.buzzbot.Config;
import net.nevet5gi.buzzbot.commands.utils.CommandContext; import net.nevet5gi.buzzbot.commands.utils.CommandContext;
import net.nevet5gi.buzzbot.commands.utils.ICommand; import net.nevet5gi.buzzbot.commands.utils.ICommand;
import net.nevet5gi.buzzbot.commands.utils.ISlashCommand;
public class PingCmd implements ICommand { public class PingCmd implements ICommand, ISlashCommand {
@Override @Override
public void handle(CommandContext ctx) { public void handle(CommandContext ctx) {
JDA jda = ctx.getJDA(); JDA jda = ctx.getJDA();
jda.getRestPing().queue((ping) -> ctx.getChannel().sendMessageFormat("Rest API Ping: %sms\nWebSocket Ping: %sms", ping, jda.getGatewayPing()).queue()); jda.getRestPing().queue((ping) -> ctx.getChannel().sendMessageFormat("Rest API Ping: %sms\nWebSocket Ping: %sms", ping, jda.getGatewayPing()).queue());
} }
@Override @Override
@@ -24,4 +25,20 @@ public class PingCmd implements ICommand {
public String getName() { public String getName() {
return "ping"; return "ping";
} }
@Override
public void handleSlash(CommandContext ctx) {
JDA jda = BuzzBot.jda;
jda.getRestPing().queue(ping -> ctx.getHook().sendMessageFormat("Rest API Ping: %sms\nWebSocket Ping: %sms", ping, jda.getGatewayPing()).queue());
}
@Override
public String getDescription() {
return "Shows the current ping from the bot to API";
}
@Override
public CommandData getCommandData() {
return new CommandData(this.getName(), this.getDescription());
}
} }

View File

@@ -0,0 +1,60 @@
package net.nevet5gi.buzzbot.commands;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.nevet5gi.buzzbot.commands.utils.CommandContext;
import net.nevet5gi.buzzbot.commands.utils.ISlashCommand;
import net.nevet5gi.buzzbot.database.SqlDB;
import net.nevet5gi.buzzbot.objects.ModRoles;
import java.util.ArrayList;
import java.util.List;
public class SetRoleCmd implements ISlashCommand {
@Override
public String getName() {
return "setrole";
}
@Override
public int getPermissionLevel() {
return 4;
}
@Override
public String getHelp() {
return "Sets the role id for the moderation roles";
}
@Override
public void handleSlash(CommandContext ctx) {
SqlDB sql = new SqlDB();
sql.updateGuildRole(ctx.getGuild().getIdLong(), ctx.getSlashEvent().getOption("role").getAsString(), ctx.getSlashEvent().getOption("guild_role").getAsRole().getIdLong());
sql.close();
ctx.getHook().sendMessage("Assigned role <@&" + ctx.getSlashEvent().getOption("guild_role").getAsRole().getId() + "> to " + ctx.getSlashEvent().getOption("role").getAsString()).queue();
}
@Override
public String getDescription() {
return this.getHelp();
}
@Override
public CommandData getCommandData() {
List<OptionData> options = new ArrayList<>();
OptionData role = new OptionData(OptionType.STRING, "role", "Role assigned to moderation roles", true);
role.addChoice("helper", ModRoles.HELPER.getRole());
role.addChoice("moderator", ModRoles.MODERATOR.getRole());
role.addChoice("administrator", ModRoles.ADMINISTRATOR.getRole());
role.addChoice("owner", ModRoles.OWNER.getRole());
options.add(role);
OptionData guildRole = new OptionData(OptionType.ROLE, "guild_role", "Mentioned role to assign", true);
options.add(guildRole);
return new CommandData(this.getName(), this.getDescription())
.addOptions(options);
}
}

View File

@@ -18,22 +18,23 @@ public class TestCmd implements ICommand, ISlashCommand {
long number = ctx.getSlashEvent().getOption("number").getAsLong(); long number = ctx.getSlashEvent().getOption("number").getAsLong();
IMentionable member = ctx.getSlashEvent().getOption("mention").getAsMentionable(); IMentionable member = ctx.getSlashEvent().getOption("mention").getAsMentionable();
boolean testBoolean = ctx.getSlashEvent().getOption("boolean").getAsBoolean(); boolean testBoolean = ctx.getSlashEvent().getOption("boolean").getAsBoolean();
String commandString = ctx.getSlashEvent().getCommandString();
String content = "number: " + number + ", mention: " + member.getAsMention() + ", boolean: " + testBoolean; String content = "number: " + number + ", mention: " + member.getAsMention() + ", boolean: " + testBoolean + ", command string: " + commandString;
ctx.getSlashEvent().getHook().sendMessage(content).queue(); ctx.getHook().sendMessage(content).queue();
} }
@Override @Override
public String getDescription() { public String getDescription() {
return "Checks the piung between bot and API"; return "Checks the ping between bot and API";
} }
@Override @Override
public CommandData getCommandData() { public CommandData getCommandData() {
return new CommandData(this.getName(), this.getDescription()) return new CommandData(this.getName(), this.getDescription())
.addOption(OptionType.INTEGER, "number", "test number", true) .addOption(OptionType.INTEGER, "number", "test number", true)
.addOption(OptionType.MENTIONABLE, "mention", "mentioned member or role", true) .addOption(OptionType.USER, "mention", "mentioned member or role", true)
.addOption(OptionType.BOOLEAN, "boolean", "test boolean", true); .addOption(OptionType.BOOLEAN, "boolean", "test boolean", true);
} }

View File

@@ -2,11 +2,31 @@ package net.nevet5gi.buzzbot.commands;
import net.nevet5gi.buzzbot.commands.utils.CommandContext; import net.nevet5gi.buzzbot.commands.utils.CommandContext;
import net.nevet5gi.buzzbot.commands.utils.ICommand; import net.nevet5gi.buzzbot.commands.utils.ICommand;
import net.nevet5gi.buzzbot.database.SqlDB;
import net.nevet5gi.buzzbot.util.GuildUtils;
import java.util.List;
public class UnbanCmd implements ICommand { public class UnbanCmd implements ICommand {
@Override @Override
public void handle(CommandContext ctx) { public void handle(CommandContext ctx) {
ctx.getMessage().reply("This command doesn't work yet").queue(); // Somehow keep track of bans
// Make sure a user can only be unbanned from the guild they were banned from
List<String> args = ctx.getArgs();
long userId;
if (args.get(0).contains("<@")) {
userId = Long.parseLong(args.get(0).replace("<","").replace("@","").replace("&","").replace(">",""));
} else {
userId = Long.parseLong(args.get(0));
}
SqlDB sql = new SqlDB();
sql.queryBan(userId, GuildUtils.getTable(ctx.getGuild()));
sql.close();
ctx.getGuild().getIdLong();
} }
@Override @Override
@@ -14,6 +34,11 @@ public class UnbanCmd implements ICommand {
return "unban"; return "unban";
} }
@Override
public int getPermissionLevel() {
return 3;
}
@Override @Override
public String getHelp() { public String getHelp() {
return "Unbans the specified user"; return "Unbans the specified user";

View File

@@ -14,6 +14,11 @@ public class UnmuteCmd implements ICommand {
return "unmute"; return "unmute";
} }
@Override
public int getPermissionLevel() {
return 2;
}
@Override @Override
public String getHelp() { public String getHelp() {
return "Unmutes the specified user"; return "Unmutes the specified user";

View File

@@ -15,6 +15,11 @@ public class UnwarnCmd implements ICommand {
return "unwarn"; return "unwarn";
} }
@Override
public int getPermissionLevel() {
return 2;
}
@Override @Override
public String getHelp() { public String getHelp() {
return "Unwarns the specified user"; return "Unwarns the specified user";

View File

@@ -1,19 +1,51 @@
package net.nevet5gi.buzzbot.commands; package net.nevet5gi.buzzbot.commands;
import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.nevet5gi.buzzbot.BuzzBot;
import net.nevet5gi.buzzbot.commands.utils.CommandContext; import net.nevet5gi.buzzbot.commands.utils.CommandContext;
import net.nevet5gi.buzzbot.commands.utils.ICommand; import net.nevet5gi.buzzbot.commands.utils.ICommand;
import net.nevet5gi.buzzbot.commands.utils.ISlashCommand; import net.nevet5gi.buzzbot.database.SqlDB;
import net.nevet5gi.buzzbot.objects.WarnData;
public class WarnCmd implements ICommand, ISlashCommand { import java.util.List;
public class WarnCmd implements ICommand {
@Override @Override
public void handle(CommandContext ctx) { public void handle(CommandContext ctx) {
ctx.getMessage().reply("This command has not been implemented yet").queue(); List<String> args = ctx.getArgs();
if (args.size() < 2) {
ctx.getChannel().sendMessage("Not enough arguments, please try again").queue();
return;
} }
@Override WarnData warn = new WarnData();
public void handleSlash(CommandContext ctx) {
ctx.getSlashEvent().getHook().sendMessage("This command has not been implemented yet").queue(); if (args.get(0).contains("<@")) {
warn.setUserId(Long.parseLong(args.get(0).replace("<","").replace("@","").replace("&","").replace(">","")));
} else {
warn.setUserId(Long.parseLong(args.get(0)));
}
StringBuilder sb = new StringBuilder();
if (args.size() >= 1) {
for (int i = 1; i < args.size(); i++) {
sb.append(args.get(i));
sb.append(" ");
}
}
warn.setReason(sb.toString().trim());
ctx.getChannel().sendMessage("<@" + ctx.getMessage().getAuthor().getId() + "> warned <@" + warn.getUserId() + "> for reason: " + warn.getReason()).queue();
BuzzBot.jda.retrieveUserById(warn.getUserId()).queue(user -> { warn.setUserName(user.getName()); });
warn.setModId(ctx.getMessage().getAuthor().getIdLong());
warn.setModName(ctx.getMessage().getAuthor().getName());
warn.setServerId(ctx.getGuild().getIdLong());
warn.setServerName(ctx.getGuild().getName());
SqlDB sql = new SqlDB();
sql.insertWarn(warn, "master_warn_record");
sql.close();
} }
@Override @Override
@@ -22,13 +54,8 @@ public class WarnCmd implements ICommand, ISlashCommand {
} }
@Override @Override
public String getDescription() { public int getPermissionLevel() {
return "Warns specified user"; return 2;
}
@Override
public CommandData getCommandData() {
return new CommandData(this.getName(), this.getDescription());
} }
@Override @Override

View File

@@ -1,6 +1,5 @@
package net.nevet5gi.buzzbot.commands.utils; package net.nevet5gi.buzzbot.commands.utils;
import me.duncte123.botcommons.commands.ICommandContext;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
@@ -26,6 +25,7 @@ public class CommandContext implements ICommandContext {
return this.event; return this.event;
} }
@Override
public SlashCommandEvent getSlashEvent() { public SlashCommandEvent getSlashEvent() {
return this.slashEvent; return this.slashEvent;
} }

View File

@@ -1,11 +1,15 @@
package net.nevet5gi.buzzbot.commands.utils; package net.nevet5gi.buzzbot.commands.utils;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.interactions.commands.build.CommandData; import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.nevet5gi.buzzbot.Bot; import net.nevet5gi.buzzbot.BuzzBot;
import net.nevet5gi.buzzbot.Config; import net.nevet5gi.buzzbot.Config;
import net.nevet5gi.buzzbot.commands.*; import net.nevet5gi.buzzbot.commands.*;
import net.nevet5gi.buzzbot.database.SqlDB;
import net.nevet5gi.buzzbot.objects.GuildData;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -15,6 +19,7 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
//TODO Make reload command for modules
public class CommandManager { public class CommandManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CommandManager.class); private static final Logger LOGGER = LoggerFactory.getLogger(CommandManager.class);
protected final List<ICommand> commands = new ArrayList<>(); protected final List<ICommand> commands = new ArrayList<>();
@@ -23,10 +28,11 @@ public class CommandManager {
public CommandManager() { public CommandManager() {
//Add to this list in alphabetical order //Add to this list in alphabetical order
addCommand(new BanCmd()); addCommand(new BanCmd());
addCommand(new BeeCmd());
addCommand(new HelpCmd(this)); addCommand(new HelpCmd(this));
addCommand(new MuteCmd()); addCommand(new MuteCmd());
addCommand(new PandaCmd());
addCommand(new PingCmd()); addCommand(new PingCmd());
addCommand(new SetRoleCmd());
addCommand(new TestCmd()); addCommand(new TestCmd());
addCommand(new UnbanCmd()); addCommand(new UnbanCmd());
addCommand(new UnmuteCmd()); addCommand(new UnmuteCmd());
@@ -35,8 +41,8 @@ public class CommandManager {
//addCommand(new CommandClass()); //addCommand(new CommandClass());
} }
private void addCommand(ICmdGeneric cmd) { protected void addCommand(ICmdGeneric cmd) {
boolean nameFound = commands.stream().anyMatch((it) -> it.getName().equalsIgnoreCase(cmd.getName())); boolean nameFound = commands.stream().anyMatch(it -> it.getName().equalsIgnoreCase(cmd.getName()));
if (nameFound) { if (nameFound) {
throw new IllegalArgumentException("A command with this name is already present"); throw new IllegalArgumentException("A command with this name is already present");
} }
@@ -56,7 +62,7 @@ public class CommandManager {
for (ISlashCommand slashCmd : slashList) { for (ISlashCommand slashCmd : slashList) {
cmdDataList.add(slashCmd.getCommandData()); cmdDataList.add(slashCmd.getCommandData());
} }
Bot.jda.updateCommands().addCommands(cmdDataList).queue(); BuzzBot.jda.updateCommands().addCommands(cmdDataList).queue();
} }
} }
@@ -64,6 +70,10 @@ public class CommandManager {
return commands; return commands;
} }
public List<ISlashCommand> getSlashCommands() {
return slashList;
}
@Nullable @Nullable
public ICommand getCommand(String search) { public ICommand getCommand(String search) {
String searchLower = search.toLowerCase(); String searchLower = search.toLowerCase();
@@ -77,6 +87,35 @@ public class CommandManager {
return null; return null;
} }
public boolean hasPermission(Member member, ICmdGeneric cmd, GuildData guild) {
List<Role> roles = member.getRoles();
int permLevel = 0;
for (Role role : roles) {
switch (role.getName().toLowerCase()) {
case "helper":
if (permLevel < 1) permLevel = 1;
continue;
case "moderator", "mod":
if (permLevel < 2) permLevel = 2;
continue;
case "administrator", "admin":
if (permLevel < 3) permLevel = 3;
continue;
case "owner":
if (permLevel < 4) permLevel = 4;
}
if (role.getIdLong() == guild.getHelperId() && permLevel < 1) permLevel = 1;
if (role.getIdLong() == guild.getModeratorId() && permLevel < 2) permLevel = 2;
if (role.getIdLong() == guild.getAdministratorId() && permLevel < 3) permLevel = 3;
if (role.getIdLong() == guild.getOwnerId() && permLevel < 4) permLevel = 4;
if (member.isOwner() && permLevel < 4) permLevel = 4;
}
return permLevel >= cmd.getPermissionLevel();
}
@Nullable @Nullable
public ISlashCommand getSlashCommand(String search) { public ISlashCommand getSlashCommand(String search) {
String searchLower = search.toLowerCase(); String searchLower = search.toLowerCase();
@@ -98,6 +137,15 @@ public class CommandManager {
String invoke = split[0].toLowerCase(); String invoke = split[0].toLowerCase();
ICommand cmd = getCommand(invoke); ICommand cmd = getCommand(invoke);
SqlDB sql = new SqlDB();
GuildData guild = sql.getGuildData(event.getGuild().getIdLong());
sql.close();
if (!hasPermission(event.getMember(), cmd, guild)) {
event.getMessage().reply("You do not have permission to use this command.").queue();
return;
}
if (cmd != null) { if (cmd != null) {
event.getChannel().sendTyping().queue(); event.getChannel().sendTyping().queue();
List<String> args = Arrays.asList(split).subList(1, split.length); List<String> args = Arrays.asList(split).subList(1, split.length);
@@ -114,6 +162,16 @@ public class CommandManager {
if (cmd != null) { if (cmd != null) {
event.deferReply().queue(); event.deferReply().queue();
SqlDB sql = new SqlDB();
GuildData guild = sql.getGuildData(event.getGuild().getIdLong());
sql.close();
if (!hasPermission(event.getMember(), cmd, guild)) {
event.getHook().sendMessage("You do not have permission to use this command.").queue();
return;
}
List<String> args = new ArrayList<>(); List<String> args = new ArrayList<>();
CommandContext ctx = new CommandContext(event, args); CommandContext ctx = new CommandContext(event, args);

View File

@@ -6,6 +6,14 @@ public interface ICmdGeneric {
String getName(); String getName();
/**
* @apiNote 0 = default, 1 = helper, 2 = moderator, 3 = admin, 4 = owner
* @return int
*/
default int getPermissionLevel() {
return 0;
}
String getHelp(); String getHelp();
default List<String> getAliases(){ default List<String> getAliases(){

View File

@@ -1,2 +1,152 @@
package net.nevet5gi.buzzbot.commands.utils;public class ICommandContext { package net.nevet5gi.buzzbot.commands.utils;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.interactions.InteractionHook;
import net.dv8tion.jda.api.sharding.ShardManager;
public interface ICommandContext {
/**
* Returns the {@link net.dv8tion.jda.api.entities.Guild} for the current command/event
*
* @return the {@link net.dv8tion.jda.api.entities.Guild} for this command/event
*/
default Guild getGuild() {
if (this.getEvent() == null) {
return this.getSlashEvent().getGuild();
} else if (this.getSlashEvent() == null) {
return this.getEvent().getGuild();
}
return null;
}
/**
* Returns the {@link net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent message event} that was received for this instance
*
* @return the {@link net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent message event} that was received for this instance
*/
GuildMessageReceivedEvent getEvent();
/**
* Returns the {@link net.dv8tion.jda.api.events.interaction.SlashCommandEvent interaction event} that was received for this instance
*
* @returns the {@link net.dv8tion.jda.api.events.interaction.SlashCommandEvent interaction event} that was received for this instance
*/
SlashCommandEvent getSlashEvent();
/**
* Returns the {@link net.dv8tion.jda.api.entities.TextChannel channel} that the message for this event was send in
*
* @return the {@link net.dv8tion.jda.api.entities.TextChannel channel} that the message for this event was send in
*/
default TextChannel getChannel() {
if (this.getEvent() == null) {
return this.getSlashEvent().getTextChannel();
} else if (this.getSlashEvent() == null) {
return this.getEvent().getChannel();
}
return null;
}
/**
* Returns the {@link net.dv8tion.jda.api.entities.Message message} that triggered this event
*
* @return the {@link net.dv8tion.jda.api.entities.Message message} that triggered this event
*/
default Message getMessage() {
if (this.getEvent() == null) {
return null;
} else if (this.getSlashEvent() == null) {
return this.getEvent().getMessage();
}
return null;
}
default String getCommandString() {
if (this.getEvent() == null) {
return this.getSlashEvent().getCommandString();
}
return null;
}
/**
* Returns the {@link net.dv8tion.jda.api.entities.User author} of the message as user
*
* @return the {@link net.dv8tion.jda.api.entities.User author} of the message as user
*/
default User getAuthor() {
if (this.getEvent() == null) {
return this.getSlashEvent().getUser();
} else if (this.getSlashEvent() == null) {
return this.getEvent().getAuthor();
}
return null;
}
/**
* Returns the {@link net.dv8tion.jda.api.entities.Member author} of the message as member
*
* @return the {@link net.dv8tion.jda.api.entities.Member author} of the message as member
*/
default Member getMember() {
if (this.getEvent() == null) {
return this.getSlashEvent().getMember();
} else if (this.getSlashEvent() == null) {
return this.getEvent().getMember();
}
return null;
}
/**
* Returns the {@link net.dv8tion.jda.api.interactions.InteractionHook interaction hook} of the slash command
*
* @return the {@link net.dv8tion.jda.api.interactions.InteractionHook interaction hook} of the slash command
*/
default InteractionHook getHook() {
return this.getSlashEvent().getHook();
}
/**
* Returns the current {@link net.dv8tion.jda.api.JDA jda} instance
*
* @return the current {@link net.dv8tion.jda.api.JDA jda} instance
*/
default JDA getJDA() {
if (this.getEvent() == null) {
return this.getSlashEvent().getJDA();
} else if (this.getSlashEvent() == null) {
return this.getEvent().getJDA();
}
return null;
}
/**
* Returns the current {@link net.dv8tion.jda.api.sharding.ShardManager} instance
*
* @return the current {@link net.dv8tion.jda.api.sharding.ShardManager} instance
*/
default ShardManager getShardManager() {
return this.getJDA().getShardManager();
}
/**
* Returns the {@link net.dv8tion.jda.api.entities.User user} for the currently logged in account
*
* @return the {@link net.dv8tion.jda.api.entities.User user} for the currently logged in account
*/
default User getSelfUser() {
return this.getJDA().getSelfUser();
}
/**
* Returns the {@link net.dv8tion.jda.api.entities.Member member} in the guild for the currently logged in account
*
* @return the {@link net.dv8tion.jda.api.entities.Member member} in the guild for the currently logged in account
*/
default Member getSelfMember() {
return this.getGuild().getSelfMember();
}
} }

View File

@@ -1,12 +1,10 @@
package net.nevet5gi.buzzbot.database; package net.nevet5gi.buzzbot.database;
import net.nevet5gi.buzzbot.Config; import net.nevet5gi.buzzbot.Config;
import net.nevet5gi.buzzbot.objects.BanData; import net.nevet5gi.buzzbot.objects.*;
import net.nevet5gi.buzzbot.objects.GuildData;
import net.nevet5gi.buzzbot.objects.MuteData;
import net.nevet5gi.buzzbot.objects.WarnData;
import java.sql.*; import java.sql.*;
import java.util.ArrayList;
public class SqlDB { public class SqlDB {
private Connection connect; private Connection connect;
@@ -25,17 +23,25 @@ public class SqlDB {
public void insertBan(BanData ban, String table) { public void insertBan(BanData ban, String table) {
try { try {
statement.executeUpdate("INSERT INTO " + table + " VALUES (default, " + ban.getUserId() + ", '" + ban.getUserName() + "', '" + ban.getDate() + "', '" + ban.getTime() + "', " + ban.getBanType() + ", " + ban.getBanLength() + ", '" + ban.getBanReason() + "', '" + ban.getModName() + "', " + ban.getModId() + ", '" + ban.getServerName() + "', " + ban.getServerId() + ")"); statement.executeUpdate("INSERT INTO master_ban_record VALUES (default, " + ban.getUserId() + ", '" + ban.getUserName() + "', '" + ban.getDate() + "', '" + ban.getTime() + "', " + ban.getBanType() + ", " + ban.getBanLength() + ", '" + ban.getReason() + "', '" + ban.getModName() + "', " + ban.getModId() + ", '" + ban.getServerName() + "', " + ban.getServerId() + ", 1)");
if (!table.equalsIgnoreCase("master_ban_record")) {
statement.executeUpdate("INSERT INTO " + table + " VALUES (default, " + ban.getUserId() + ", '" + ban.getUserName() + "', '" + ban.getDate() + "', '" + ban.getTime() + "', " + ban.getBanType() + ", " + ban.getBanLength() + ", '" + ban.getReason() + "', '" + ban.getModName() + "', " + ban.getModId() + ", '" + ban.getServerName() + "', " + ban.getServerId() + ", 1)");
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
public void insertUnban(long userId, String table) {
close();
} }
public void insertMute(MuteData mute, String table) { public void insertMute(MuteData mute, String table) {
try { try {
statement.executeUpdate("INSERT INTO " + table + " VALUES (default, " + mute.getUserId() + ", '" + mute.getUserName() + "', '" + mute.getDate() + "', '" + mute.getTime() + "', " + mute.getMuteLength() + ", '" + mute.getMuteReason() + "', '" + mute.getModName() + "', " + mute.getModId() + ", '" + mute.getServerName() + "', " + mute.getServerId() + ")"); statement.executeUpdate("INSERT INTO master_mute_record VALUES (default, " + mute.getUserId() + ", '" + mute.getUserName() + "', '" + mute.getDate() + "', '" + mute.getTime() + "', " + mute.getMuteLength() + ", '" + mute.getReason() + "', '" + mute.getModName() + "', " + mute.getModId() + ", '" + mute.getServerName() + "', " + mute.getServerId() + ")");
if (!table.equalsIgnoreCase("master_mute_record")) {
statement.executeUpdate("INSERT INTO " + table + " VALUES (default, " + mute.getUserId() + ", '" + mute.getUserName() + "', '" + mute.getDate() + "', '" + mute.getTime() + "', " + mute.getMuteLength() + ", '" + mute.getReason() + "', '" + mute.getModName() + "', " + mute.getModId() + ", '" + mute.getServerName() + "', " + mute.getServerId() + ")");
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -43,7 +49,10 @@ public class SqlDB {
public void insertWarn(WarnData warn, String table) { public void insertWarn(WarnData warn, String table) {
try { try {
statement.executeUpdate("INSERT INTO " + table + " VALUES (default, " + warn.getUserId() + ", '" + warn.getUserName() + "', '" + warn.getDate() + "', '" + warn.getTime() + "', " + warn.getBanType() + ", " + warn.getBanLength() + ", '" + warn.getBanReason() + "', '" + warn.getModName() + "', " + warn.getModId() + ", '" + warn.getServerName() + "', " + warn.getServerId() + ")"); statement.executeUpdate("INSERT INTO master_warn_record VALUES (default, " + warn.getUserId() + ", '" + warn.getUserName() + "', '" + warn.getDate() + "', '" + warn.getTime() + "', '" + warn.getReason() + "', '" + warn.getModName() + "', " + warn.getModId() + ", '" + warn.getServerName() + "', " + warn.getServerId() + ")");
if (!table.equalsIgnoreCase("master_warn_record")){
statement.executeUpdate("INSERT INTO " + table + " VALUES (default, " + warn.getUserId() + ", '" + warn.getUserName() + "', '" + warn.getDate() + "', '" + warn.getTime() + "', '" + warn.getReason() + "', '" + warn.getModName() + "', " + warn.getModId() + ", '" + warn.getServerName() + "', " + warn.getServerId() + ")");
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -53,8 +62,6 @@ public class SqlDB {
BanData ban = new BanData(); BanData ban = new BanData();
try { try {
//TODO Make this use GuildUtils in order to get the proper group for the server
resultSet = statement.executeQuery("SELECT * FROM " + table + " WHERE userId=" + userId); resultSet = statement.executeQuery("SELECT * FROM " + table + " WHERE userId=" + userId);
while (resultSet.next()) { while (resultSet.next()) {
@@ -62,9 +69,9 @@ public class SqlDB {
ban.setUserName(resultSet.getString("user_name")); ban.setUserName(resultSet.getString("user_name"));
ban.setDate(resultSet.getDate("ban_date")); ban.setDate(resultSet.getDate("ban_date"));
ban.setTime(resultSet.getTime("ban_time")); ban.setTime(resultSet.getTime("ban_time"));
ban.setReason(resultSet.getString("ban_reason"));
ban.setBanType(resultSet.getBoolean("ban_type")); ban.setBanType(resultSet.getBoolean("ban_type"));
ban.setBanLength(resultSet.getInt("ban_length")); ban.setBanLength(resultSet.getInt("ban_length"));
ban.setBanReason(resultSet.getString("ban_reason"));
ban.setModName(resultSet.getString("mod_name")); ban.setModName(resultSet.getString("mod_name"));
ban.setModId(resultSet.getLong("mod_id")); ban.setModId(resultSet.getLong("mod_id"));
ban.setServerName(resultSet.getString("server_name")); ban.setServerName(resultSet.getString("server_name"));
@@ -74,8 +81,6 @@ public class SqlDB {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
close();
return ban; return ban;
} }
@@ -93,7 +98,6 @@ public class SqlDB {
} catch (SQLException e) { } catch (SQLException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
return mute; return mute;
} }
@@ -110,18 +114,15 @@ public class SqlDB {
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
return warn; return warn;
} }
public void addGuild(GuildData guild) { public void addGuild(GuildData guild) {
try { try {
statement.executeUpdate("INSERT INTO guild_settings VALUES ('" + guild.getName() + "', " + guild.getId() + ", '" + guild.getGroup() + "', " + guild.getProfanityLevel() + ")"); statement.executeUpdate("INSERT INTO guild_settings VALUES ('" + guild.getName() + "', " + guild.getId() + ", '" + guild.getGroup() + "', " + guild.getProfanityLevel() + ", 0, 0, 0, 0)");
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
close();
} }
public GuildData getGuildData(long guildId) { public GuildData getGuildData(long guildId) {
@@ -135,15 +136,47 @@ public class SqlDB {
guild.setId(resultSet.getLong("guild_id")); guild.setId(resultSet.getLong("guild_id"));
guild.setGroup(resultSet.getString("guild_group")); guild.setGroup(resultSet.getString("guild_group"));
guild.setProfanityLevel(resultSet.getInt("profanity_level")); guild.setProfanityLevel(resultSet.getInt("profanity_level"));
guild.setHelperId(resultSet.getLong("helper_id"));
guild.setModeratorId(resultSet.getLong("moderator_id"));
guild.setAdministratorId(resultSet.getLong("administrator_id"));
guild.setOwnerId(resultSet.getLong("owner_id"));
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
return guild; return guild;
} }
private void close() { public void updateGuildRole(long guildId, String role, long roleId) {
String sql = "UPDATE guild_settings SET " + role + " = " + roleId + " WHERE guild_id = " + guildId;
try {
statement.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addGroup(Group group) {
//TODO Make this function
}
public ArrayList<Group> getGroups() {
String sql = "";
ArrayList<Group> groups = new ArrayList<>();
try {
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
}
} catch (SQLException e) {
e.printStackTrace();
}
return groups;
}
public void close() {
try { try {
if (resultSet != null) { if (resultSet != null) {
resultSet.close(); resultSet.close();

View File

@@ -25,12 +25,12 @@ public class ProfanityFilter {
public void handle(GuildMessageReceivedEvent event) { public void handle(GuildMessageReceivedEvent event) {
event.getMessage().delete().queue(); event.getMessage().delete().queue();
event.getChannel().sendMessage("No swearing please :)").queue(); event.getChannel().sendMessage("Hey <@" + event.getAuthor().getId() + ">, no swearing!").queue();
} }
public void handleEdit(GuildMessageUpdateEvent event) { public void handleEdit(GuildMessageUpdateEvent event) {
event.getMessage().delete().queue(); event.getMessage().delete().queue();
event.getChannel().sendMessage("Nice try ;)").queue(); event.getChannel().sendMessage("Hey <@" + event.getAuthor().getId() + ">, no swearing!").queue();
} }
public void buildDictionaries() { public void buildDictionaries() {

View File

@@ -0,0 +1,12 @@
package net.nevet5gi.buzzbot.modules;
import net.dv8tion.jda.api.JDA;
public interface BuzzyModule {
default void onPreEnable() {}
void onEnable(JDA jda);
void onDisable();
}

View File

@@ -0,0 +1,71 @@
package net.nevet5gi.buzzbot.modules;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.jar.Attributes;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
public class ModuleLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(ModuleLoader.class);
public static ArrayList<Path> getModules() {
File modulesPath = new File("./modules/");
if (!modulesPath.exists()) {
modulesPath.mkdirs();
}
ArrayList<Path> modules = new ArrayList<>();
try {
Files.walk(Paths.get("./modules/"))
.filter(Files::isRegularFile)
.forEach(modules::add);
} catch (IOException e) {
System.out.println("Unable to get module list");
e.printStackTrace();
}
return modules;
}
public static ArrayList<BuzzyModule> loadModules() throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
ArrayList<Path> modulePaths = getModules();
ArrayList<BuzzyModule> modules = new ArrayList<>();
for (Path module : modulePaths) {
JarInputStream jarStream = new JarInputStream(new FileInputStream(String.valueOf(module)));
Manifest mf = jarStream.getManifest();
Attributes attributes = mf.getMainAttributes();
String className = attributes.getValue("Main-Class");
if (className == null) {
LOGGER.error("Unable to get Main Class from module " + module.toString());
}
File file = module.toFile();
URL[] urls = {file.toURI().toURL()};
URLClassLoader urlClassLoader = URLClassLoader.newInstance(urls);
Class<?> mainClass = Class.forName(className, true, urlClassLoader);
BuzzyModule newModule = (BuzzyModule) mainClass.getDeclaredConstructor().newInstance();
newModule.onPreEnable();
modules.add(newModule);
if (jarStream != null ) {
jarStream.close();
}
if (urlClassLoader != null) {
urlClassLoader.close();
}
}
return modules;
}
}

View File

@@ -3,18 +3,15 @@ package net.nevet5gi.buzzbot.objects;
import java.sql.Date; import java.sql.Date;
import java.sql.Time; import java.sql.Time;
public class BanData extends UserData { public class BanData extends DisciplineData {
private boolean banType; private boolean banType;
private int banLength; private int banLength;
private String banReason;
public BanData() {} public BanData() {}
public BanData(long userId, String userName, Date date, Time time, boolean banType, int banLength, String banReason, String modName, long modId, String serverName, long serverId) { public BanData(long userId, String userName, Date date, Time time, String reason, boolean banType, int banLength, String modName, long modId, String serverName, long serverId) {
super(userId, userName, date, time, modName, modId, serverName, serverId); super(userId, userName, date, time, reason, modName, modId, serverName, serverId);
this.banType = banType; this.banType = banType;
this.banLength = banLength; this.banLength = banLength;
this.banReason = banReason;
} }
public void setBanType(boolean banType) { public void setBanType(boolean banType) {
@@ -32,12 +29,4 @@ public class BanData extends UserData {
public int getBanLength() { public int getBanLength() {
return banLength; return banLength;
} }
public void setBanReason(String banReason) {
this.banReason = banReason;
}
public String getBanReason() {
return banReason;
}
} }

View File

@@ -5,23 +5,25 @@ import java.sql.Time;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalTime; import java.time.LocalTime;
public class UserData { public class DisciplineData {
private long userId; private long userId;
private String userName; private String userName;
private Date date = Date.valueOf(LocalDate.now()); private Date date = Date.valueOf(LocalDate.now());
private Time time = Time.valueOf(LocalTime.now()); private Time time = Time.valueOf(LocalTime.now());
private String reason;
private String modName; private String modName;
private long modId; private long modId;
private String serverName; private String serverName;
private long serverId; private long serverId;
public UserData() {} public DisciplineData() {}
public UserData(long userId, String userName, Date date, Time time, String modName, long modId, String serverName, long serverId) { public DisciplineData(long userId, String userName, Date date, Time time, String reason, String modName, long modId, String serverName, long serverId) {
this.setUserId(userId); this.setUserId(userId);
this.setUserName(userName); this.setUserName(userName);
this.setDate(date); this.setDate(date);
this.setTime(time); this.setTime(time);
this.setReason(reason);
this.setModName(modName); this.setModName(modName);
this.setModId(modId); this.setModId(modId);
this.setServerName(serverName); this.setServerName(serverName);
@@ -60,6 +62,14 @@ public class UserData {
return time; return time;
} }
public void setReason(String reason) {
this.reason = reason;
}
public String getReason() {
return reason;
}
public void setModName(String modName) { public void setModName(String modName) {
this.modName = modName; this.modName = modName;
} }

View File

@@ -0,0 +1,37 @@
package net.nevet5gi.buzzbot.objects;
import java.util.List;
public class Group {
private String name;
private String tablePrefix;
private List<String> members;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setTablePrefix(String tablePrefix) {
this.tablePrefix = tablePrefix;
}
public String getTablePrefix() {
return tablePrefix;
}
public void setMembers(List<String> members) {
this.members = members;
}
public void addMember(String member) {
this.members.add(member);
}
public List<String> getMembers() {
return members;
}
}

View File

@@ -5,6 +5,10 @@ public class GuildData {
private long id; private long id;
private String group; private String group;
private int profanityLevel; private int profanityLevel;
private long helperId;
private long moderatorId;
private long administratorId;
private long ownerId;
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
@@ -37,4 +41,36 @@ public class GuildData {
public int getProfanityLevel() { public int getProfanityLevel() {
return profanityLevel; return profanityLevel;
} }
public void setHelperId(long helperId) {
this.helperId = helperId;
}
public long getHelperId() {
return helperId;
}
public void setModeratorId(long moderatorId) {
this.moderatorId = moderatorId;
}
public long getModeratorId() {
return moderatorId;
}
public void setAdministratorId(long administratorId) {
this.administratorId = administratorId;
}
public long getAdministratorId() {
return administratorId;
}
public void setOwnerId(long ownerId) {
this.ownerId = ownerId;
}
public long getOwnerId() {
return ownerId;
}
} }

View File

@@ -0,0 +1,17 @@
package net.nevet5gi.buzzbot.objects;
public enum ModRoles {
HELPER("helper_id"),
MODERATOR("moderator_id"),
ADMINISTRATOR("administrator_id"),
OWNER("owner_id");
private final String role;
ModRoles(String role) {
this.role = role;
}
public String getRole() {
return this.role;
}
}

View File

@@ -3,16 +3,14 @@ package net.nevet5gi.buzzbot.objects;
import java.sql.Date; import java.sql.Date;
import java.sql.Time; import java.sql.Time;
public class MuteData extends UserData { public class MuteData extends DisciplineData {
private int muteLength; private int muteLength;
private String muteReason;
public MuteData() {} public MuteData() {}
public MuteData(long userId, String userName, Date date, Time time, int muteLength, String muteReason, String modName, long modId, String serverName, long serverId) { public MuteData(long userId, String userName, Date date, Time time, String reason, int muteLength, String modName, long modId, String serverName, long serverId) {
super(userId, userName, date, time, modName, modId, serverName, serverId); super(userId, userName, date, time, reason, modName, modId, serverName, serverId);
this.muteLength = muteLength; this.muteLength = muteLength;
this.muteReason = muteReason;
} }
public void setMuteLength(int muteLength) { public void setMuteLength(int muteLength) {
@@ -22,12 +20,4 @@ public class MuteData extends UserData {
public int getMuteLength() { public int getMuteLength() {
return muteLength; return muteLength;
} }
public void setMuteReason(String muteReason) {
this.muteReason = muteReason;
}
public String getMuteReason() {
return muteReason;
}
} }

View File

@@ -3,41 +3,11 @@ package net.nevet5gi.buzzbot.objects;
import java.sql.Date; import java.sql.Date;
import java.sql.Time; import java.sql.Time;
public class WarnData extends UserData { public class WarnData extends DisciplineData {
private boolean banType;
private int banLength;
private String banReason;
public WarnData() {} public WarnData() {}
public WarnData(long userId, String userName, Date date, Time time, boolean banType, int banLength, String banReason, String modName, long modId, String serverName, long serverId) { public WarnData(long userId, String userName, Date date, Time time, String reason, String modName, long modId, String serverName, long serverId) {
super(userId, userName, date, time, modName, modId, serverName, serverId); super(userId, userName, date, time, reason, modName, modId, serverName, serverId);
this.banType = banType;
this.banLength = banLength;
this.banReason = banReason;
}
public void setBanType(boolean banType) {
this.banType = banType;
}
public boolean getBanType() {
return banType;
}
public void setBanLength(int banLength) {
this.banLength = banLength;
}
public int getBanLength() {
return banLength;
}
public void setBanReason(String banReason) {
this.banReason = banReason;
}
public String getBanReason() {
return banReason;
} }
} }

View File

@@ -0,0 +1,19 @@
package net.nevet5gi.buzzbot.util;
import net.dv8tion.jda.api.entities.Guild;
import net.nevet5gi.buzzbot.database.SqlDB;
public class GuildUtils {
public static void loadGroups() {
SqlDB sql = new SqlDB();
sql.close();
}
public static String getTable(Guild guild) {
guild.getIdLong();
return null;
}
}

View File

@@ -1,14 +1,12 @@
package net.nevet5gi.buzzbot.util; package net.nevet5gi.buzzbot.util;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import net.nevet5gi.buzzbot.objects.DisciplineData;
import net.nevet5gi.buzzbot.objects.UserData;
import java.io.*; import java.io.*;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.ArrayList;
public class JsonUtils <T extends UserData> { public class JsonUtils <T extends DisciplineData> {
T object; T object;
// public void createJson(T object) { // public void createJson(T object) {