I'm making a bot with Discord.js
and was wondering how I could add a mute function. I would like the bot to give you a predefined muted role for a certain amount of time, and then remove it.
I'm making a bot with Discord.js
and was wondering how I could add a mute function. I would like the bot to give you a predefined muted role for a certain amount of time, and then remove it.
-
To make a mute mand, you have to give a "mute" role to the player, and then with a
.setTimeout()
remove it. Create a role with no permission, so they can't write in any channel. – BoBsmil3Y Commented Sep 4, 2020 at 9:07 - how do i add a role to a mentioned player? can you give the code please or a tutorial? sorry. i'm new to discord bot dvelopment. – user14043502 Commented Sep 4, 2020 at 10:21
1 Answer
Reset to default 1There are a few things you need to make a good mute
mand:
- The
GuildMemberRoleManager#add()
Function - The
setTimeout()
Function - The
GuildMemberRoleManager#remove()
Function
There are many other features you should take into consideration when making the mand, such as permission restrictions, confirmation messages, etc. However, these are the bare basics.
First, you need to get the Muted
role.
// get the role by id:
const mutedRole = message.guild.roles.cache.get('<Muted Role ID>');
// or, if you can't get the id:
const mutedRole = message.guild.roles.cache.find(
(role) => role.name === 'Muted'
);
// if there is no `Muted` role, send an error
if (!mutedRole)
return message.channel.send('There is no Muted role on this server');
Then, you must get GuildMember
object of the user you want to mute.
// assuming you want the mand to mention the target, for example: `!mute @user`
const target = message.mentions.members.first();
Now, you can give that user the Muted
role.
target.roles.add(mutedRole);
To take away the role after a bit of time, you need a delay function. The best function for that is setTimeout
. After the target.roles.add()
line:
setTimeout(() => {
target.roles.remove(mutedRole); // remove the role
}, <time>)
Getting the specified amount of time will be tricky. setTimeout()
only accepts milliseconds as a delay value. You could either:
- Just always trigger the mand with an
ms
time argument - Always trigger the mand with a time value that isn't
ms
, such as seconds, hours, etc. Then, parse the given time toms
in the script - Use a handy dandy
npm
package calledms
. You'll be able to use values such as10s
,12h
,2d
, etc.
If you choose the first option, then you're pretty much finished with the mand! Just replace <time>
in the above snippet with args[1]
, and everything should work.
If you chose the second option, then you'll need to do a bit more. If you chose to mute in seconds, replace <time>
with args[1] * 1000
. If you chose hour, replace it with args[1] * 60000
, etc.
If you chose the third option, you can parse the time using the ms
package by simply replacing <time>
with ms(args[1])