HidekoBot/src/main/java/wtf/beatrice/hidekobot/HidekoBot.java

204 lines
8.6 KiB
Java
Raw Normal View History

package wtf.beatrice.hidekobot;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
2022-08-26 00:39:55 +02:00
import net.dv8tion.jda.api.OnlineStatus;
2022-08-25 22:18:36 +02:00
import net.dv8tion.jda.api.entities.Activity;
2022-08-25 23:20:51 +02:00
import net.dv8tion.jda.api.requests.GatewayIntent;
import sun.misc.Signal;
import wtf.beatrice.hidekobot.commands.completer.AvatarCommandCompleter;
import wtf.beatrice.hidekobot.commands.message.HelloCommand;
import wtf.beatrice.hidekobot.commands.slash.*;
2022-11-22 23:44:34 +01:00
import wtf.beatrice.hidekobot.datasources.ConfigurationSource;
import wtf.beatrice.hidekobot.datasources.DatabaseSource;
import wtf.beatrice.hidekobot.datasources.PropertiesSource;
import wtf.beatrice.hidekobot.listeners.ButtonInteractionListener;
import wtf.beatrice.hidekobot.listeners.MessageCommandListener;
import wtf.beatrice.hidekobot.listeners.SlashCommandCompletionListener;
2022-11-20 03:01:46 +01:00
import wtf.beatrice.hidekobot.listeners.SlashCommandListener;
2022-11-21 15:02:40 +01:00
import wtf.beatrice.hidekobot.runnables.ExpiredMessageTask;
import wtf.beatrice.hidekobot.runnables.HeartBeatTask;
2022-11-22 00:31:52 +01:00
import wtf.beatrice.hidekobot.util.Logger;
import wtf.beatrice.hidekobot.util.SlashCommandUtil;
import java.io.File;
2022-11-21 12:19:35 +01:00
import java.time.LocalDateTime;
import java.util.ArrayList;
2022-08-26 20:43:49 +02:00
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class HidekoBot
{
private static JDA jda;
2022-08-25 22:59:47 +02:00
private static final Logger logger = new Logger(HidekoBot.class);
2022-08-25 22:54:08 +02:00
public static void main(String[] args)
{
2022-08-25 22:20:05 +02:00
// load configuration
logger.log("Loading configuration...");
String configFilePath = Cache.getExecPath() + File.separator + "config.yml";
2022-11-22 00:28:33 +01:00
ConfigurationSource configurationSource = new ConfigurationSource(configFilePath);
configurationSource.initConfig();
Cache.setConfigurationSource(configurationSource);
logger.log("Configuration loaded!");
// load properties
logger.log("Loading properties...");
PropertiesSource propertiesSource = new PropertiesSource();
propertiesSource.load();
Cache.setPropertiesSourceInstance(propertiesSource);
logger.log("Properties loaded!");
// check loaded bot token
String botToken = Cache.getBotToken();
if(botToken == null || botToken.isEmpty())
2022-08-25 22:20:05 +02:00
{
logger.log("Invalid bot token!");
shutdown();
2022-08-25 22:20:05 +02:00
return;
}
try
{
2022-08-25 22:37:32 +02:00
// try to create the bot object and authenticate it with discord.
JDABuilder jdaBuilder = JDABuilder.createDefault(botToken);
2022-08-25 23:20:51 +02:00
// enable necessary intents.
jdaBuilder.enableIntents(
GatewayIntent.MESSAGE_CONTENT,
2022-08-25 23:20:51 +02:00
GatewayIntent.DIRECT_MESSAGES,
GatewayIntent.GUILD_MESSAGES
);
2022-08-25 23:20:51 +02:00
jda = jdaBuilder.build().awaitReady();
2022-11-20 06:13:52 +01:00
} catch (Exception e)
{
2022-08-25 22:37:32 +02:00
logger.log(e.getMessage()); // print the error message, omit the stack trace.
shutdown(); // if we failed connecting and authenticating, then quit.
}
2022-08-25 22:37:32 +02:00
2022-11-20 18:11:00 +01:00
// find the bot's user/application id
2022-11-20 16:07:04 +01:00
String botUserId = jda.getSelfUser().getId();
2022-11-21 20:20:11 +01:00
Cache.setBotApplicationId(botUserId);
2022-11-20 18:56:57 +01:00
// store if we have to force refresh commands despite no apparent changes.
2022-11-20 18:54:13 +01:00
boolean forceUpdateCommands = false;
2022-11-20 03:01:46 +01:00
2022-08-26 20:57:23 +02:00
// if there is more than 1 arg, then iterate through them because we have additional things to do.
// we are doing this at the end because we might need the API to be already initialized for some things.
if(args.length > 1) {
List<String> argsList = new ArrayList<>(Arrays.asList(args));
// NOTE: do not replace with enhanced for, since we might need
// to know what position we're at or do further elaboration of the string.
// we were using this for api key parsing in the past.
for(int i = 0; i < argsList.size(); i++)
{
String arg = argsList.get(i);
2022-11-21 20:20:11 +01:00
if(arg.equals("verbose")) Cache.setVerbose(true);
if(arg.equals("refresh")) forceUpdateCommands = true;
}
}
// register slash commands and completers
SlashCommandListener slashCommandListener = new SlashCommandListener();
SlashCommandCompletionListener slashCommandCompletionListener = new SlashCommandCompletionListener();
AvatarCommand avatarCommand = new AvatarCommand();
AvatarCommandCompleter avatarCommandCompleter = new AvatarCommandCompleter(avatarCommand);
slashCommandListener.registerCommand(avatarCommand);
slashCommandCompletionListener.registerCommandCompleter(avatarCommandCompleter);
slashCommandListener.registerCommand(new BotInfoCommand());
slashCommandListener.registerCommand(new ClearCommand());
slashCommandListener.registerCommand(new CoinFlipCommand());
slashCommandListener.registerCommand(new DieCommand());
slashCommandListener.registerCommand(new HelpCommand());
slashCommandListener.registerCommand(new InviteCommand());
slashCommandListener.registerCommand(new PingCommand());
slashCommandListener.registerCommand(new SayCommand());
Cache.setSlashCommandListener(slashCommandListener);
Cache.setSlashCommandCompletionListener(slashCommandCompletionListener);
// register message commands
MessageCommandListener messageCommandListener = new MessageCommandListener();
messageCommandListener.registerCommand(new HelloCommand());
messageCommandListener.registerCommand(new wtf.beatrice.hidekobot.commands.message.InviteCommand());
messageCommandListener.registerCommand(new wtf.beatrice.hidekobot.commands.message.BotInfoCommand());
messageCommandListener.registerCommand(new wtf.beatrice.hidekobot.commands.message.CoinFlipCommand());
messageCommandListener.registerCommand(new wtf.beatrice.hidekobot.commands.message.ClearCommand());
Cache.setMessageCommandListener(messageCommandListener);
2022-11-20 18:54:13 +01:00
// register listeners
jda.addEventListener(messageCommandListener);
jda.addEventListener(slashCommandListener);
jda.addEventListener(slashCommandCompletionListener);
jda.addEventListener(new ButtonInteractionListener());
2022-11-20 18:54:13 +01:00
// update slash commands (delayed)
final boolean finalForceUpdateCommands = forceUpdateCommands;
Executors.newSingleThreadScheduledExecutor().schedule(() -> // todo: try-with-resources
2022-11-21 15:02:40 +01:00
SlashCommandUtil.updateSlashCommands(finalForceUpdateCommands), 1, TimeUnit.SECONDS);
2022-11-20 18:54:13 +01:00
// set the bot's status
jda.getPresence().setStatus(OnlineStatus.ONLINE);
jda.getPresence().setActivity(Activity.playing("Hatsune Miku: Project DIVA"));
// connect to database
logger.log("Connecting to database...");
String dbFilePath = Cache.getExecPath() + File.separator + "db.sqlite"; // in current directory
2022-11-22 00:28:33 +01:00
DatabaseSource databaseSource = new DatabaseSource(dbFilePath);
if(databaseSource.connect() && databaseSource.initDb())
{
logger.log("Database connection initialized!");
2022-11-22 00:28:33 +01:00
Cache.setDatabaseSourceInstance(databaseSource);
// load data here...
logger.log("Database data loaded into memory!");
} else {
logger.log("Error initializing database connection!");
}
// start scheduled runnables
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); // todo: try-with-resources
ExpiredMessageTask expiredMessageTask = new ExpiredMessageTask();
scheduler.scheduleAtFixedRate(expiredMessageTask, 5, 5, TimeUnit.SECONDS); //every 5 seconds
HeartBeatTask heartBeatTask = new HeartBeatTask();
scheduler.scheduleAtFixedRate(heartBeatTask, 10, 30, TimeUnit.SECONDS); //every 30 seconds
2022-11-21 12:19:35 +01:00
// register shutdown interrupt signal listener for proper shutdown.
Signal.handle(new Signal("INT"), signal -> shutdown());
// set startup time.
2022-11-21 20:20:11 +01:00
Cache.setStartupTime(LocalDateTime.now());
2022-08-25 22:54:08 +02:00
// print the bot logo.
2022-11-21 20:20:11 +01:00
logger.log("\n\n" + logger.getLogo() + "\nv" + Cache.getBotVersion() + " - bot is ready!\n", 2);
2022-08-25 22:54:08 +02:00
2022-08-25 22:37:32 +02:00
// log the invite-link to console so noob users can just click on it.
2022-08-26 20:29:10 +02:00
logger.log("Bot User ID: " + botUserId, 3);
2022-11-21 20:20:11 +01:00
logger.log("Invite Link: " + Cache.getInviteUrl(), 4);
2022-08-25 23:20:51 +02:00
}
public static JDA getAPI()
{
return jda;
}
2022-08-25 22:13:39 +02:00
public static void shutdown()
{
logger.log("WARNING! Shutting down!");
if(jda != null) jda.shutdown();
System.exit(0);
}
}