[16.2k Lines] Moved the DiscordBot from the old repository on GitLab to here and cleaned up the code a bit

This commit is contained in:
Rainnny7 2021-02-19 16:29:56 -05:00
parent bf098e4e0f
commit 3e717de947
14 changed files with 255 additions and 223 deletions

@ -40,13 +40,8 @@ public class AccountRepository extends MySQLRepository {
/**
* Construct a {@link AccountModel} from the given parameters
* @param accountId the account id
* @param uuid the uuid
* @param name the name
* @param resultSet the result set
* @param ipAddress the ip address
* @param encryptedIpAddress the encrypted ip address
* @param lastLogin the last login
* @return the account
*/
private AccountModel constructAccount(UUID uuid, ResultSet resultSet) {

@ -1,7 +1,7 @@
dependencies {
implementation(project(":core"))
implementation("com.jagrosh:jda-utilities:3.0.5")
implementation("net.dv8tion:JDA:4.2.0_228")
implementation("com.jagrosh:jda-utilities:3.0.5")
}
val jar by tasks.getting(Jar::class) {

@ -0,0 +1,28 @@
package zone.themcgamer.discordbot;
import java.util.Calendar;
/**
* @author Nicholas
*/
public class BotConstants {
public static final String TOKEN = "ODA5NjMxMzcxNzg1Nzk3NjMz.YCX5-Q.t4S8qOmhAc98DKKw9rBsPNv82xM";
public static final String PREFIX = ".";
public static final String OWNER_ID = "504069946528104471"; // Joel
public static final String[] BOT_ADMINS = new String[] {
"758733013579595836", // Nicholas
"504147739131641857" // Braydon
};
// Guilds
public static final String MAIN_GUILD_ID = "764609803459756093";
public static final String TEAM_GUILD_ID = "796582717956423760";
public static final String TEST_GUILD_ID = "811044415211700234";
// Default Lines
public static final String COPYRIGHT = "© McGamerZone - " + Calendar.getInstance().get(Calendar.YEAR);
// Channels
public static final String SUGGESTIONS = "811048367412215851"; // TODO: 2/15/2021 Change this to the main guild's suggestions channel when the bot is on the main guild.
}

@ -1,60 +1,57 @@
package zone.themcgamer.discordbot;
import com.jagrosh.jdautilities.command.CommandClientBuilder;
import com.jagrosh.jdautilities.commons.waiter.EventWaiter;
import lombok.Getter;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.requests.GatewayIntent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import zone.themcgamer.discordbot.commands.BotStatusCommand;
import zone.themcgamer.discordbot.command.impl.SetActivityCommand;
import zone.themcgamer.discordbot.command.impl.SuggestCommand;
import javax.security.auth.login.LoginException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@Getter
public class MGZBot {
@Getter private static MGZBot instance;
private static final Logger LOG = LoggerFactory.getLogger(MGZBot.class);
private JDA jda;
@Getter private static JDA jda;
@Getter private static CommandClientBuilder commandClientBuilder;
@Getter private static EventWaiter eventWaiter;
@Getter private static ScheduledExecutorService executorService;
public static void main(String[] args) {
public MGZBot() {
instance = this;
long time = System.currentTimeMillis();
eventWaiter = new EventWaiter();
commandClientBuilder = new CommandClientBuilder();
commandClientBuilder.setPrefix(".");
CommandClientBuilder commandClientBuilder = new CommandClientBuilder();
commandClientBuilder.setPrefix(BotConstants.PREFIX);
commandClientBuilder.setActivity(Activity.playing("McGamerZone"));
commandClientBuilder.setStatus(OnlineStatus.DO_NOT_DISTURB);
commandClientBuilder.setOwnerId("504069946528104471");
commandClientBuilder.setCoOwnerIds("504147739131641857");
commandClientBuilder.setEmojis("<:success:789354594651209738>", "<:warning:789354594877964324>", "<:error:789354595003793408>");
commandClientBuilder.setAlternativePrefix("/");
commandClientBuilder.setStatus(OnlineStatus.ONLINE);
commandClientBuilder.setOwnerId(BotConstants.OWNER_ID);
for (String botAdmin : BotConstants.BOT_ADMINS)
commandClientBuilder.setCoOwnerIds(botAdmin);
commandClientBuilder.useHelpBuilder(false);
commandClientBuilder.addCommand(new BotStatusCommand(eventWaiter));
executorService = Executors.newScheduledThreadPool(10);
commandClientBuilder.addCommand(new SuggestCommand());
commandClientBuilder.addCommand(new SetActivityCommand());
try {
jda = JDABuilder.createDefault("ODA5NjMxMzcxNzg1Nzk3NjMz.YCX5-Q.t4S8qOmhAc98DKKw9rBsPNv82xM")
.setCallbackPool(getExecutorService())
.setActivity(Activity.playing("loading..."))
jda = JDABuilder.createDefault(BotConstants.TOKEN)
.setCallbackPool(Executors.newScheduledThreadPool(10))
.setActivity(Activity.playing("Booting up..."))
.setStatus(OnlineStatus.IDLE)
.enableIntents(GatewayIntent.GUILD_MEMBERS, GatewayIntent.GUILD_EMOJIS)
.addEventListeners(eventWaiter,
commandClientBuilder.build())
.addEventListeners(commandClientBuilder.build())
.build();
} catch (LoginException e) {
e.printStackTrace();
jda.awaitReady();
} catch (LoginException | InterruptedException ex) {
ex.printStackTrace();
}
System.out.println("Done (" + (System.currentTimeMillis() - time) + ")! For help, type \"help\" or \"?\"\n");
System.out.println("Done (" + (System.currentTimeMillis() - time) + "ms)!");
}
public static void main(String[] args) {
new MGZBot();
}
}

@ -0,0 +1,35 @@
package zone.themcgamer.discordbot.command;
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
import zone.themcgamer.discordbot.BotConstants;
import zone.themcgamer.discordbot.guild.Guild;
import zone.themcgamer.discordbot.utilities.GuildUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
/**
* @author Nicholas
*/
public abstract class BaseCommand extends Command {
protected List<Guild> guilds; // The guilds the command can be executed in
@Override
protected void execute(CommandEvent event) {
if (!guilds.contains(GuildUtils.getGuildFromId(event.getGuild().getId())))
return;
List<String> args = new ArrayList<>();
if (event.getArgs() != null && event.getArgs().length() > 0) {
String[] split = event.getMessage().getContentRaw()
.replaceFirst("(?i)" + Pattern.quote(BotConstants.PREFIX), "")
.split("\\s+");
args = Arrays.asList(split);
}
execute(event, args);
}
protected abstract void execute(CommandEvent event, List<String> args);
}

@ -0,0 +1,47 @@
package zone.themcgamer.discordbot.command.impl;
import com.jagrosh.jdautilities.command.CommandEvent;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Activity;
import zone.themcgamer.discordbot.BotConstants;
import zone.themcgamer.discordbot.MGZBot;
import zone.themcgamer.discordbot.command.BaseCommand;
import zone.themcgamer.discordbot.guild.Guild;
import zone.themcgamer.discordbot.utilities.EmbedUtils;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Nicholas
*/
public class SetActivityCommand extends BaseCommand {
public SetActivityCommand() {
name = "setactivity";
help = "Set the bot activity.";
arguments = "<message>";
userPermissions = new Permission[] { Permission.ADMINISTRATOR };
guildOnly = true;
guilds = Arrays.asList(Guild.MAIN, Guild.TEAM, Guild.TEST);
}
@Override
protected void execute(CommandEvent event, List<String> args) {
if (args.size() < 1) {
event.getChannel().sendMessage(EmbedUtils.errorEmbed()
.appendDescription("Usage: " + BotConstants.PREFIX + name + " " + arguments)
.build()
).queue();
return;
}
String activity = args.stream().skip(1).collect(Collectors.joining(" "));
MGZBot.getInstance().getJda().getPresence().setActivity(Activity.playing(activity));
event.getChannel().sendMessage(EmbedUtils.successEmbed()
.setThumbnail(event.getAuthor().getAvatarUrl())
.setTitle("Activity updated!")
.appendDescription(event.getAuthor().getAsTag() + " updated the bot activity to \"" + activity + "\".")
.build()
).queue();
}
}

@ -0,0 +1,57 @@
package zone.themcgamer.discordbot.command.impl;
import com.jagrosh.jdautilities.command.CommandEvent;
import net.dv8tion.jda.api.entities.TextChannel;
import zone.themcgamer.discordbot.BotConstants;
import zone.themcgamer.discordbot.MGZBot;
import zone.themcgamer.discordbot.command.BaseCommand;
import zone.themcgamer.discordbot.guild.Guild;
import zone.themcgamer.discordbot.utilities.EmbedUtils;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Nicholas
*/
public class SuggestCommand extends BaseCommand {
public SuggestCommand() {
name = "suggest";
help = "Share a suggestion!";
arguments = "<suggestion>";
guildOnly = true;
guilds = Collections.singletonList(Guild.TEST); // TODO: 2/15/2021 Update this to MAIN whenever the bot is on the main guild.
}
@Override
protected void execute(CommandEvent event, List<String> args) {
if (args.size() < 1) {
event.getChannel().sendMessage(EmbedUtils.errorEmbed()
.appendDescription("Usage: " + BotConstants.PREFIX + name + " " + arguments)
.build()
).queue();
return;
}
TextChannel channel = MGZBot.getInstance().getJda().getTextChannelById(BotConstants.SUGGESTIONS);
if (channel == null)
return;
String suggestion = args.stream().skip(1).collect(Collectors.joining(" "));
if (suggestion.length() < 120) {
event.getChannel().sendMessage(EmbedUtils.errorEmbed()
.appendDescription("Your suggestion is too short. Suggestions must be at least 120 characters.")
.build()
).queue();
return;
}
channel.sendMessage(EmbedUtils.defaultEmbed()
.setThumbnail(event.getAuthor().getAvatarUrl())
.setTitle(event.getAuthor().getAsTag() + " has a suggestion!")
.appendDescription(suggestion)
.build()
).queue(message -> {
message.addReaction("").queue();
message.addReaction("").queue();
});
}
}

@ -1,45 +0,0 @@
package zone.themcgamer.discordbot.commands;
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
import com.jagrosh.jdautilities.doc.standard.CommandInfo;
import com.jagrosh.jdautilities.doc.standard.Error;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import java.util.List;
import java.util.UUID;
@CommandInfo(
name = {"account", "profile"},
usage = "<name>",
description = "View your own account")
@Error(prefix = "Account » ",
value = "An error occured in this command, please contact an administrator.")
public class AccountCommand extends Command {
@Override
protected void execute(CommandEvent commandEvent) {
Message message = commandEvent.getMessage();
String[] args = message.getContentDisplay().split(" ");
UUID player;
List<Member> mentioned = message.getMentionedMembers();
if (args.length > 1) {
Member target = mentioned.get(0);
//(!mentioned.isEmpty()) ? mentioned.get(0) : args[0];
//TODO check if account is linked
player = UUID.randomUUID(); //"SET THE UUID";
} else {
//TODO your own account if you did not have more than 1 args.
player = UUID.randomUUID(); //"YOUR OWN UUID";
}
//TODO sent the message with player information
}
}

@ -1,53 +0,0 @@
package zone.themcgamer.discordbot.commands;
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
import com.jagrosh.jdautilities.commons.waiter.EventWaiter;
import com.sun.management.OperatingSystemMXBean;
import net.dv8tion.jda.api.EmbedBuilder;
import java.awt.*;
import java.lang.management.ManagementFactory;
import java.text.DecimalFormat;
import java.time.Instant;
import java.util.Date;
public class BotStatusCommand extends Command {
public BotStatusCommand(EventWaiter waiter) {
this.name = "botstatus";
//this.aliases = new String[]{"bot"};
this.help = "view status of thee bot.";
this.ownerCommand = true;
this.guildOnly = false;
this.category = new Category("Administration");
}
@Override
protected void execute(CommandEvent commandEvent) {
String title = ":information_source: Stats of **"+ commandEvent.getJDA().getSelfUser().getName()+"**:";
String os = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getName();
String arch = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getArch();
String version = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getVersion();
os = os+" "+arch+" "+version;
int cpus = Runtime.getRuntime().availableProcessors();
String processCpuLoad = new DecimalFormat("###.###%").format(ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getProcessCpuLoad());
String systemCpuLoad = new DecimalFormat("###.###%").format(ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getSystemCpuLoad());
long ramUsed = ((Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()) / (1024 * 1024));
EmbedBuilder builder = new EmbedBuilder();
builder.setTitle(title);
builder.addField(":desktop: OS:", os, true);
builder.addField(":computer: RAM usage:", ramUsed+"MB", true);
builder.addField(":gear: CPU usage:", processCpuLoad + "/" + systemCpuLoad + " (" + cpus + " Cores)", true);
builder.addField(":map: Guilds:", "" + commandEvent.getJDA().getGuilds().size() , true);
builder.addField(":speech_balloon: Text Channels:", "" + commandEvent.getJDA().getTextChannels().size(), true);
builder.addField(":speaker: Voice Channels:", "" + commandEvent.getJDA().getVoiceChannels().size(), true);
builder.addField(":bust_in_silhouette: Users:", "" + commandEvent.getJDA().getUsers().size(), true);
builder.setColor(Color.RED);
builder.setFooter("© McGamerZone - " + Date.from(Instant.now()).getYear(), commandEvent.getJDA().getSelfUser().getEffectiveAvatarUrl());
commandEvent.getChannel().sendMessage(builder.build()).queue();
}
}

@ -1,53 +0,0 @@
package zone.themcgamer.discordbot.commands;
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
import com.jagrosh.jdautilities.commons.waiter.EventWaiter;
import com.sun.management.OperatingSystemMXBean;
import net.dv8tion.jda.api.EmbedBuilder;
import java.awt.*;
import java.lang.management.ManagementFactory;
import java.text.DecimalFormat;
import java.time.Instant;
import java.util.Date;
public class StatusCommand extends Command {
public StatusCommand(EventWaiter waiter) {
this.name = "setstatus";
//this.aliases = new String[]{"bot"};
this.help = "view status of thee bot.";
this.ownerCommand = true;
this.guildOnly = false;
this.category = new Category("Administration");
}
@Override
protected void execute(CommandEvent commandEvent) {
String title = ":information_source: Stats of **"+ commandEvent.getJDA().getSelfUser().getName()+"**:";
String os = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getName();
String arch = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getArch();
String version = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getVersion();
os = os+" "+arch+" "+version;
int cpus = Runtime.getRuntime().availableProcessors();
String processCpuLoad = new DecimalFormat("###.###%").format(ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getProcessCpuLoad());
String systemCpuLoad = new DecimalFormat("###.###%").format(ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class).getSystemCpuLoad());
long ramUsed = ((Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()) / (1024 * 1024));
EmbedBuilder builder = new EmbedBuilder();
builder.setTitle(title);
builder.addField(":desktop: OS:", os, true);
builder.addField(":computer: RAM usage:", ramUsed+"MB", true);
builder.addField(":gear: CPU usage:", processCpuLoad + "/" + systemCpuLoad + " (" + cpus + " Cores)", true);
builder.addField(":map: Guilds:", "" + commandEvent.getJDA().getGuilds().size() , true);
builder.addField(":speech_balloon: Text Channels:", "" + commandEvent.getJDA().getTextChannels().size(), true);
builder.addField(":speaker: Voice Channels:", "" + commandEvent.getJDA().getVoiceChannels().size(), true);
builder.addField(":bust_in_silhouette: Users:", "" + commandEvent.getJDA().getUsers().size(), true);
builder.setColor(Color.RED);
builder.setFooter("© McGamerZone - " + Date.from(Instant.now()).getYear(), commandEvent.getJDA().getSelfUser().getEffectiveAvatarUrl());
commandEvent.getChannel().sendMessage(builder.build()).queue();
}
}

@ -1,35 +0,0 @@
package zone.themcgamer.discordbot.commands;
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
import com.jagrosh.jdautilities.doc.standard.CommandInfo;
import com.jagrosh.jdautilities.doc.standard.Error;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@CommandInfo(
name = {"mycommand", "coolcommand"},
description = "Use this command if you are cool! B)",
requirements = {"The bot has all necessary permissions."})
@Error(
prefix = "Test »",
value = "Rip this command had an error.",
response = "Invalid page number")
public class Test extends Command {
@Override
protected void execute(CommandEvent commandEvent) {
}
private OkHttpClient clientWithApiKey(String apiKey) {
return new OkHttpClient.Builder()
.addInterceptor(chain -> {
Request originalRequest = chain.request();
HttpUrl newUrl = originalRequest.url().newBuilder()
.addQueryParameter("key", apiKey).build();
Request request = originalRequest.newBuilder().url(newUrl).build();
return chain.proceed(request);
}).build();
}
}

@ -0,0 +1,8 @@
package zone.themcgamer.discordbot.guild;
/**
* @author Nicholas
*/
public enum Guild {
MAIN, TEAM, TEST
}

@ -0,0 +1,30 @@
package zone.themcgamer.discordbot.utilities;
import net.dv8tion.jda.api.EmbedBuilder;
import zone.themcgamer.discordbot.BotConstants;
import zone.themcgamer.discordbot.MGZBot;
import java.awt.*;
import java.time.LocalDateTime;
public class EmbedUtils {
public static EmbedBuilder successEmbed() {
return defaultEmbed().setColor(Color.decode("#41bc7f"));
}
public static EmbedBuilder errorEmbed() {
return defaultEmbed().setTitle("Oops!")
.setColor(Color.decode("#d74742"));
}
public static EmbedBuilder warnEmbed() {
return defaultEmbed().setColor(Color.decode("#f85b2e"));
}
public static EmbedBuilder defaultEmbed() {
return new EmbedBuilder()
.setColor(Color.decode("#1DD0D5"))
.setTimestamp(LocalDateTime.now())
.setFooter(BotConstants.COPYRIGHT, MGZBot.getInstance().getJda().getSelfUser().getEffectiveAvatarUrl());
}
}

@ -0,0 +1,21 @@
package zone.themcgamer.discordbot.utilities;
import zone.themcgamer.discordbot.BotConstants;
import zone.themcgamer.discordbot.guild.Guild;
/**
* @author Nicholas
*/
public class GuildUtils {
public static Guild getGuildFromId(String id) {
switch (id) {
case BotConstants.MAIN_GUILD_ID:
return Guild.MAIN;
case BotConstants.TEAM_GUILD_ID:
return Guild.TEAM;
case BotConstants.TEST_GUILD_ID:
return Guild.TEST;
}
return null;
}
}