A Wonderful Ban Command For Your Discord.js Bot

Gilles Heinesch
DiscordBots
Published in
2 min readFeb 27, 2019

What is our goal with this new command?

Our goal is to program a good and well-developed ban command. It gives you and your moderators the possibility to ban a Discord server member via your bot with a specific reason. All ban details can be posted in a pre-defined Discord channel (Modlog).

What will the command look like when we are done?

?ban <@USER/UserID> <reason for the ban>

Examples:

  • ?ban @Monkeyyy11#0001 Spam
  • ?ban 238590234135101440 Spam

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 ?ban.

Example: If you enter the command in a Discord channel ?ban @Monkeyyy11#0001 Spam , args will be @Monkeyyy11#0001 Spam.

In the second line of code we request the first mention of a Discord user from the message object. If there is an user mention, you will receive the user object of this Discord user.

In the next line we slice the ban reason from our arguments of the command (args in this case).

Here we have a very nice feature that allows your ban command to enter an userID of a Discord server member instead of mentioning him.

First we check if the message contains an user mention, if not; then check if a valid userID has been entered. If not; the client returns an error in form of a Discord channel message. If yes; the client overwrites the uservariable with the new user object.

3 different checks have been added here before we continue with further code.

The first if, checks if the user variable is the same user object as the message author object.

The next code line checks if the message author hasn’t forgotten to enter a reason for the ban of the Discord user.

The last line that we’ve added, checks if the bot has even enough permissions to ban this Discord user because otherwise the following code that we will cover as next will not work.

With the new code in line 24, we ban the Discord user from the current Discord server where we enter the bot command.

After this, we send a confirmation RichEmbed in the current channel where we entered our command to confirm that the user has been successfully banned.

In the new code that we’ve added, we give your bot the possibility to modlog all details of the ban in a Discord channel of your choice.

Conclusion

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

Photo by Temple Cerulean on Unsplash

--

--