Shutdown Command
As mentioned in the comments, you could create a simple command to shut down your client, which would send the desired message.
Example:
// Async context required to use keyword 'await'
try {
await message.channel.send('Goodbye'); // Send the message
await message.delete(); // Delete the command message
await client.user.setStatus('invisible'); // Mark the client as offline (instead of waiting)
await client.destroy(); // Remove the client instance
} catch(err) {
console.error(err); // Return any errors from rejected promises
}
Webhook
If you wanted the message to be sent when your Node process exits in general for any reason (i.e. client logs out, computer is turned off, CTRL + C, etc.), you could create a Webhook and use it in the process's beforeExit
event.
To create the Webhook, navigate to the options of the channel you want the messages to be sent in. Go to Webhooks, click Create Webhook, customize the options, copy the Webhook URL, and then click Save. In the URL, the ID is the first group of digits only after /webhooks/
, and the token follows the next /
.
Example:
const { id, token } = require('./webhook.json'); // json file with Webhook's ID and token
// const Discord = require('discord.js');
// const client = new Discord.Client();
const webhook = new Discord.WebhookClient(id, token);
process.once('beforeExit', () => {
webhook.send(`${client.user} has gone offline.`)
.catch(console.error);
});
Bonus: You could also use the Webhook in the ready event to send the 'ready' message.
client.once('ready', () => {
webhook.send(`${client.user} is now online.`)
.catch(console.error);
});
EDIT:
The beforeExit
event is not emitted when the Node.js process exits unexpectedly, like when you close the console window. Therefore the only scenarios where you'd find the Webhook option helpful is when your client crashes or you use CTRL
/CMD
+ C
in the console window.
My suggestion would be to stick to a shutdown command. To keep your bot running without proper hosting, you could try a process manager or creating a Windows Service.