Initial Commit

This commit is contained in:
2022-04-23 22:32:58 -04:00
commit 7deb3dabc7
24 changed files with 1715 additions and 0 deletions

View File

@@ -0,0 +1,81 @@
package net.nevet5.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.utils.cache.CacheFlag;
import javax.security.auth.login.LoginException;
import java.util.EnumSet;
public class Bot {
public static JDA jda;
public static void main(String[] args) {
Config.loadConfig();
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();
getActivity();
} catch (LoginException e) {
e.printStackTrace();
}
}
public static void getActivity() {
if (Config.getConfig().getString("bot.activity").equalsIgnoreCase("playing")) {
jda.getPresence().setActivity(Activity.playing(Config.getConfig().getString("bot.action")));
} else if (Config.getConfig().getString("bot.activity").equalsIgnoreCase("watching")) {
jda.getPresence().setActivity(Activity.watching(Config.getConfig().getString("bot.action")));
} else if (Config.getConfig().getString("bot.activity").equalsIgnoreCase("competing")) {
jda.getPresence().setActivity(Activity.competing(Config.getConfig().getString("bot.action")));
} else if (Config.getConfig().getString("bot.activity").equalsIgnoreCase("listening")) {
jda.getPresence().setActivity(Activity.listening(Config.getConfig().getString("bot.action")));
} else if (Config.getConfig().getString("bot.activity").equalsIgnoreCase("debug")) {
jda.getPresence().setActivity(Activity.listening("my prefix " + Config.getConfig().getString("bot.prefix")));
} else {
jda.getPresence().setActivity(Activity.playing("with myself!"));
}
}
// 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();
// }
// }
}

View File

@@ -0,0 +1,46 @@
package net.nevet5.buzzbot;
import org.simpleyaml.configuration.file.YamlFile;
import java.io.IOException;
public class Config {
private static final YamlFile YML_FILE = new YamlFile("./config.yml");
public static void loadConfig() {
YML_FILE.setConfigurationFile("./config.yml");
try {
if (!YML_FILE.exists()) {
System.out.println("Config file not found, creating new one...");
YML_FILE.createNewFile(true);
System.out.println("Config file created!");
// YML_FILE.addDefault("bot.token", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// YML_FILE.addDefault("bot.prefix", "!");
// YML_FILE.set("bot.token", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// YML_FILE.set("bot.prefix", "!");
} else {
System.out.println("Loading Config file...");
YML_FILE.loadWithComments();
System.out.println("Config file loaded!");
}
} catch (final Exception e) {
System.out.println("Error while loading config file!");
e.printStackTrace();
}
YML_FILE.addDefault("bot.token", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
YML_FILE.addDefault("bot.prefix", "!");
YML_FILE.addDefault("bot.activity", "playing");
YML_FILE.addDefault("bot.action", "with myself");
try {
YML_FILE.save();
} catch (IOException e) {
e.printStackTrace();
}
}
public static YamlFile getConfig() {
return YML_FILE;
}
}

View File

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

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

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

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

@@ -0,0 +1,31 @@
package net.nevet5.buzzbot.commands.utils;
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,70 @@
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

@@ -0,0 +1,15 @@
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();
}
}