Discord.js – Deleting messages from a channel!

Discord.js – Deleting messages from a channel!

So you want a command that deletes XX messages from the current channel? Let’s try and get that command build!
Note! This article assumes that you have a running bot and a simple command handler. I will be showing a simple command that deletes up to 100 (Discords API limit) messages, but not older than 14 days (again Discord API limit).

const Prefix = '!'; //This is the prefix the message has to start with, to invoke the command
if (message.content.startsWith(Prefix + 'delete')) { //the prefix + 'delete' states that the command is: delete

Basically we want to say: !delete 25, and that should delete the latest 25 messages in that channel.
No we need to get that number into a variable, and that’s simple enough:

const args = message.content.split(' ').slice(1); //Splits the message into pieces, and removes the first (command) from there
const amount = args.join(' '); //We want the argument (number) to be the amount, so we do a join on the arg.

Next we want to check that the user did in fact specify a second argument, and that that argument is a numeric value:

if (!amount) return message.reply(`You need to specify an amount of messages to delete!`); // If amount isn't set, then return a message to the channel.
if (isNaN(amount)) return message.reply(`You need to use a numeric value to use this command`); //isNaN is a JavaScript function and stand for is Not-a-Number

Further more, we need to check if the number provided is over the Discord API limit:

if (amount > 100) return message.reply(`You can't delete more than 100 messages in this function`);

Right, checks are done and we can now start deleting messages from the current channel: (Note the use of await, so this needs to be in an async function!)

await message.channel.messages.fetch({ limit: amount }) //Specify the limit (amount) of messages to fetch.
    .then(messages => { // Fetches the messages from the current channel
        message.channel.bulkDelete(messages); // bulkDelete is a function and deletes all messages that have been fetched and are not older than 14 days (due to the Discord API)

Congratulations! You now have the command: !delete that can delete up to 100 messages from the channel, that aren’t older than 14 days.
This command can be built upon and in a future post I will give a more in-depth use of this feature.

Leave a Reply

Your email address will not be published. Required fields are marked *