An Awesome Clear Command For Your Discord.JS Bot

Gilles Heinesch
DiscordBots
Published in
2 min readJul 20, 2019

What is our goal with this new command?

My goal with this post is, to show you how to program a well structured clear command. At the end it is able to clear a specific amount of messages posted in a Discord textchannel.

What will the command look like when we are done?

?clear <amount of messages that should be deleted>

Example: ?clear 50

Let’s start with programming

First of all, we start with the basic setup of our new command.

With this line of code we get all the content behind the prefix with the commandname. In this case, everything behind ?clear.

Example: If you enter the command in a Discord textchannel ?clear 50 , args will be [ 50 ] (which is an array).

Now, we’ve added a new line which just makes it simpler to read the amount of messages which should be deleted. For this we simply need to join() the array. If you don’t know the function of join() , you can read more here.

2 new lines. The first one checks if the amount parameter is given. If not, the bot (command) throws an error that this parameter is needed to execute this command.

The next one checks if the amount parameter is even a number because an amount can only be an integer (a number) and can’t include letters.

Again 2 new lines. These lines should not be complicated at all. The first one checks if the amount integer is bigger than 100, if yes the bot throws an error. The same for the next line, only that it checks if the integer (amount parameter) is smaller than 1. If you don’t know why the maximum can only be 100; this is due to the Discord API, it only allows a bot application to fetch 100 messages at once. More can be found here.

The first new line fetches all messages. The limit is the above given amount parameter (To revise: This is the number behind the ?clear command). Then we continue to the main function of this command; Bulkdelete. The bot now bulkdeletes all messages that have been fetched.

Be careful! The messages can not be older than 14 days (again due to the Discord API).

Conclusion

I hope I could help you a little bit with your bot and the setup of your clear command. If you have any questions, you can visit our forum for further support!

Photo by Paweł Czerwiński on Unsplash

--

--