Back to Blog
Discord Bot Moderation Commands — Complete Code Guide (2025)
Tutorial June 15, 2025 12 min read dlist.space Team
discord moderation bot discord ban command discord mute command discord warn system discord.js moderation

Discord Bot Moderation Commands — Complete Code Guide (2025)

A Discord moderation bot is one of the most useful bots you can build. Every active Discord server needs tools to manage members, enforce rules, and maintain a healthy community. In this guide, we'll build a complete moderation system with warn, mute, tempmute, lock, slowmode, and more.

Discord Bot Moderation Commands Guide

Moderation Commands We'll Build

  • !warn — Issue a warning to a user with a reason
  • !warnings — View all warnings for a user
  • !clearwarns — Clear all warnings for a user
  • !mute — Mute a member in the server
  • !unmute — Unmute a member
  • !tempmute — Temporarily mute a member for X minutes
  • !kick — Kick a member with a reason
  • !ban — Ban a member with a reason
  • !tempban — Temporarily ban for X days
  • !unban — Unban a user by ID
  • !slowmode — Set channel slowmode
  • !lock — Lock a channel from messaging
  • !unlock — Unlock a channel
  • !modlog — View moderation log for a user

discord.js Complete Moderation Bot

require('dotenv').config();
const { Client, GatewayIntentBits, EmbedBuilder, PermissionFlagsBits } = require('discord.js');

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

// Simple in-memory warning storage (use a database in production)
const warnings = new Map();

const PREFIX = '!';

function getWarnings(guildId, userId) {
  const key = `${guildId}-${userId}`;
  return warnings.get(key) || [];
}

function addWarning(guildId, userId, reason, moderator) {
  const key = `${guildId}-${userId}`;
  const warns = getWarnings(guildId, userId);
  warns.push({ reason, moderator, date: new Date().toISOString() });
  warnings.set(key, warns);
  return warns.length;
}

