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.
.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
There are a few things you need to make a good mute
mand:
GuildMemberRoleManager#add()
FunctionsetTimeout()
FunctionGuildMemberRoleManager#remove()
FunctionThere 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:
ms
time argumentms
, such as seconds, hours, etc. Then, parse the given time to ms
in the scriptnpm
package called ms
. You'll be able to use values such as 10s
, 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])