Revamped config system

This commit is contained in:
Steven Tracey 2021-07-23 01:30:17 -04:00
parent bf341dd8d3
commit f4a1a0a918
17 changed files with 313 additions and 144 deletions

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="1.8" />
<bytecodeTargetLevel target="11" />
</component>
</project>

View File

@ -21,5 +21,15 @@
<option name="name" value="maven" />
<option name="url" value="https://m2.dv8tion.net/releases" />
</remote-repository>
<remote-repository>
<option name="id" value="duncte123-jfrog" />
<option name="name" value="duncte123-jfrog" />
<option name="url" value="https://duncte123.jfrog.io/artifactory/maven" />
</remote-repository>
<remote-repository>
<option name="id" value="maven2" />
<option name="name" value="maven2" />
<option name="url" value="https://jitpack.io" />
</remote-repository>
</component>
</project>

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="azul-11" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View File

@ -10,13 +10,20 @@ group 'tech.nevets.lunarbot'
version '1.0'
def jdaVer = '4.3.0_298'
sourceCompatibility = targetCompatibility = 1.8
sourceCompatibility = targetCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
maven {
url "https://m2.dv8tion.net/releases"
}
maven {
name 'duncte123-jfrog'
url 'https://duncte123.jfrog.io/artifactory/maven'
}
maven {
url 'https://jitpack.io'
}
}
dependencies {
@ -24,6 +31,9 @@ dependencies {
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
implementation("net.dv8tion:JDA:$jdaVer")
compile group: 'org.yaml', name: 'snakeyaml', version: '1.27'
implementation group: 'me.duncte123', name: 'botCommons', version: '2.3.8'
implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.4'
implementation 'me.carleslc.Simple-YAML:Simple-Yaml:1.7.2'
}
compileJava.options.encoding = 'UTF-8'

View File

@ -1,2 +0,0 @@
prefix: "!"
botToken: "BOTTOKEN"

View File

@ -7,30 +7,16 @@ import tech.nevets.lunarbot.commands.games.CoinCmd;
import tech.nevets.lunarbot.commands.games.DiceCmd;
import tech.nevets.lunarbot.commands.wiki.InfoCmd;
import tech.nevets.lunarbot.commands.games.PingCmd;
import tech.nevets.lunarbot.config.Config;
import tech.nevets.lunarbot.config.ConfigHandler;
import tech.nevets.lunarbot.config.ConfigUtils;
import tech.nevets.lunarbot.webserver.WebAPI;
import tech.nevets.lunarbot.webserver.WebGenerator;
import java.io.File;
public class Bot {
public static void main(String[] args) throws Exception {
String configPath = ConfigHandler.configPath.toString();
File file = new File(configPath);
Config.loadConfig();
String token = Config.getToken();
if (!file.exists()) {
ConfigUtils.createConfig();
}
ConfigHandler handler = ConfigHandler.getInstance();
Config config = handler.getConfig();
String prefix = config.getPrefix();
String botToken = config.getBotToken();
JDA jda = JDABuilder.createDefault(botToken)
JDA jda = JDABuilder.createDefault(token)
.setActivity(Activity.competing("being the very best"))
.addEventListeners(new InfoCmd())
.addEventListeners(new PingCmd())

View File

@ -0,0 +1,61 @@
package tech.nevets.lunarbot;
import org.simpleyaml.configuration.file.YamlFile;
import java.io.IOException;
public class Config {
private static String prefix;
private static String token;
private static String ownerID;
private static boolean verbose;
public static void loadConfig() {
final YamlFile ymlFile = new YamlFile("config.yml");
try {
if (!ymlFile.exists()) {
System.out.println("Configuration file has been created\n");
ymlFile.createNewFile(true);
} else {
System.out.println("config.yml already exists, loading configuration file...\n");
}
ymlFile.loadWithComments();
} catch (final Exception e) {
e.printStackTrace();
}
System.out.println("Adding default values...");
ymlFile.addDefault("prefix", "!");
ymlFile.addDefault("token", "BotToken122333444455555666666777777788888888999999999");
ymlFile.addDefault("verbose", false);
try {
ymlFile.save();
} catch (
IOException e) {
e.printStackTrace();
}
prefix = ymlFile.getString("prefix");
token = ymlFile.getString("token");
ownerID = ymlFile.getString("owner-id");
verbose = ymlFile.getBoolean("verbose");
}
public static String getPrefix() {
return prefix;
}
public static String getToken() {
return token;
}
public static String getOwnerID() {
return ownerID;
}
public static boolean getVerbose() {
return verbose;
}
}

View File

@ -0,0 +1,18 @@
package tech.nevets.lunarbot;
import net.dv8tion.jda.api.events.ReadyEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
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);
@Override
public void onReady(@Nonnull ReadyEvent event) {
LOGGER.info("{} is ready", event.getJDA().getSelfUser().getAsTag());
}
}

View File

@ -0,0 +1,31 @@
package tech.nevets.lunarbot.commands;
import me.duncte123.botcommons.commands.ICommandContext;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import java.util.List;
public class CommandContext implements ICommandContext {
private final GuildMessageReceivedEvent event;
private final List<String> args;
public CommandContext(GuildMessageReceivedEvent event, List<String> args) {
this.event = event;
this.args = args;
}
@Override
public Guild getGuild() {
return null;
}
@Override
public GuildMessageReceivedEvent getEvent() {
return this.event;
}
public List<String> getArgs() {
return this.args;
}
}

View File

@ -0,0 +1,68 @@
package tech.nevets.lunarbot.commands;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import tech.nevets.lunarbot.Config;
import tech.nevets.lunarbot.commands.games.CoinCmd;
import tech.nevets.lunarbot.commands.games.DiceCmd;
import tech.nevets.lunarbot.commands.games.PingCmd;
import tech.nevets.lunarbot.commands.wiki.InfoCmd;
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() {
addCommand(new CoinCmd());
addCommand(new DiceCmd());
addCommand(new PingCmd);
addCommand(new InfoCmd());
}
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);
}
@Nullable
private 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 prefix = Config.getPrefix();
String[] split = event.getMessage().getContentRaw()
.replaceFirst("(?i)" + Pattern.quote(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

@ -0,0 +1,13 @@
package tech.nevets.lunarbot.commands;
import java.util.List;
public interface ICommand {
void handle(CommandContext ctx);
String getName();
default List<String> getAliases() {
return List.of();
}
}

View File

@ -1,14 +1,43 @@
package tech.nevets.lunarbot.commands.games;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import tech.nevets.lunarbot.config.ConfigHandler;
import tech.nevets.lunarbot.Config;
import tech.nevets.lunarbot.commands.CommandContext;
import tech.nevets.lunarbot.commands.ICommand;
import java.io.FileNotFoundException;
import java.util.Random;
public class CoindCmd implements ICommand {
@Override
public void handle(CommandContext ctx) {
JDA jda = ctx.getJDA();
Random rand = new Random();
int upperbound = 2;
MessageChannel channel = jda.getChannel;
int i = rand.nextInt(upperbound);
if (i == 0) {
channel.sendTyping().queue();
channel.sendMessage("The coin landed on **heads**").queue();
} else {
channel.sendTyping().queue();
channel.sendMessage("The coin landed on **tails**").queue();
}
}
@Override
public String getName() {
return "coinflip";
}
}
/**
public class CoinCmd extends ListenerAdapter {
@Override
public void onMessageReceived(MessageReceivedEvent e) {
@ -16,8 +45,7 @@ public class CoinCmd extends ListenerAdapter {
Message message = e.getMessage();
String content = message.getContentRaw();
String prefix = null;
try { prefix = ConfigHandler.getInstance().getConfig().getPrefix(); } catch (FileNotFoundException fileNotFoundException) { fileNotFoundException.printStackTrace(); }
String prefix = Config.getPrefix();
if (content.equalsIgnoreCase(prefix + "coinflip")) {
Random rand = new Random();
@ -35,4 +63,5 @@ public class CoinCmd extends ListenerAdapter {
System.out.println(i);
}
}
}
}
**/

View File

@ -1,22 +0,0 @@
package tech.nevets.lunarbot.config;
public class Config {
private String prefix;
private String botToken;
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getBotToken() {
return botToken;
}
public void setBotToken(String botToken) {
this.botToken = botToken;
}
}

View File

@ -1,59 +0,0 @@
package tech.nevets.lunarbot.config;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ConfigHandler {
public static final Path configPath = Paths.get("./config.yml");
private static ConfigHandler configHandler;
Config config;
public static ConfigHandler getInstance() throws FileNotFoundException {
return getInstance(configPath);
}
public static ConfigHandler getInstance(Path configPath) throws FileNotFoundException {
if (configHandler == null) {
configHandler = new ConfigHandler(configPath);
}
return configHandler;
}
private ConfigHandler(Path configPath) throws FileNotFoundException {
this.config = loadConfig(configPath);
}
public Config loadConfig(Path configPath) throws FileNotFoundException {
Constructor constructor = new Constructor(Config.class);
Yaml yaml = new Yaml(constructor);
return yaml.load(new FileInputStream(configPath.toFile()));
}
public void dumpConfig() throws IllegalArgumentException, IllegalAccessException, IOException {
dumpConfig(this.config, this.configPath);
}
public void dumpConfig(Config config, Path configPath) throws IllegalArgumentException, IllegalAccessException, IOException {
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setPrettyFlow(true);
Yaml yml = new Yaml(options);
yml.dump(config, new FileWriter(configPath.toFile()));
}
public Config getConfig() {
return this.config;
}
}

View File

@ -1,36 +0,0 @@
package tech.nevets.lunarbot.config;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class ConfigUtils {
public static void createConfig() {
System.out.println("Attemption to create file...");
try {
File config = new File("config.yml");
if (config.createNewFile()) {
System.out.println(config.getName() + " has been successfully created!");
} else {
System.out.println(config.getName() + " already exists!");
}
} catch (IOException e) {
System.out.println("An error has occurred");
e.printStackTrace();
}
try {
FileWriter writer = new FileWriter("config.yml");
writer.write("prefix: \"!\"\nbotToken: \"BOTTOKEN\"");
writer.close();
System.out.println("Successfully wrote to config.yml");
} catch (IOException e) {
System.out.println("An error occurred while writing to config.yml");
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,50 @@
package tech.nevets.lunarbot.gui;
import tech.nevets.lunarbot.gui.commands.KillBot;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI implements ActionListener {
public GUI() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JLabel lb1 = new JLabel("Set Bot token Here");
JButton bt1 = new JButton("Kill Bot and close App");
JButton bt2 = new JButton("Set Bot Token");
JFormattedTextField field1 = new JFormattedTextField("");
panel.setBorder(BorderFactory.createEmptyBorder(200,830,200,830));
panel.setLayout(new GridLayout(0,1));
panel.add(lb1);
panel.add(field1);
panel.add(bt2);
panel.add(bt1);
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("GUI");
frame.pack();
frame.setVisible(true);
bt1.addActionListener(new KillBot());
}
public static void GUI(String[] args) {
new GUI();
}
@Override
public void actionPerformed(ActionEvent e) {
}
}

View File

@ -0,0 +1,12 @@
package tech.nevets.lunarbot.gui.commands;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class KillBot implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}