How do I make a command that mutes or unmutes a user?

Great question! I’ll be going over that today! First, I’d like to make you aware that while there is a way to automatically unmute a user, I’m going to be going over how to unmute a user manually. I also would like to make you aware that all of these codes are written in their own separate files. If you do not know how to do that, please check this tutorial. Let’s get started!
This is how your code will look for the mute command when it is completed:

const Discord = require("discord.js");

module.exports = {
  name: "mute",
  description: "This will mute users.\n**Note:** You have to have the MANAGE_MESSAGES permission to use this command.",
  aliases: ['turnoff', 'off', 'nospeak', 'm'],
  usage: ".mute @username or user ID [length of time] [reason]",
  inHelp: "yes",
  execute (message, args) {

    // Defines and logs variables
    const reason = args.slice(2).join(" ");
    console.log('reason:' + reason);
    const person = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
    console.log('user:' + person);
    const cachedUserRoles = {};
    console.log('user roles are cached.');
    const muterole = message.guild.roles.cache.find( r => r.name === 'Muted');

    // find person
    if (!person) {
      message.reply(":x: Couldn't find that member!");
      return;
    } 
    // Requiring reason
    if (reason.length < 1) {
      message.reply('You must supply a reason for the mute.');
      return;
    } 
    
    // makes sure bot and user have roles.
    if(!message.member.hasPermission("MANAGE_MEMBERS")) {
      message.channel.send(":no_entry_sign: You do not have the permission to use this command!");
      return;
    } 

    if(!message.guild.me.hasPermission(["MANAGE_MEMBERS"])) {
      message.channel.send(":no_entry_sign: I do not have the permission to add roles!");
      return;
    }

    //finds role and if it isn't there, creates it.
    if (!muterole) {
      try {
        muterole = message.guild.roles.create({
          data: {
            name:'Muted',
            color: 'RED',
            permissions: []
          },
          reason: 'Need a role for muted users.',
        });
        message.guild.channels.forEach((channel, id) => {
          channel.overwritePermissions(muterole, {
            SEND_MESSAGES: false,
            MANAGE_MESSAGES: false,
            ADD_REACTIONS: false,
            CONNECT: false,
          });
        });
      }catch(e) { console.log(e.stack); }
      console.log('role created!');
    } // end if

    //Cache their already existing roles
    cachedUserRoles[person.id] = person.roles.cache;

    //Set their roles to an empty array to clear them, then add the muted role once all roles were removed successfully
    person.roles.set([]).then(member => member.roles.add(muterole)).catch(console.error);
    message.channel.send(`${person} has been muted.`);
    console.log('Successful!');
  },
};

Once you are finished coding that, this is how your unmute command will look:

const Discord = require("discord.js");

module.exports = {
  name: "unmute",
  description: "This will unmute a user. Giving them the ability to speak again.\n**Note:** You have to have the MANAGE_MESSAGES permission to use this command.",
  aliases: ['de-mute', 'mm', 'um', 'speak'],
  usage: ".unmute @username or user ID [reason]",
  inHelp: "yes",
  execute (message, args) {

    // Defines and logs variables
    const person = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
    const reason = args.slice(1).join(" ");
    const muterole = message.guild.roles.cache.find( r => r.name === 'Muted');
    console.log('unmute reason:' + reason);
    console.log('user:' + person);
    console.log('user roles')
    
    // find person
    if (!person) {
      message.reply(":x: Couldn't find that member!");
      return;
    } 
    // Requiring reason
    if (reason.length < 1) {
      message.reply(':x: You must supply a reason for to unmute.');
      return;
    } 
    
    // makes sure bot and user have roles.
    if(!message.member.hasPermission("MANAGE_MEMBERS")) {
      message.channel.send(":no_entry_sign: You do not have the permission to use this command!");
      return;
    } 

    if(!message.guild.me.hasPermission(["MANAGE_MEMBERS"])) {
      message.channel.send(":no_entry_sign: I do not have the permission to add roles!");
      return;
    }

    if(!muterole) {
        message.reply(':x: Mute role could not be found!');
        return;
    }

    person.roles.remove(muterole).catch(console.error);
    message.channel.send(`:white_check_mark: ${person} has been unmuted and we were provided this reason: ${reason}.`);

  },
};

Now that you can see how the code is written as a whole, I will be going over it in parts. I will be ignoring what is between the module.exports and the execute(message,args) as that has been gone over in other tutorials. I will start here:

   // Defines and logs variables
    const reason = args.slice(2).join(" ");
    console.log('reason:' + reason);
    const person = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
    console.log('user:' + person);
    const cachedUserRoles = {};
    console.log('user roles are cached.');
    const muterole = message.guild.roles.cache.find( r => r.name === 'Muted');

Just like the comment says, this section is defining all of the variables and having them print out to the console using console.log. As long as you know basic JavaScript (recommended) this should be fairly easy to read. Moving on…

    // find person
    if (!person) {
      message.reply(":x: Couldn't find that member!");
      return;
    }

This looks for the user you mentioned and if it can’t find that user (they left, you used the wrong ID, etc.) it spits out (to Discord) that it couldn’t find that member. Next..

    // Requiring reason
    if (reason.length < 1) {
      message.reply('You must supply a reason for the mute.');
      return;
    }

This makes sure you include a reason for muting a user and if you don’t, it spits out (to Discord) that you must supply a reason for the mute.

    // makes sure bot and user have roles.
    if(!message.member.hasPermission("MANAGE_MEMBERS")) {
      message.channel.send(":no_entry_sign: You do not have the permission to use this command!");
      return;
    }

Just like the comments state here, this makes sure that both the bot and the user running the command have the MANAGE_MEMBERS command. If they don’t, the command will not run and will advise the user they do not have permission to run the command.

  //finds role and if it isn't there, creates it.
    if (!muterole) {
      try {
        muterole = message.guild.roles.create({
          data: {
            name:'Muted',
            color: 'RED',
            permissions: []
          },
          reason: 'Need a role for muted users.',
        });
        message.guild.channels.forEach((channel, id) => {
          channel.overwritePermissions(muterole, {
            SEND_MESSAGES: false,
            MANAGE_MESSAGES: false,
            ADD_REACTIONS: false,
            CONNECT: false,
          });
        });
      }catch(e) { console.log(e.stack); }
      console.log('role created!');
    } // end if

This checks for the Muted role in your server and if you do not have that role, it creates it and sets the above permissions off so the user cannot send messages, manage messages, add reactions, or use voice channels. If it does find the Muted role then this does not run and is ignored.
The rest of the Mute command is pretty small so I will group it.

   //Cache their already existing roles
    cachedUserRoles[person.id] = person.roles.cache;

    //Set their roles to an empty array to clear them, then add the muted role once all roles were removed successfully
    person.roles.set([]).then(member => member.roles.add(muterole)).catch(console.error);
    message.channel.send(`${person} has been muted.`);
    console.log('Successful!');

The first 2 lines, cache a user’s roles so they can be re-applied when you run the Unmute command. The next 4 lines do just what the comment states, it clears the user’s roles and then gives the user the Muted role. That’s the end of the Mute command. Now you want to also be able to Unmute the user so they can communicate again. Now I will start with the Unmute command. I’m just going to be showing what is different between the two commands:

    person.roles.remove(muterole).catch(console.error);
    message.channel.send(`:white_check_mark: ${person} has been unmuted and we were provided this reason: ${reason}.`);

This removes the Muted role and gives the user back their roles.

You are done! Congratulations! If you have issues, you know where you can ask!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.