Logo

dev-resources.site

for different kinds of informations.

Creating a Moderation Bot for Discord

Published at
12/6/2024
Categories
discord
javascript
tutorial
learning
Author
leimanisemils
Author
13 person written this
leimanisemils
open
Creating a Moderation Bot for Discord

In this guide, we’ll create a simple moderation bot for Discord using Node.js and the Discord.js library. This bot will include features like banning, muting, and monitoring chat activity.

Creating a Moderation Bot for Discord

In this guide, we’ll create a simple moderation bot for Discord using Node.js and the Discord.js library. This bot will include features like banning, muting, and monitoring chat activity.


Prerequisites

  1. Node.js Installed: Download and install Node.js from nodejs.org.
  2. Discord Account: Ensure you have a Discord account and administrative access to the server where you’ll test the bot.
  3. Basic JavaScript Knowledge: Familiarity with JavaScript basics is recommended.

Step 1: Create a New Discord Bot

  1. Go to the Discord Developer Portal.
  2. Click New Application and give your bot a name.
  3. In the left sidebar, go to Bot and click Add Bot.
  4. Copy the bot’s Token for later use (keep it private).
  5. Under "Privileged Gateway Intents," enable MESSAGE CONTENT INTENT to allow the bot to read messages.

Step 2: Set Up Your Project

  1. Open a terminal and create a new folder for your bot:
   mkdir discord-moderation-bot
   cd discord-moderation-bot
Enter fullscreen mode Exit fullscreen mode
  1. Initialize a new Node.js project:
   npm init -y
Enter fullscreen mode Exit fullscreen mode
  1. Install Discord.js:
   npm install discord.js
Enter fullscreen mode Exit fullscreen mode
  1. Create an index.js file in the folder to hold your bot’s code:
   touch index.js
Enter fullscreen mode Exit fullscreen mode

Step 3: Write the Bot Code

Open index.js in a code editor and add the following code:

1. Import and Configure Discord.js

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.GuildMembers
    ]
});

const TOKEN = 'YOUR_BOT_TOKEN'; // Replace with your bot token
Enter fullscreen mode Exit fullscreen mode

2. Set Up Bot Login and Ready Event

client.once('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.login(TOKEN);
Enter fullscreen mode Exit fullscreen mode

3. Add Moderation Commands

Ban Command

client.on('messageCreate', (message) => {
    if (message.content.startsWith('!ban')) {
        if (!message.member.permissions.has('BanMembers')) {
            return message.reply('You do not have permission to ban members.');
        }

        const member = message.mentions.members.first();
        if (!member) {
            return message.reply('Please mention a user to ban.');
        }

        member.ban()
            .then(() => message.reply(`${member.user.tag} has been banned.`))
            .catch((err) => message.reply('I was unable to ban the member.'));  
    }
});
Enter fullscreen mode Exit fullscreen mode

Mute Command

client.on('messageCreate', (message) => {
    if (message.content.startsWith('!mute')) {
        if (!message.member.permissions.has('ManageRoles')) {
            return message.reply('You do not have permission to mute members.');
        }

        const member = message.mentions.members.first();
        if (!member) {
            return message.reply('Please mention a user to mute.');
        }

        let muteRole = message.guild.roles.cache.find(role => role.name === 'Muted');
        if (!muteRole) {
            return message.reply('No "Muted" role found. Please create one first.');
        }

        member.roles.add(muteRole)
            .then(() => message.reply(`${member.user.tag} has been muted.`))
            .catch((err) => message.reply('I was unable to mute the member.'));  
    }
});
Enter fullscreen mode Exit fullscreen mode

Clear Messages Command

client.on('messageCreate', (message) => {
    if (message.content.startsWith('!clear')) {
        if (!message.member.permissions.has('ManageMessages')) {
            return message.reply('You do not have permission to manage messages.');
        }

        const args = message.content.split(' ');
        const amount = parseInt(args[1]);

        if (isNaN(amount) || amount <= 0) {
            return message.reply('Please specify a valid number of messages to delete.');
        }

        message.channel.bulkDelete(amount, true)
            .then((deletedMessages) => message.reply(`Deleted ${deletedMessages.size} messages.`))
            .catch((err) => message.reply('I was unable to delete messages.'));  
    }
});
Enter fullscreen mode Exit fullscreen mode

Step 4: Invite the Bot to Your Server

  1. Go back to the Discord Developer Portal.
  2. In the left sidebar, click OAuth2 > URL Generator.
  3. Under Scopes, select bot. Under Bot Permissions, select:
    • Ban Members
    • Manage Roles
    • Manage Messages
  4. Copy the generated URL and paste it into your browser to invite the bot to your server.

Step 5: Test Your Bot

  1. Run the bot:
   node index.js
Enter fullscreen mode Exit fullscreen mode
  1. In your Discord server, try using the following commands:
    • !ban @user to ban a user.
    • !mute @user to mute a user (ensure a "Muted" role exists).
    • !clear <number> to delete a specified number of messages.

Additional Tips

  1. Improve Error Handling: Add better logging and user feedback for errors.
  2. Add a Help Command: Provide users with a list of commands and their descriptions.
  3. Secure Your Bot Token: Use environment variables or a configuration file to keep your token safe.
  4. Expand Features: Add warnings, unmute, or even automatic spam detection using a message tracker.

With this guide, you have a fully functional moderation bot that you can customize to suit your server’s needs!

discord Article's
30 articles in total
Favicon
TypeScript Discord Bot Handler
Favicon
Desvendando Subprocessos: Criando um Bot de Música com Go
Favicon
Does anyone know someone who makes Discord bots for free, or where to find such a person?
Favicon
Alarme Dynamo Throttle Events - Discord
Favicon
Boost Communication on Slack, Discord, GitHub, and Beyond! /BUTIFULL EMOJIS
Favicon
Using Discord as an unlimited cloud storage service
Favicon
Deploy your Discord Bot using Amazon EC2
Favicon
Discord Developer Cheat Sheet
Favicon
How to Set Up a Mock Server
Favicon
10 Cool Ideas for Discord Bots You Can Build Today
Favicon
Intro: Jonah 🐷
Favicon
Monetize your Discord community with these tips
Favicon
Creating a Moderation Bot for Discord
Favicon
Automating Event Management: A Discord to Google Calendar Bot
Favicon
Bulk Delete Messages with MEE6 Discord Bot
Favicon
Monitoring Discord server, detect CA, sending it to telegram bot
Favicon
Building a Discord Bot with OpenAI GPT
Favicon
Building a Cost-Effective Valheim Server on Azure with Serverless Discord Bot Integration
Favicon
Mass Delete Discord Messages Easily
Favicon
Hacktoberfest Extended Until November 30 for Robo.js
Favicon
Hacktoberfest 2024: Code Templates and Win Rewards 🎉
Favicon
Get News Updates automatically posted to your Discord using Supercog
Favicon
Hacktoberfest 2024: Create Discord Features or Videos to Win Rewards 🎉
Favicon
Running a Discord Bot on Raspberry Pi
Favicon
Missing Launch Button in your Discord Activity? Fix the Entry Point Command!
Favicon
🌟 Join the Open Source Community on Discord! 🚀
Favicon
DISCORD PROMOTION, DISOCRD SERVER PROMOTION
Favicon
I will discord promotion, nft discord server promotion, nft discord server marketing
Favicon
Patch Your Discord Activity’s Network Requests for Smooth CSP Compliance
Favicon
New PHP Package: Discord Table Builder

Featured ones: