Add shutdown interrupt signal listener

This way, we can nicely close the API connection and perform general cleanup.
This commit is contained in:
Bea 2022-11-20 03:17:37 +01:00
parent b43b882cab
commit 8b9ce25684
2 changed files with 16 additions and 9 deletions

View File

@ -5,8 +5,8 @@ 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 sun.misc.Signal;
import wtf.beatrice.hidekobot.listeners.MessageListener;
import wtf.beatrice.hidekobot.listeners.MessageLogger;
import wtf.beatrice.hidekobot.listeners.SlashCommandListener;
import wtf.beatrice.hidekobot.utils.Logger;
import wtf.beatrice.hidekobot.utils.SlashCommandsUtil;
@ -15,6 +15,8 @@ import javax.security.auth.login.LoginException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class HidekoBot
{
@ -70,8 +72,8 @@ public class HidekoBot
jda.addEventListener(new MessageListener());
jda.addEventListener(new SlashCommandListener());
// update slash commands
SlashCommandsUtil.updateSlashCommands(jda);
// update slash commands (delayed)
Executors.newSingleThreadScheduledExecutor().schedule(SlashCommandsUtil::updateSlashCommands, 5, TimeUnit.SECONDS);
// set the bot's status
jda.getPresence().setStatus(OnlineStatus.ONLINE);
@ -88,6 +90,9 @@ public class HidekoBot
// print the bot logo.
logger.log("\n\n" + logger.getLogo() + "\nv" + version + " - bot is ready!\n", 2);
// register shutdown interrupt signal listener for proper shutdown.
Signal.handle(new Signal("INT"), signal -> shutdown());
// log the invite-link to console so noob users can just click on it.
logger.log("Bot User ID: " + botUserId, 3);
logger.log("Invite Link: " + standardInviteLink, 4);
@ -98,4 +103,11 @@ public class HidekoBot
return jda;
}
public static void shutdown()
{
logger.log("WARNING! Shutting down!");
jda.shutdown();
System.exit(0);
}
}

View File

@ -111,12 +111,7 @@ public class MessageListener extends ListenerAdapter
channel.sendMessage("Going to sleep! Cya :sparkles:").queue();
Executors.newSingleThreadScheduledExecutor().schedule(() ->
{
logger.log("WARNING! Shutting down!");
HidekoBot.getAPI().shutdown();
System.exit(0);
}, 5, TimeUnit.SECONDS);
Executors.newSingleThreadScheduledExecutor().schedule(HidekoBot::shutdown, 3, TimeUnit.SECONDS);
return;
}