How to Build a Moderation Bot for Discord With Auto-Mute
🔍 WiseChecker

How to Build a Moderation Bot for Discord With Auto-Mute

Discord server moderators often struggle to manage disruptive members who spam, use voice channels inappropriately, or break server rules. Manually muting each user takes time and can miss repeat offenders. A moderation bot with auto-mute capabilities automates this process by muting users automatically when they trigger a defined rule. This article explains how to build a basic moderation bot using Discord.js and Node.js, with a focus on implementing an auto-mute feature that responds to text or voice channel violations.

Key Takeaways: Building a Discord Moderation Bot With Auto-Mute

  • Discord Developer Portal > Application > Bot > Add Bot: Creates a bot user and provides the token needed to connect your code to Discord.
  • Node.js and Discord.js v14: The runtime and library required to write the bot’s logic and interact with the Discord API.
  • GuildMember.timeout() method: Built-in Discord API method that temporarily mutes a member in both text and voice channels for up to 28 days.

What the Auto-Mute Bot Does and What You Need

A moderation bot with auto-mute watches for specific events, such as a user sending a banned word or exceeding a message rate limit. When the bot detects a violation, it applies a timeout to the member. The timeout silences the member in all text channels and voice channels for a defined duration. This approach eliminates the need for moderators to manually mute individuals and ensures consistent enforcement of server rules.

Prerequisites

Before you start coding, you need the following:

  • A Discord server where you have the Manage Server and Manage Roles permissions
  • Node.js version 16.9.0 or higher installed on your computer
  • A code editor such as Visual Studio Code
  • A Discord application and bot token from the Discord Developer Portal

How the Auto-Mute Feature Works

The auto-mute feature uses Discord’s timeout API. When a member is timed out, Discord automatically applies a Timeout status that prevents the member from sending messages, reacting, or speaking in voice channels. The timeout duration is set in milliseconds, with a maximum of 2,419,200,000 ms (28 days). The bot does not need a custom mute role or manual role assignment. This method is simpler and more reliable than older mute techniques that relied on role permissions.

Steps to Build the Bot and Implement Auto-Mute

Step 1: Create a Discord Application and Bot

  1. Go to the Discord Developer Portal
    Open https://discord.com/developers/applications and click New Application. Give your application a name, for example “ModBot,” and click Create.
  2. Create a bot user
    In the left sidebar, click Bot. Click Add Bot and confirm by clicking Yes, do it!. Your bot now appears with a username and an icon.
  3. Copy the bot token
    Under the bot’s username, click Reset Token. Copy the new token and save it in a secure place. You will need it later in your code.
  4. Enable privileged gateway intents
    Scroll down to Privileged Gateway Intents. Turn on Server Members Intent and Message Content Intent. These intents allow the bot to see member events and read message content.
  5. Invite the bot to your server
    In the left sidebar, click OAuth2 > URL Generator. Under Scopes, select bot. Under Bot Permissions, select Send Messages, Manage Messages, Mute Members, and Read Message History. Copy the generated URL, paste it into your browser, and invite the bot to your server.

Step 2: Set Up the Node.js Project

  1. Create a new folder
    On your computer, create a folder named modbot. Open a terminal in that folder.
  2. Initialize the project
    Run npm init -y to create a package.json file.
  3. Install Discord.js
    Run npm install discord.js. This installs the latest version of Discord.js (v14 or later).
  4. Create the main bot file
    Create a file named index.js in the same folder.

