Compare commits

..

9 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
d8a43381d2 Added some more slash commands 2022-05-25 10:12:17 -04:00
6f87ef3a5e fixed db and reworked bans 2022-05-24 21:03:01 -04:00
f82a8988f9 I gotta start committing more consistently 2022-05-24 19:48:32 -04:00
98abaccf25 Periodic update 2022-04-27 21:50:06 -04:00
62ea316e07 Minor update 2022-04-25 22:40:42 -04:00
50 changed files with 2102 additions and 543 deletions

3
.gitignore vendored
View File

@@ -42,3 +42,6 @@ bin/
.DS_Store
config.yml
strong.txt
moderate.txt
mild.txt

1
.idea/gradle.xml generated
View File

@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>

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">
<output url="file://$PROJECT_DIR$/out" />
</component>
<component name="SwUserDefinedSpecifications">
<option name="specTypeByUrl">
<map />
</option>
</component>
</project>

2
.idea/sqldialects.xml generated
View File

@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/src/main/java/net/nevet5/buzzbot/database/SqlDB.java" dialect="GenericSQL" />
<file url="file://$PROJECT_DIR$/src/main/java/net/nevet5gi/buzzbot/database/SqlDB.java" dialect="GenericSQL" />
<file url="PROJECT" dialect="MySQL" />
</component>
</project>

View File

@@ -1,16 +1,17 @@
plugins {
id 'java'
id 'application'
id 'maven-publish'
id 'com.github.johnrengelman.shadow' version '5.2.0'
}
mainClassName = 'net.nevet5.buzzbot.Bot'
mainClassName = 'net.nevet5gi.buzzbot.Bot'
group 'net.nevet5'
version '0.1.0'
def jdaVer = '4.4.0_350'
group 'net.nevet5gi'
version '0.5.2'
sourceCompatibility = targetCompatibility = JavaVersion.VERSION_17
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
repositories {
mavenCentral()
@@ -27,11 +28,34 @@ repositories {
}
dependencies {
implementation("net.dv8tion:JDA:$jdaVer")
implementation group: 'me.duncte123', name: 'botCommons', version: '2.3.8'
implementation 'net.dv8tion:JDA:4.4.0_350'
implementation 'ch.qos.logback:logback-classic:1.2.11'
//implementation 'me.duncte123:botCommons:2.3.8'
implementation 'com.google.code.gson:gson:2.9.0'
implementation 'me.carleslc.Simple-YAML:Simple-Yaml:1.7.2'
implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.28'
implementation 'mysql:mysql-connector-java:8.0.29'
//implementation 'com.github.Kaktushose:jda-commands:v.2.2.0'
}
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

@@ -1,33 +0,0 @@
package net.nevet5.buzzbot;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.nevet5.buzzbot.commands.utils.CommandManager;
import javax.annotation.Nonnull;
public class Listener extends ListenerAdapter {
private final CommandManager manager = new CommandManager();
@Override
public void onReady(@Nonnull ReadyEvent event) {
System.out.println("BuzzBot is ready" + event.getJDA().getSelfUser().getAsTag());
}
@Override
public void onGuildMessageReceived(@Nonnull GuildMessageReceivedEvent event) {
User user = event.getAuthor();
if (user.isBot() || event.isWebhookMessage()) {
return;
}
String raw = event.getMessage().getContentRaw();
if (raw.startsWith(Config.getConfig().getString("bot.prefix"))) {
manager.handle(event);
}
}
}

View File

@@ -1,9 +0,0 @@
package net.nevet5.buzzbot;
import java.time.LocalTime;
public class Test {
public static void main(String[] args) {
}
}

View File

@@ -1,68 +0,0 @@
package net.nevet5.buzzbot.commands;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.TextChannel;
import net.nevet5.buzzbot.Config;
import net.nevet5.buzzbot.commands.utils.CommandContext;
import net.nevet5.buzzbot.commands.utils.CommandManager;
import net.nevet5.buzzbot.commands.utils.ICommand;
import java.util.List;
public class HelpCmd implements ICommand {
private final CommandManager manager;
public HelpCmd(CommandManager manager) {
this.manager = manager;
}
@Override
public void handle(CommandContext ctx) {
List<String> args = ctx.getArgs();
TextChannel channel = ctx.getChannel();
if (args.isEmpty()) {
StringBuilder builder = new StringBuilder();
EmbedBuilder eb = new EmbedBuilder();
eb.setTitle("List of Commands");
manager.getCommands().stream().map(ICommand::getName).forEach(
(it) -> builder.append('`').append(Config.getConfig().getString("bot.prefix")).append(it).append("`\n")
);
eb.addField("", builder.toString(), false);
channel.sendMessageEmbeds(eb.build()).queue();
return;
}
String search = args.get(0);
ICommand command = manager.getCommand(search);
if (command == null) {
channel.sendMessage("Nothing found for " + search);
return;
}
channel.sendMessage(command.getHelp()).queue();
}
@Override
public String getName() {
return "help";
}
@Override
public String getHelp() {
return "Shows the list of bot commands\n" +
"Usage: `" + Config.getConfig().getString("bot.prefix") + "help [command]`";
}
@Override
public List<String> getAliases() {
return List.of("commands", "cmds", "commandlist");
}
}

View File

@@ -1,64 +0,0 @@
package net.nevet5.buzzbot.commands;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import net.dv8tion.jda.api.EmbedBuilder;
import net.nevet5.buzzbot.Config;
import net.nevet5.buzzbot.commands.utils.CommandContext;
import net.nevet5.buzzbot.commands.utils.ICommand;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class PandaCmd implements ICommand {
public static String url;
@Override
public void handle(CommandContext ctx) {
try { getHttpConnection(); } catch (IOException | InterruptedException e) { e.printStackTrace(); }
EmbedBuilder eb = new EmbedBuilder();
ctx.getChannel().sendTyping().queue();
eb.setImage(url.replace("\"",""));
ctx.getChannel().sendMessage(eb.build()).queue();
}
@Override
public String getName() {
return "panda";
}
@Override
public String getHelp() {
return "Sends a picture of a panda!\n" +
"Usage: `" + Config.getConfig().getString("bot.prefix") + "panda`";
}
public static void getHttpConnection() throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.GET()
.header("accept", "application/json")
.uri(URI.create("https://some-random-api.ml/img/panda"))
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenApply(PandaCmd::parse)
.join();
}
public static String parse(String response) {
String mod = "[ " + response + " ]";
JsonArray ja = new Gson().fromJson(mod, JsonArray.class);
for (int i = 0; i < ja.getAsJsonArray().size(); i++) {
JsonElement jo = ja.get(i);
url = jo.getAsJsonObject().get("link").toString();
}
return null;
}
}

View File

@@ -1,27 +0,0 @@
package net.nevet5.buzzbot.commands;
import net.dv8tion.jda.api.JDA;
import net.nevet5.buzzbot.Config;
import net.nevet5.buzzbot.commands.utils.CommandContext;
import net.nevet5.buzzbot.commands.utils.ICommand;
public class PingCmd implements ICommand {
@Override
public void handle(CommandContext ctx) {
JDA jda = ctx.getJDA();
jda.getRestPing().queue((ping) -> ctx.getChannel().sendMessageFormat("Rest API Ping: %sms\nWebSocket Ping: %sms", ping, jda.getGatewayPing()).queue());
}
@Override
public String getHelp() {
return "Shows the current ping from the bot to the Discord servers" +
"Usage: `" + Config.getConfig().getString("bot.prefix") + "ping`";
}
@Override
public String getName() {
return "ping";
}
}

View File

@@ -1,70 +0,0 @@
package net.nevet5.buzzbot.commands.utils;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.nevet5.buzzbot.Config;
import net.nevet5.buzzbot.commands.HelpCmd;
import net.nevet5.buzzbot.commands.PandaCmd;
import net.nevet5.buzzbot.commands.PingCmd;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
public class CommandManager {
protected final List<ICommand> commands = new ArrayList<>();
public CommandManager() {
//Add to this list in alphabetical order
addCommand(new HelpCmd(this));
addCommand(new PandaCmd());
addCommand(new PingCmd());
//addCommand(new CommandClass());
}
private void addCommand(ICommand cmd) {
boolean nameFound = this.commands.stream().anyMatch((it) -> it.getName().equalsIgnoreCase(cmd.getName()));
if (nameFound) {
throw new IllegalArgumentException("A command with this name is already present");
}
commands.add(cmd);
}
public List<ICommand> getCommands() {
return commands;
}
@Nullable
public ICommand getCommand(String search) {
String searchLower = search.toLowerCase();
for (ICommand cmd : this.commands) {
if (cmd.getName().equals(searchLower) || cmd.getAliases().contains(searchLower)) {
return cmd;
}
}
return null;
}
public void handle(GuildMessageReceivedEvent event) {
String[] split = event.getMessage().getContentRaw()
.replaceFirst("(?i)" + Pattern.quote(Config.getConfig().getString("bot.prefix")), "")
.split("\\s+");
String invoke = split[0].toLowerCase();
ICommand cmd = this.getCommand(invoke);
if (cmd !=null) {
event.getChannel().sendTyping().queue();
List<String> args = Arrays.asList(split).subList(1, split.length);
CommandContext ctx = new CommandContext(event, args);
cmd.handle(ctx);
}
}
}

View File

@@ -1,15 +0,0 @@
package net.nevet5.buzzbot.commands.utils;
import java.util.List;
public interface ICommand {
void handle(CommandContext ctx);
String getName();
String getHelp();
default List<String> getAliases() {
return List.of();
}
}

View File