client.on('messageCreate', async (message) => {
  if (message.author.bot || !message.content.startsWith(PREFIX)) return;

  const args = message.content.slice(PREFIX.length).trim().split(/ +/);
  const command = args.shift().toLowerCase();

  // WARN command
  if (command === 'warn') {
    if (!message.member.permissions.has(PermissionFlagsBits.ModerateMembers)) {
      return message.reply('❌ You need the Moderate Members permission.');
    }
    const target = message.mentions.members.first();
    if (!target) return message.reply('❌ Please mention a member to warn.');
    const reason = args.slice(1).join(' ') || 'No reason provided';
    const count = addWarning(message.guild.id, target.id, reason, message.author.tag);
    const embed = new EmbedBuilder()
      .setTitle('⚠️ Warning Issued')
      .setColor(0xf59e0b)
      .addFields(
        { name: 'Member', value: target.user.tag, inline: true },
        { name: 'Moderator', value: message.author.tag, inline: true },
        { name: 'Reason', value: reason },
        { name: 'Total Warnings', value: count.toString(), inline: true },
      );
    message.reply({ embeds: [embed] });
    target.send(`⚠️ You were warned in **${message.guild.name}** for: ${reason}`).catch(() => {});
  }

  // WARNINGS command
  if (command === 'warnings') {
    const target = message.mentions.members.first() || message.member;
    const userWarns = getWarnings(message.guild.id, target.id);
    if (userWarns.length === 0) {
      return message.reply(`✅ ${target.user.username} has no warnings.`);
    }
    const embed = new EmbedBuilder()
      .setTitle(`⚠️ Warnings for ${target.user.username}`)
      .setColor(0xf59e0b)
      .setDescription(userWarns.map((w, i) =>
        `**${i + 1}.** ${w.reason} — by ${w.moderator} on ${new Date(w.date).toDateString()}`
      ).join('\n'));
    message.reply({ embeds: [embed] });
  }

  // CLEARWARNS command
  if (command === 'clearwarns') {
    if (!message.member.permissions.has(PermissionFlagsBits.Administrator)) {
      return message.reply('❌ You need Administrator permission.');
    }
    const target = message.mentions.members.first();
    if (!target) return message.reply('❌ Please mention a member.');
    warnings.delete(`${message.guild.id}-${target.id}`);
    message.reply(`✅ Cleared all warnings for ${target.user.username}.`);
  }

  // MUTE command (using Discord timeout / "time out" feature)
  if (command === 'mute') {
    if (!message.member.permissions.has(PermissionFlagsBits.ModerateMembers)) {
      return message.reply('❌ You need the Moderate Members permission.');
    }
    const target = message.mentions.members.first();
    if (!target) return message.reply('❌ Please mention a member to mute.');
    const reason = args.slice(1).join(' ') || 'No reason provided';
    // Timeout for 28 days (maximum)
    await target.timeout(28 * 24 * 60 * 60 * 1000, reason);
    message.reply(`🔇 ${target.user.username} has been muted. Reason: ${reason}`);
  }

  // TEMPMUTE command
  if (command === 'tempmute') {
    if (!message.member.permissions.has(PermissionFlagsBits.ModerateMembers)) {
      return message.reply('❌ You need the Moderate Members permission.');
    }
    const target = message.mentions.members.first();
    if (!target) return message.reply('❌ Please mention a member to tempmute.');
    const minutes = parseInt(args[1]);
    if (isNaN(minutes) || minutes < 1) return message.reply('❌ Please provide minutes (e.g., !tempmute @user 30 spamming)');
    const reason = args.slice(2).join(' ') || 'No reason provided';
    await target.timeout(minutes * 60 * 1000, reason);
    message.reply(`🔇 ${target.user.username} has been muted for ${minutes} minutes. Reason: ${reason}`);
  }

  // UNMUTE command
  if (command === 'unmute') {
    if (!message.member.permissions.has(PermissionFlagsBits.ModerateMembers)) {
      return message.reply('❌ You need the Moderate Members permission.');
    }
    const target = message.mentions.members.first();
    if (!target) return message.reply('❌ Please mention a member to unmute.');
    await target.timeout(null);
    message.reply(`🔊 ${target.user.username} has been unmuted.`);
  }

  // SLOWMODE command
  if (command === 'slowmode') {
    if (!message.member.permissions.has(PermissionFlagsBits.ManageChannels)) {
      return message.reply('❌ You need Manage Channels permission.');
    }
    const seconds = parseInt(args[0]);
    if (isNaN(seconds) || seconds < 0 || seconds > 21600) {
      return message.reply('❌ Please provide seconds between 0 and 21600.');
    }
    await message.channel.setRateLimitPerUser(seconds);
    message.reply(seconds === 0 ? '✅ Slowmode disabled.' : `✅ Slowmode set to ${seconds} seconds.`);
  }

  // LOCK command
  if (command === 'lock') {
    if (!message.member.permissions.has(PermissionFlagsBits.ManageChannels)) {
      return message.reply('❌ You need Manage Channels permission.');
    }
    await message.channel.permissionOverwrites.edit(message.guild.roles.everyone, {
      SendMessages: false,
    });
    message.reply('🔒 Channel locked.');
  }

  // UNLOCK command
  if (command === 'unlock') {
    if (!message.member.permissions.has(PermissionFlagsBits.ManageChannels)) {
      return message.reply('❌ You need Manage Channels permission.');
    }
    await message.channel.permissionOverwrites.edit(message.guild.roles.everyone, {
      SendMessages: null,
    });
    message.reply('🔓 Channel unlocked.');
  }

  // UNBAN command
  if (command === 'unban') {
    if (!message.member.permissions.has(PermissionFlagsBits.BanMembers)) {
      return message.reply('❌ You need Ban Members permission.');
    }
    const userId = args[0];
    if (!userId) return message.reply('❌ Please provide a user ID to unban.');
    try {
      await message.guild.members.unban(userId);
      message.reply(`✅ User ${userId} has been unbanned.`);
    } catch {
      message.reply('❌ Could not find that user in the ban list.');
    }
  }
});

client.login(process.env.TOKEN);

Best Practices for Moderation Bots

  • Use a database — Store warnings, bans, and mutes in MongoDB or SQLite for persistence
  • Set up mod logs — Log all moderation actions to a dedicated channel
  • DM users — Notify users when they are moderated
  • Auto-moderation — Add spam detection, word filtering, and anti-raid protection
  • Hierarchy checks — Prevent mods from actioning users with higher roles
  • Reason tracking — Always require a reason for serious actions

Share Your Moderation Bot

Built a great moderation bot? List it on dlist.space in the Moderation category and let thousands of server owners discover it!