Step 3: Write the Bot Code With Auto-Mute Logic

  1. Import Discord.js and create a client
    Open index.js and add the following code:
    const { Client, GatewayIntentBits } = require('discord.js');
    
    const client = new Client({
      intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.GuildMembers
      ]
    });
  2. Log in the bot
    Add the login line at the bottom of the file:
    client.login('YOUR_BOT_TOKEN_HERE');

    Replace YOUR_BOT_TOKEN_HERE with the token you copied from the Developer Portal.

  3. Add a ready event
    Insert this code before the login line:
    client.once('ready', () => {
      console.log(`Logged in as ${client.user.tag}`);
    });
  4. Implement auto-mute for banned words
    Add a message event that checks for a banned word and applies a timeout:
    const bannedWords = ['spam', 'badword', 'advertisement'];
    
    client.on('messageCreate', async (message) => {
      if (message.author.bot) return;
    
      const containsBannedWord = bannedWords.some(word =>
        message.content.toLowerCase().includes(word)
      );
    
      if (containsBannedWord) {
        try {
          await message.member.timeout(60  1000, 'Auto-mute for banned word');
          message.channel.send(`${message.author} has been muted for 1 minute due to a banned word.`);
        } catch (error) {
          console.error('Failed to timeout member:', error);
        }
      }
    });

    This code mutes the member for 60 seconds (60,000 ms) when they send a message containing any word in the bannedWords array. The timeout reason is visible in the server audit log.

  5. Implement auto-mute for rate limiting
    To mute members who send messages too quickly, add a cooldown tracker:
    const messageTimestamps = new Map();
    
    client.on('messageCreate', async (message) => {
      if (message.author.bot) return;
    
      const now = Date.now();
      const userTimestamps = messageTimestamps.get(message.author.id) || [];
      const recentMessages = userTimestamps.filter(timestamp => now - timestamp < 5000);
    
      if (recentMessages.length >= 5) {
        try {
          await message.member.timeout(120  1000, 'Auto-mute for spamming');
          message.channel.send(`${message.author} has been muted for 2 minutes for spamming.`);
          messageTimestamps.delete(message.author.id);
        } catch (error) {
          console.error('Failed to timeout member:', error);
        }
      } else {
        recentMessages.push(now);
        messageTimestamps.set(message.author.id, recentMessages);
      }
    });

    This example mutes a member for 2 minutes if they send 5 or more messages within a 5-second window.

Step 4: Run the Bot

  1. Start the bot
    In your terminal, run node index.js. You should see the message “Logged in as ModBot#1234” (your bot’s tag).
  2. Test the auto-mute
    In a text channel where the bot has permission, send a message containing one of the banned words. The bot should reply with a mute notice, and your message will be visible but you will be unable to send new messages for 60 seconds.

Common Mistakes and Things to Avoid

Bot Does Not Have Mute Members Permission

If the bot cannot timeout members, check that the bot’s role has the Mute Members permission enabled. Also confirm that the bot’s role is positioned above the members it tries to mute in the server’s role hierarchy. Go to Server Settings > Roles and drag the bot’s role above the member roles.

Bot Does Not Respond to Messages

Make sure you enabled the Message Content Intent in the Developer Portal. Without this intent, the bot cannot read message content. Also verify that the bot is online and has the Send Messages permission in the channel.

Timeout Duration Exceeds 28 Days

The Discord API accepts timeout durations up to 2,419,200,000 milliseconds (28 days). If you pass a larger value, the API returns an error. Always convert your desired duration to milliseconds and ensure it does not exceed that limit.

Bot Timeouts Itself or Other Bots

The code shown above includes a check for message.author.bot at the start of the message event. If you remove that check, the bot may attempt to timeout itself or other bots, which will fail and produce an error.

Manual Mute vs Auto-Mute: Timeout Method Comparison

Item Manual Mute (Role-Based) Auto-Mute (Timeout via Bot)
Setup complexity Requires creating a mute role and configuring channel permissions No role needed; uses Discord’s built-in timeout API
Automation Must be applied manually by a moderator each time Triggered automatically by rules (banned words, spam detection)
Duration control Indefinite until role is removed Set in milliseconds; maximum 28 days
Scope Silences only text or voice depending on role permissions Mutes both text and voice simultaneously
Audit trail No automatic logging Reason can be passed and appears in server audit log

You now have a working Discord moderation bot that automatically mutes users based on banned words or spam behavior. Start by testing the bot in a private channel before rolling it out to your entire server. For advanced functionality, consider adding a command to adjust the mute duration or to exempt specific roles from auto-mute. Use the GuildMember.timeout() method instead of role-based mutes to keep your code simple and reliable.