@@ -1,188 +0,0 @@
package net.nevet5.buzzbot.database;
import net.nevet5.buzzbot.Config;
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalTime;
public class SqlDB {
//TODO Make this a two way class for reading and writing from db
private int userId;
private String userName;
private int userDiscriminator;
private String date = LocalDate.now().toString();
private String time = LocalTime.now().toString().split("\\.")[0];
private boolean banType;
private int banLength;
private String banReason;
private String modName;
private int modId;
private String serverName;
private int serverId;
private Connection connect;
private Statement statement;
private PreparedStatement preparedStatement;
private ResultSet resultSet;
public SqlDB() {
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://" + Config.getConfig().getString("database.url") + "/" + Config.getConfig().getString("database.database") + "?user=" + Config.getConfig().getString("database.user") + "&password=" + Config.getConfig().getString("database.password"));
statement = connect.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
public void readDatabase() {
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://" + Config.getConfig().getString("database.url") + "/" + Config.getConfig().getString("database.database") + "?user=" + Config.getConfig().getString("database.user") + "&password=" + Config.getConfig().getString("database.password"));
statement = connect.createStatement();
resultSet = statement
.executeQuery("SELECT * FROM masterbanlist");
} catch (ClassNotFoundException | SQLException e) {
throw new RuntimeException(e);
}
}
public void insert() {
try {
statement = connect.createStatement();
resultSet = statement.executeQuery("INSERT INTO " + Config.getConfig().getString("database.database") + " VALUES (default, " + userId + ", '" + userName + "', '" + userDiscriminator + "', '" + date + "', '" + time + "', " + banType + ", " + banLength + ", '" + banReason + "', '" + modName + "', " + modId + ", '" + serverName + "', " + serverId + ");");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
while (resultSet.next()) {
userId = resultSet.getInt("userid");
userName = resultSet.getString("username");
userDiscriminator = resultSet.getInt("userdiscriminator");
// date;
// time;
// banType;
// banLength;
// banReason;
// modName;
// modId;
// serverName;
// serverId;
String user = resultSet.getString("myuser");
String website = resultSet.getString("webpage");
String summary = resultSet.getString("summary");
Date date = resultSet.getDate("datum");
String comment = resultSet.getString("comments");
System.out.println("User: " + user);
System.out.println("Website: " + website);
System.out.println("summary: " + summary);
System.out.println("Date: " + date);
System.out.println("Comment: " + comment);
}
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getUserId() {
return userId;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserDiscriminator(int userDiscriminator) {
this.userDiscriminator = userDiscriminator;
}
public int getUserDiscriminator() {
return userDiscriminator;
}
public void setDate(String date) {
this.date = date;
}
public String getDate() {
return date;
}
public void setTime(String time) {
this.time = time;
}
public String getTime() {
return time;
}
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;
}
public void setModName(String modName) {
this.modName = modName;
}
public String getModName() {
return modName;
}
public void setModId(int modId) {
this.modId = modId;
}
public int getModId() {
return modId;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public String getServerName() {
return serverName;
}
public void setServerId(int serverId) {
this.serverId = serverId;
}
public int getServerId() {
return serverId;
}
}

View File

@@ -1,33 +1,65 @@
package net.nevet5.buzzbot;
package net.nevet5gi.buzzbot;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.utils.cache.CacheFlag;
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.LoggerFactory;
import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.EnumSet;
public class Bot {
public class BuzzBot {
//TODO Make shutdown sequence
public static JDA jda;
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) {
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 {
jda = JDABuilder.createDefault(Config.getConfig().getString("bot.token"))
JDABuilder builder = JDABuilder.createDefault(Config.getConfig().getString("bot.token"))
.disableCache(EnumSet.of(
CacheFlag.CLIENT_STATUS,
CacheFlag.ACTIVITY,
CacheFlag.EMOTE
))
.enableCache(CacheFlag.VOICE_STATE)
.addEventListeners(new Listener())
.build();
.enableCache(CacheFlag.VOICE_STATE);
for (ListenerAdapter listener : PLUGIN_LISTENERS) {
builder.addEventListeners(listener);
}
jda = builder.build();
CommandManager.registerSlashCommands();
for (BuzzyModule module : modules) {
module.onEnable(jda);
}
getActivity();
LOGGER.info("BuzzBot finished loading!");
} catch (LoginException e) {
e.printStackTrace();
}
Listener.startProfanityFilter();
}
public static void getActivity() {
@@ -46,36 +78,8 @@ public class Bot {
}
}
// public static void main(String[] args) {
// Config.loadConfig();
//
// JDABuilder jdaBotBuilder = JDABuilder.createDefault(Config.getConfig().getString("bot.token"));
// // A token must be provided
//
// /* Start the JDA bot builder, letting you provide the token externally rather
// * than writing it in your program's code. args[0] is the token. */
//
// // Disable parts of the cache
// jdaBotBuilder.disableCache(CacheFlag.MEMBER_OVERRIDES, CacheFlag.VOICE_STATE);
//
// // Enable the bulk delete event - this means you'll have to handle it yourself!
// jdaBotBuilder.setBulkDeleteSplittingEnabled(false);
//
// // Set activity (like "playing Something")
//
// // Set event listeners
// jdaBotBuilder.addEventListeners(/*new MessageListener(), new ReadyListener()*/);
//
// try {
// // create the instance of JDA
// JDA discordBot = jdaBotBuilder.build();
//
// // optionally block until JDA is ready
// discordBot.awaitReady();
// } catch (LoginException | InterruptedException e) {
// System.err.println("Couldn't login.");
// e.printStackTrace();
// }
// }
public static void addListener(ListenerAdapter listener) {
PLUGIN_LISTENERS.add(listener);
}
}

View File

@@ -1,28 +1,29 @@
package net.nevet5.buzzbot;
package net.nevet5gi.buzzbot;
import org.simpleyaml.configuration.file.YamlFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Config {
private static final YamlFile YML_FILE = new YamlFile("./config.yml");
private static final Logger LOGGER = LoggerFactory.getLogger(Config.class);
public static void loadConfig() {
YML_FILE.setConfigurationFile("./config.yml");
try {
if (!YML_FILE.exists()) {
System.out.println("Config file not found, creating new one...");
LOGGER.info("Config file not found, creating new one...");
YML_FILE.createNewFile(true);
System.out.println("Config file created!");
LOGGER.info("Config file created!");
} else {
System.out.println("Loading Config file...");
LOGGER.info("Loading Config file...");
YML_FILE.loadWithComments();
System.out.println("Config file loaded!");
LOGGER.info("Config file loaded!");
}
} catch (final Exception e) {
System.out.println("Error while loading config file!");
LOGGER.error("Error while loading config file!");
e.printStackTrace();
}
@@ -32,9 +33,12 @@ public class Config {
YML_FILE.addDefault("bot.activity", "playing");
YML_FILE.addDefault("bot.action", "with myself");
YML_FILE.addDefault("database.url", "localhost");
YML_FILE.addDefault("database.database", "buzzbot");
YML_FILE.addDefault("database.user", "barry");
YML_FILE.addDefault("database.password", "benson");
YML_FILE.addDefault("database.database", "buzzbot");
YML_FILE.addDefault("filter.path.mild", "./mild.txt");
YML_FILE.addDefault("filter.path.moderate", "./moderate.txt");
YML_FILE.addDefault("filter.path.strong", "./strong.txt");
try {
YML_FILE.save();

View File

@@ -0,0 +1,104 @@
package net.nevet5gi.buzzbot;
import net.dv8tion.jda.api.entities.User;
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.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageUpdateEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.nevet5gi.buzzbot.commands.utils.CommandManager;
import net.nevet5gi.buzzbot.database.SqlDB;
import net.nevet5gi.buzzbot.functions.ProfanityFilter;
import net.nevet5gi.buzzbot.objects.GuildData;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
public class Listener extends ListenerAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(Listener.class);
private final CommandManager manager = new CommandManager();
private static final ProfanityFilter profanityFilter = new ProfanityFilter();
public static void startProfanityFilter() {
profanityFilter.buildDictionaries();
}
@Override
public void onReady(@Nonnull ReadyEvent event) {
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
public void onGuildMessageReceived(@Nonnull GuildMessageReceivedEvent event) {
User user = event.getAuthor();
String raw = event.getMessage().getContentRaw();
if (user.isBot() || event.isWebhookMessage()) {
return;
}
if (profanityFilter.containsProfanity(raw, "strong")) {
SqlDB sql = new SqlDB();
int profanityLevel = sql.getGuildData(event.getGuild().getIdLong()).getProfanityLevel();
sql.close();
switch (profanityLevel) {
case 1 -> {
if (profanityFilter.containsProfanity(raw, "mild")) profanityFilter.handle(event);
}
case 2 -> {
if (profanityFilter.containsProfanity(raw, "moderate")) profanityFilter.handle(event);
}
case 3 -> profanityFilter.handle(event);
}
}
if (raw.startsWith(Config.getConfig().getString("bot.prefix"))) {
manager.handle(event);
}
}
@Override
public void onGuildMessageUpdate(@Nonnull GuildMessageUpdateEvent event) {
String raw = event.getMessage().getContentRaw();
if (profanityFilter.containsProfanity(raw, "strong")) {
SqlDB sql = new SqlDB();
int profanityLevel = sql.getGuildData(event.getGuild().getIdLong()).getProfanityLevel();
sql.close();
switch (profanityLevel) {
case 1:
if (profanityFilter.containsProfanity(raw, "mild")) profanityFilter.handleEdit(event);
break;
case 2:
if (profanityFilter.containsProfanity(raw, "moderate")) profanityFilter.handleEdit(event);
break;
case 3:
profanityFilter.handleEdit(event);
break;
}
}
}
@Override
public void onSlashCommand(@NotNull SlashCommandEvent event) {
manager.handle(event);
}
}

View File

@@ -0,0 +1,76 @@
package net.nevet5gi.buzzbot;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.utils.cache.CacheFlag;
import net.nevet5gi.buzzbot.database.SqlDB;
import net.nevet5gi.buzzbot.modules.ModuleLoader;
import net.nevet5gi.buzzbot.objects.BanData;
import javax.security.auth.login.LoginException;
import java.sql.Date;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.EnumSet;
public class Test {
private static JDA jda;
public static void main(String[] args) {
Config.loadConfig();
//initJda();
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();
}
private static void initJda() {
try {
jda = JDABuilder.createDefault(Config.getConfig().getString("bot.token"))
.disableCache(EnumSet.of(
CacheFlag.CLIENT_STATUS,
CacheFlag.ACTIVITY,
CacheFlag.EMOTE
))
.enableCache(CacheFlag.VOICE_STATE)
.addEventListeners(new Listener())
.build();
} catch (LoginException e) {
e.printStackTrace();
jda = null;
}
}
private static void sqlTest() {
SqlDB db = new SqlDB();
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.close();
SqlDB db2 = new SqlDB();
BanData qban = db2.queryBan(972924565361695745L, "masterbanlist");
db2.close();
System.out.println(qban.getUserName());
System.out.println(qban.getDate());
}
}

View File

@@ -0,0 +1,100 @@
package net.nevet5gi.buzzbot.commands;
import net.nevet5gi.buzzbot.BuzzBot;
import net.nevet5gi.buzzbot.commands.utils.CommandContext;
import net.nevet5gi.buzzbot.commands.utils.ICommand;
import net.nevet5gi.buzzbot.database.SqlDB;
import net.nevet5gi.buzzbot.objects.BanData;
import java.util.List;
public class BanCmd implements ICommand {
@Override
public void handle(CommandContext ctx) {
//TODO Add checks for commands so they dont break the bot
//TODO Get username and discriminator of person banned and mod
//TODO DM Person who was banned with info about ban
//TODO Make bans able to be modified by original banner only
List<String> args = ctx.getArgs();
if (args.size() < 3) {
ctx.getChannel().sendMessage("Not enough arguments, please try again").queue();
return;
}
BanData ban = new BanData();
if (args.get(0).contains("<@")) {
ban.setUserId(Long.parseLong(args.get(0).replace("<","").replace("@","").replace("&","").replace(">","")));
} else {
ban.setUserId(Long.parseLong(args.get(0)));
}
if (args.get(1).contains("perm")) {
ban.setBanLength(0);
ban.setBanType(true);
} else if (args.get(1).contains("h")) {
ban.setBanLength(Integer.parseInt(args.get(1).replace("h","")));
ban.setBanType(false);
} else if (args.get(1).contains("d")) {
ban.setBanLength(Integer.parseInt(args.get(1).replace("d","")) * 24);
ban.setBanType(false);
} else if (args.get(1).contains("w")) {
ban.setBanLength(Integer.parseInt(args.get(1).replace("w","")) * 24 * 7);
ban.setBanType(false);
} else if (args.get(1).contains("m")) {
ban.setBanLength(Integer.parseInt(args.get(1).replace("m", "")) * 24 * 30);
ban.setBanType(false);
} else if (args.get(1).contains("y")) {
ban.setBanLength(Integer.parseInt(args.get(1).replace("y","")) * 24 * 365);
ban.setBanType(false);
} else {
ctx.getChannel().sendMessage("Invalid time argument, please try again").queue();
return;
}
StringBuilder sb = new StringBuilder();
if (args.size() >= 2) {
for (int i = 2; i < args.size(); i++) {
sb.append(args.get(i));
sb.append(" ");
}
}
ban.setReason(sb.toString().trim());
if (ban.getBanLength() == 0) {
ctx.getChannel().sendMessage("<@" + ctx.getMessage().getAuthor().getId() + "> permanently banned <@" + ban.getUserId() + ">. Reason: " + ban.getReason()).queue();
} else {
ctx.getChannel().sendMessage("<@" + ctx.getMessage().getAuthor().getId() + "> banned <@" + ban.getUserId() + "> for " + ban.getBanLength() + " hours. Reason: " + ban.getReason()).queue();
}
BuzzBot.jda.retrieveUserById(ban.getUserId()).queue(user -> { ban.setUserName(user.getName()); });
ban.setModId(ctx.getMessage().getAuthor().getIdLong());
ban.setModName(ctx.getMessage().getAuthor().getName());
ban.setServerId(ctx.getGuild().getIdLong());
ban.setServerName(ctx.getGuild().getName());
SqlDB sql = new SqlDB();
sql.insertBan(ban, "master_ban_record");
sql.close();
//ctx.getEvent().getGuild().ban(cmdf, 1 , "").submit();
//ctx.getMessage().reply("yes ban");
}
@Override
public String getName() {
return "ban";
}
@Override
public int getPermissionLevel() {
return 3;
}
@Override
public String getHelp() {
return "Bans the specified user";
}
}

View File

@@ -0,0 +1,77 @@
package net.nevet5gi.buzzbot.commands;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.nevet5gi.buzzbot.Config;
import net.nevet5gi.buzzbot.commands.utils.CommandContext;
import net.nevet5gi.buzzbot.commands.utils.ICommand;
import net.nevet5gi.buzzbot.commands.utils.ISlashCommand;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class BeeCmd implements ICommand, ISlashCommand {
public static String url;
@Override
public void handle(CommandContext ctx) {
try { getHttpConnection(); } catch (IOException | InterruptedException e) { e.printStackTrace(); }
EmbedBuilder eb = new EmbedBuilder();
eb.setImage(url.replace("\"",""));
ctx.getChannel().sendMessageEmbeds(eb.build()).queue();
}
@Override
public String getName() {
return "bee";
}
@Override
public String getHelp() {
return "Sends a picture of a bee!\n" +
"Usage: `" + Config.getConfig().getString("bot.prefix") + "bee`";
}
public static void getHttpConnection() throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.GET()
.header("accept", "application/json")
.uri(URI.create("https://api.nevets.tech/bee"))
.build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenApply(BeeCmd::parse)
.join();
}
public static String parse(String response) {
JsonElement je = new Gson().fromJson(response, JsonElement.class);
url = je.getAsJsonObject().get("link").toString();
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

@@ -0,0 +1,139 @@
package net.nevet5gi.buzzbot.commands;
import net.dv8tion.jda.api.EmbedBuilder;
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.OptionType;
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.commands.utils.*;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class HelpCmd implements ICommand, ISlashCommand {
private final CommandManager manager;
public HelpCmd(CommandManager manager) {
this.manager = manager;
}
@Override
public void handle(CommandContext ctx) {
List<String> args = ctx.getArgs();
TextChannel channel = ctx.getChannel();
if (args.isEmpty()) {
StringBuilder sb = new StringBuilder();
EmbedBuilder eb = new EmbedBuilder();
eb.setTitle("List of Commands");
manager.getCommands().stream().map(ICmdGeneric::getName).forEach(
(it) -> sb.append('`').append(Config.getConfig().getString("bot.prefix")).append(it).append("`\n")
);
eb.addField("", sb.toString(), false);
channel.sendMessageEmbeds(eb.build()).queue();
return;
}
String search = args.get(0);
ICommand command = manager.getCommand(search);
ISlashCommand slashCommand = manager.getSlashCommand(search);
if (command == null && slashCommand == null) {
channel.sendMessage("Nothing found for " + search).queue();
return;
}
channel.sendMessage(command.getHelp()).queue();
}
@Override
public void handleSlash(CommandContext ctx) {
StringBuilder sb = new StringBuilder();
EmbedBuilder eb = new EmbedBuilder();
OptionMapping option = ctx.getSlashEvent().getOption("command");
String cmd = null;
if (option != null) cmd = option.getAsString();
if (cmd == null) {
ICommand command = manager.getCommand(ctx.getSlashEvent().getName());
ISlashCommand slashCommand = manager.getSlashCommand(ctx.getSlashEvent().getName());
if (command == null && slashCommand == null) {
ctx.getSlashEvent().getHook().sendMessage("Nothing found for " + ctx.getSlashEvent()).queue();
return;
}
eb.setTitle("Commands");
manager.getCommands().stream().map(ICmdGeneric::getName).forEach(
(it) -> sb.append('`').append(Config.getConfig().getString("bot.prefix")).append(it).append("`\n")
);
eb.addField("", sb.toString(), false);
} else {
ICommand scmd = manager.getCommand(cmd);
if (scmd != null) {
eb.setTitle(scmd.getName());
eb.addField("", scmd.getHelp(), false);
} else {
eb.setTitle("Error");
eb.addField("", "Unknown command, run `/help` to see a list of available commands", false);
}
}
ctx.getSlashEvent().getHook().sendMessageEmbeds(eb.build()).queue();
}
@Override
public String getName() {
return "help";
}
@Override
public String getDescription() {
return "Lists bot commands";
}
@Override
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())
.addOptions(option);
}
@Override
public String getHelp() {
return "Shows the list of bot commands\n" +
"Usage: `" + Config.getConfig().getString("bot.prefix") + "help [command]`";
}
@Override
public List<String> getAliases() {
return List.of("commands", "cmds", "commandlist");
}
}

View File

@@ -0,0 +1,26 @@
package net.nevet5gi.buzzbot.commands;
import net.nevet5gi.buzzbot.commands.utils.CommandContext;
import net.nevet5gi.buzzbot.commands.utils.ICommand;
public class MuteCmd implements ICommand {
@Override
public void handle(CommandContext ctx) {
ctx.getMessage().reply("This command has not been implemented yet").queue();
}
@Override
public String getName() {
return "mute";
}
@Override
public int getPermissionLevel() {
return 2;
}
@Override
public String getHelp() {
return "Mutes the specified user";
}
}

View File

@@ -0,0 +1,44 @@
package net.nevet5gi.buzzbot.commands;
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.commands.utils.CommandContext;
import net.nevet5gi.buzzbot.commands.utils.ICommand;
import net.nevet5gi.buzzbot.commands.utils.ISlashCommand;
public class PingCmd implements ICommand, ISlashCommand {
@Override
public void handle(CommandContext ctx) {
JDA jda = ctx.getJDA();
jda.getRestPing().queue((ping) -> ctx.getChannel().sendMessageFormat("Rest API Ping: %sms\nWebSocket Ping: %sms", ping, jda.getGatewayPing()).queue());
}
@Override
public String getHelp() {
return "Shows the current ping from the bot to the Discord servers" +
"Usage: `" + Config.getConfig().getString("bot.prefix") + "ping`";
}
@Override
public String getName() {
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

@@ -0,0 +1,51 @@
package net.nevet5gi.buzzbot.commands;
import net.dv8tion.jda.api.entities.IMentionable;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.nevet5gi.buzzbot.commands.utils.CommandContext;
import net.nevet5gi.buzzbot.commands.utils.ICommand;
import net.nevet5gi.buzzbot.commands.utils.ISlashCommand;
public class TestCmd implements ICommand, ISlashCommand {
@Override
public void handle(CommandContext ctx) {
ctx.getMessage().reply("test command").queue();
}
@Override
public void handleSlash(CommandContext ctx) {
long number = ctx.getSlashEvent().getOption("number").getAsLong();
IMentionable member = ctx.getSlashEvent().getOption("mention").getAsMentionable();
boolean testBoolean = ctx.getSlashEvent().getOption("boolean").getAsBoolean();
String commandString = ctx.getSlashEvent().getCommandString();
String content = "number: " + number + ", mention: " + member.getAsMention() + ", boolean: " + testBoolean + ", command string: " + commandString;
ctx.getHook().sendMessage(content).queue();
}
@Override
public String getDescription() {
return "Checks the ping between bot and API";
}
@Override
public CommandData getCommandData() {
return new CommandData(this.getName(), this.getDescription())
.addOption(OptionType.INTEGER, "number", "test number", true)
.addOption(OptionType.USER, "mention", "mentioned member or role", true)
.addOption(OptionType.BOOLEAN, "boolean", "test boolean", true);
}
@Override
public String getName() {
return "test";
}
@Override
public String getHelp() {
return "tests api ping";
}
}

View File

@@ -0,0 +1,46 @@
package net.nevet5gi.buzzbot.commands;
import net.nevet5gi.buzzbot.commands.utils.CommandContext;
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 {
@Override
public void handle(CommandContext ctx) {
// 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
public String getName() {
return "unban";
}
@Override
public int getPermissionLevel() {
return 3;
}
@Override
public String getHelp() {
return "Unbans the specified user";
}
}

View File

@@ -0,0 +1,26 @@
package net.nevet5gi.buzzbot.commands;
import net.nevet5gi.buzzbot.commands.utils.CommandContext;
import net.nevet5gi.buzzbot.commands.utils.ICommand;
public class UnmuteCmd implements ICommand {
@Override
public void handle(CommandContext ctx) {
ctx.getMessage().reply("This command has not been implemented yet").queue();
}
@Override
public String getName() {
return "unmute";
}
@Override
public int getPermissionLevel() {
return 2;
}
@Override
public String getHelp() {
return "Unmutes the specified user";
}
}

View File

@@ -0,0 +1,27 @@
package net.nevet5gi.buzzbot.commands;
import net.nevet5gi.buzzbot.commands.utils.CommandContext;
import net.nevet5gi.buzzbot.commands.utils.ICommand;
public class UnwarnCmd implements ICommand {
//TODO Make this command only work for warns that were given from the same server
@Override
public void handle(CommandContext ctx) {
ctx.getMessage().reply("This command has not been implemented yet").queue();
}
@Override
public String getName() {
return "unwarn";
}
@Override
public int getPermissionLevel() {
return 2;
}
@Override
public String getHelp() {
return "Unwarns the specified user";
}
}

View File

@@ -0,0 +1,65 @@
package net.nevet5gi.buzzbot.commands;
import net.nevet5gi.buzzbot.BuzzBot;
import net.nevet5gi.buzzbot.commands.utils.CommandContext;
import net.nevet5gi.buzzbot.commands.utils.ICommand;
import net.nevet5gi.buzzbot.database.SqlDB;
import net.nevet5gi.buzzbot.objects.WarnData;
import java.util.List;
public class WarnCmd implements ICommand {
@Override
public void handle(CommandContext ctx) {
List<String> args = ctx.getArgs();
if (args.size() < 2) {
ctx.getChannel().sendMessage("Not enough arguments, please try again").queue();
return;
}
WarnData warn = new WarnData();
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
public String getName() {
return "warn";
}
@Override
public int getPermissionLevel() {
return 2;
}
@Override
public String getHelp() {
return "Warns the specified user";
}
}

View File

@@ -1,13 +1,13 @@
package net.nevet5.buzzbot.commands.utils;
package net.nevet5gi.buzzbot.commands.utils;
import me.duncte123.botcommons.commands.ICommandContext;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import java.util.List;
public class CommandContext implements ICommandContext {
private final GuildMessageReceivedEvent event;
private GuildMessageReceivedEvent event;
private SlashCommandEvent slashEvent;
private final List<String> args;
public CommandContext(GuildMessageReceivedEvent event, List<String> args) {
@@ -15,9 +15,9 @@ public class CommandContext implements ICommandContext {
this.args = args;
}
@Override
public Guild getGuild() {
return null;
public CommandContext(SlashCommandEvent slashEvent, List<String> args) {
this.slashEvent = slashEvent;
this.args = args;
}
@Override
@@ -25,6 +25,11 @@ public class CommandContext implements ICommandContext {
return this.event;
}
@Override
public SlashCommandEvent getSlashEvent() {
return this.slashEvent;
}
public List<String> getArgs() {
return this.args;
}

View File

@@ -0,0 +1,182 @@
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.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.nevet5gi.buzzbot.BuzzBot;
import net.nevet5gi.buzzbot.Config;
import net.nevet5gi.buzzbot.commands.*;
import net.nevet5gi.buzzbot.database.SqlDB;
import net.nevet5gi.buzzbot.objects.GuildData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
//TODO Make reload command for modules
public class CommandManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CommandManager.class);
protected final List<ICommand> commands = new ArrayList<>();
protected static List<ISlashCommand> slashList = new ArrayList<>();
public CommandManager() {
//Add to this list in alphabetical order
addCommand(new BanCmd());
addCommand(new BeeCmd());
addCommand(new HelpCmd(this));
addCommand(new MuteCmd());
addCommand(new PingCmd());
addCommand(new SetRoleCmd());
addCommand(new TestCmd());
addCommand(new UnbanCmd());
addCommand(new UnmuteCmd());
addCommand(new UnwarnCmd());
addCommand(new WarnCmd());
//addCommand(new CommandClass());
}
protected void addCommand(ICmdGeneric cmd) {
boolean nameFound = commands.stream().anyMatch(it -> it.getName().equalsIgnoreCase(cmd.getName()));
if (nameFound) {
throw new IllegalArgumentException("A command with this name is already present");
}
if (cmd instanceof ICommand) {
commands.add((ICommand) cmd);
}
if (cmd instanceof ISlashCommand) {
slashList.add(((ISlashCommand) cmd));
}
}
public static void registerSlashCommands() {
if (slashList != null) {
List<CommandData> cmdDataList = new ArrayList<>();
for (ISlashCommand slashCmd : slashList) {
cmdDataList.add(slashCmd.getCommandData());
}
BuzzBot.jda.updateCommands().addCommands(cmdDataList).queue();
}
}
public List<ICommand> getCommands() {
return commands;
}
public List<ISlashCommand> getSlashCommands() {
return slashList;
}
@Nullable
public ICommand getCommand(String search) {
String searchLower = search.toLowerCase();
for (ICommand cmd : commands) {
if (cmd.getName().equals(searchLower) || cmd.getAliases().contains(searchLower)) {
return cmd;
}
}
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
public ISlashCommand getSlashCommand(String search) {
String searchLower = search.toLowerCase();
for (ISlashCommand scmd : slashList) {
if (scmd.getName().equals(searchLower) || scmd.getAliases().contains(searchLower)) {
return scmd;
}
}
return null;
}
public void handle(GuildMessageReceivedEvent event) {
String[] split = event.getMessage().getContentRaw()
.replaceFirst("(?i)" + Pattern.quote(Config.getConfig().getString("bot.prefix")), "")
.split("\\s+");
String invoke = split[0].toLowerCase();
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) {
event.getChannel().sendTyping().queue();
List<String> args = Arrays.asList(split).subList(1, split.length);
CommandContext ctx = new CommandContext(event, args);
cmd.handle(ctx);
}
}
public void handle(SlashCommandEvent event) {
String invoke = event.getName();
ISlashCommand cmd = getSlashCommand(invoke);
if (cmd != null) {
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<>();
CommandContext ctx = new CommandContext(event, args);
cmd.handleSlash(ctx);
}
}
}

View File

@@ -0,0 +1,22 @@
package net.nevet5gi.buzzbot.commands.utils;
import java.util.List;
public interface ICmdGeneric {
String getName();
/**
* @apiNote 0 = default, 1 = helper, 2 = moderator, 3 = admin, 4 = owner
* @return int
*/
default int getPermissionLevel() {
return 0;
}
String getHelp();
default List<String> getAliases(){
return List.of();
}
}

View File

@@ -0,0 +1,7 @@
package net.nevet5gi.buzzbot.commands.utils;
public interface ICommand extends ICmdGeneric {
void handle(CommandContext ctx);
}

View File

@@ -0,0 +1,152 @@
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

@@ -0,0 +1,11 @@
package net.nevet5gi.buzzbot.commands.utils;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
public interface ISlashCommand extends ICmdGeneric {
void handleSlash(CommandContext ctx);
String getDescription();
CommandData getCommandData();
}

View File

@@ -0,0 +1,197 @@
package net.nevet5gi.buzzbot.database;
import net.nevet5gi.buzzbot.Config;
import net.nevet5gi.buzzbot.objects.*;
import java.sql.*;
import java.util.ArrayList;
public class SqlDB {
private Connection connect;
private Statement statement;
private ResultSet resultSet;
public SqlDB() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://" + Config.getConfig().getString("database.url") + "/" + Config.getConfig().getString("database.database"), Config.getConfig().getString("database.user"), Config.getConfig().getString("database.password"));
statement = connect.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
public void insertBan(BanData ban, String table) {
try {
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) {
e.printStackTrace();
}
}
public void insertUnban(long userId, String table) {
}
public void insertMute(MuteData mute, String table) {
try {
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) {
e.printStackTrace();
}
}
public void insertWarn(WarnData warn, String table) {
try {
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) {
e.printStackTrace();
}
}
public BanData queryBan(long userId, String table) {
BanData ban = new BanData();
try {
resultSet = statement.executeQuery("SELECT * FROM " + table + " WHERE userId=" + userId);
while (resultSet.next()) {
ban.setUserId(resultSet.getLong("user_id"));
ban.setUserName(resultSet.getString("user_name"));
ban.setDate(resultSet.getDate("ban_date"));
ban.setTime(resultSet.getTime("ban_time"));
ban.setReason(resultSet.getString("ban_reason"));
ban.setBanType(resultSet.getBoolean("ban_type"));
ban.setBanLength(resultSet.getInt("ban_length"));
ban.setModName(resultSet.getString("mod_name"));
ban.setModId(resultSet.getLong("mod_id"));
ban.setServerName(resultSet.getString("server_name"));
ban.setServerId(resultSet.getLong("server_id"));
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
return ban;
}
public MuteData queryMute(long userId, String table) {
MuteData mute = new MuteData();
try {
resultSet = statement.executeQuery("SELECT * FROM " + table + "WHERE userId=" + userId);
while (resultSet.next()) {
mute.setUserId(resultSet.getLong("user_id"));
mute.setUserName(resultSet.getString("user_name"));
//mute.setDate(resultSet.);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return mute;
}
public WarnData queryWarn(long userId, String table) {
WarnData warn = new WarnData();
try {
resultSet = statement.executeQuery("SELECT * FROM " + table + "WHERE userId=" + userId);
while (resultSet.next()) {
warn.setUserId(resultSet.getLong("user_id"));
warn.setUserName(resultSet.getString("user_name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return warn;
}
public void addGuild(GuildData guild) {
try {
statement.executeUpdate("INSERT INTO guild_settings VALUES ('" + guild.getName() + "', " + guild.getId() + ", '" + guild.getGroup() + "', " + guild.getProfanityLevel() + ", 0, 0, 0, 0)");
} catch (SQLException e) {
e.printStackTrace();
}
}
public GuildData getGuildData(long guildId) {
GuildData guild = new GuildData();
try {
resultSet = statement.executeQuery("SELECT * FROM guild_settings WHERE guild_id=" + guildId);
while (resultSet.next()) {
guild.setName(resultSet.getString("guild_name"));
guild.setId(resultSet.getLong("guild_id"));
guild.setGroup(resultSet.getString("guild_group"));
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) {
e.printStackTrace();
}
return guild;
}
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 {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,109 @@
package net.nevet5gi.buzzbot.functions;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageUpdateEvent;
import net.nevet5gi.buzzbot.Config;
import net.nevet5gi.buzzbot.util.Dictionary;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ProfanityFilter {
private final Dictionary mildDictionary;
private final Dictionary moderateDictionary;
private final Dictionary strongDictionary;
public ProfanityFilter() {
mildDictionary = new Dictionary();
moderateDictionary = new Dictionary();
strongDictionary = new Dictionary();
}
public void handle(GuildMessageReceivedEvent event) {
event.getMessage().delete().queue();
event.getChannel().sendMessage("Hey <@" + event.getAuthor().getId() + ">, no swearing!").queue();
}
public void handleEdit(GuildMessageUpdateEvent event) {
event.getMessage().delete().queue();
event.getChannel().sendMessage("Hey <@" + event.getAuthor().getId() + ">, no swearing!").queue();
}
public void buildDictionaries() {
String mildPath = Config.getConfig().getString("filter.path.mild");
String moderatePath = Config.getConfig().getString("filter.path.moderate");
String strongPath = Config.getConfig().getString("filter.path.strong");
String line;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(mildPath));
while ((line = in.readLine()) != null) {
mildDictionary.addToDictionary(line);
moderateDictionary.addToDictionary(line);
strongDictionary.addToDictionary(line);
}
in = new BufferedReader(new FileReader(moderatePath));
while ((line = in.readLine()) != null) {
moderateDictionary.addToDictionary(line);
strongDictionary.addToDictionary(line);
}
in = new BufferedReader(new FileReader(strongPath));
while ((line = in.readLine()) != null) {
strongDictionary.addToDictionary(line);
}
} catch (FileNotFoundException e) { // FileReader
e.printStackTrace();
} catch (IOException e) { // readLine
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public boolean containsProfanity(String input, String strength) {
Dictionary dictionary = null;
switch (strength) {
case "mild" -> dictionary = mildDictionary;
case "moderate" -> dictionary = moderateDictionary;
case "strong" -> dictionary = strongDictionary;
}
if (dictionary == null) {
dictionary = new Dictionary();
}
input = convert(input);
for (String profanity : dictionary.getDictionary()) {
String pattern = "\\b" + Pattern.quote(profanity) + "\\b";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(input);
if (m.find()) {
return true;
}
}
return false;
}
public String convert(String input) {
return input.toLowerCase()
.replace("@", "a")
.replace("$", "s")
.replace("!", "i")
.replace("(", "c");
}
}

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

@@ -0,0 +1,32 @@
package net.nevet5gi.buzzbot.objects;
import java.sql.Date;
import java.sql.Time;
public class BanData extends DisciplineData {
private boolean banType;
private int banLength;
public BanData() {}
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, reason, modName, modId, serverName, serverId);
this.banType = banType;
this.banLength = banLength;
}
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;
}
}

View File

@@ -0,0 +1,104 @@
package net.nevet5gi.buzzbot.objects;
import java.sql.Date;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalTime;
public class DisciplineData {
private long userId;
private String userName;
private Date date = Date.valueOf(LocalDate.now());
private Time time = Time.valueOf(LocalTime.now());
private String reason;
private String modName;
private long modId;
private String serverName;
private long serverId;
public DisciplineData() {}
public DisciplineData(long userId, String userName, Date date, Time time, String reason, String modName, long modId, String serverName, long serverId) {
this.setUserId(userId);
this.setUserName(userName);
this.setDate(date);
this.setTime(time);
this.setReason(reason);
this.setModName(modName);
this.setModId(modId);
this.setServerName(serverName);
this.setServerId(serverId);
}
public void setUserId(long userId) {
this.userId = userId;
}
public long getUserId() {
return userId;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setDate(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
public void setTime(Time time) {
this.time = time;
}
public Time getTime() {
return time;
}
public void setReason(String reason) {
this.reason = reason;
}
public String getReason() {
return reason;
}
public void setModName(String modName) {
this.modName = modName;
}
public String getModName() {
return modName;
}
public void setModId(long modId) {
this.modId = modId;
}
public long getModId() {
return modId;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public String getServerName() {
return serverName;
}
public void setServerId(long serverId) {
this.serverId = serverId;
}
public long getServerId() {
return serverId;
}
}

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

@@ -0,0 +1,76 @@
package net.nevet5gi.buzzbot.objects;
public class GuildData {
private String name;
private long id;
private String group;
private int profanityLevel;
private long helperId;
private long moderatorId;
private long administratorId;
private long ownerId;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setGroup(String group) {
this.group = group;
}
public String getGroup() {
return group;
}
public void setProfanityLevel(int level) {
this.profanityLevel = level;
}
public int getProfanityLevel() {
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

@@ -0,0 +1,23 @@
package net.nevet5gi.buzzbot.objects;
import java.sql.Date;
import java.sql.Time;
public class MuteData extends DisciplineData {
private int muteLength;
public MuteData() {}
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, reason, modName, modId, serverName, serverId);
this.muteLength = muteLength;
}
public void setMuteLength(int muteLength) {
this.muteLength = muteLength;
}
public int getMuteLength() {
return muteLength;
}
}

View File

@@ -0,0 +1,13 @@
package net.nevet5gi.buzzbot.objects;
import java.sql.Date;
import java.sql.Time;
public class WarnData extends DisciplineData {
public WarnData() {}
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, reason, modName, modId, serverName, serverId);
}
}

View File

@@ -0,0 +1,15 @@
package net.nevet5gi.buzzbot.util;
import java.util.ArrayList;
public class Dictionary {
private final ArrayList<String> dictionary = new ArrayList<>();
public void addToDictionary(String word) {
dictionary.add(word);
}
public ArrayList<String> getDictionary() {
return dictionary;
}
}

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

@@ -0,0 +1,37 @@
package net.nevet5gi.buzzbot.util;
import com.google.gson.Gson;
import net.nevet5gi.buzzbot.objects.DisciplineData;
import java.io.*;
import java.lang.reflect.Type;
public class JsonUtils <T extends DisciplineData> {
T object;
// public void createJson(T object) {
// try {
// Writer writer = new FileWriter("./" + object.getName() + ".json");
//
// GsonBuilder builder = new GsonBuilder();
// builder.setPrettyPrinting();
// Gson gson = builder.create();
// String jsonString = gson.toJson(object);
// writer.write(jsonString);
// writer.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
public T loadJson(String jsonFileName) {
try {
BufferedReader reader = new BufferedReader(new FileReader("./" + jsonFileName + ".json"));
return new Gson().fromJson(reader, (Type) object);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
}

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %-34.-34thread %10.10X{jda.shard} %-15.-15logger{0} %-6level %msg%n</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="STDOUT" />
</root>
</configuration>