I'm trying to create a discord bot using the Discord4J api, but when I try to run the app from IntelliJ or CMD, when I exit the app, the bot is still active and in my task manager I can see the active threads created by this app, the only way is to manually end the tasks from task manager.
I followed the steps provided by the official Discord4J wiki Music-Bot-Tutorial, It mentions If you wish to disconnect your bot, click on the Exit button in the console., but this is not happening with my program.
This is the code I am using:
public static void main(String[] args) throws Exception {
DiscordClient client = DiscordClientBuilder.create(BOT_TOKEN).build();
GatewayDiscordClient gateway = client.login().block();
gateway.onDisconnect().block();
}
Gradle only gives this details when I try to stop the application
Execution failed for task ':SampleBot.main()'. Build cancelled while executing task ':SampleBot.main()'
By clicking the "stop" button, you're forcibly closing the application without letting it terminate properly. If the bot still appears online, it is because due to this force close, it never sends a "disconnect" message to Discord. The threads you see are from gradle, which runs as a daemon by default, meaning it is always active to launch the applications faster the next time you use it.
If you want to shut down your bot correctly, you should add some logic in your code by listening for input in the console by example and calling
client.logout().block();.