如何在 Discord.js 中创建静音命令

用户14043502

我正在制作一个机器人,Discord.js想知道如何添加静音功能。我希望机器人在一定时间内为您提供预定义的静音角色,然后将其删除。

母狮100

有几件事情你需要做出一个好的mute命令:

在执行命令时,您还应该考虑许多其他功能,例如权限限制、确认消息等。但是,这些只是最基本的。


首先,您需要获得Muted角色。

// 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');

然后,您必须获取GuildMember要静音的用户的对象。

// assuming you want the command to mention the target, for example: `!mute @user`
const target = message.mentions.members.first();

现在,您可以为该用户授予Muted角色。

target.roles.add(mutedRole);

要在一段时间后拿走角色,您需要一个延迟功能。最好的功能是setTimeout. target.roles.add()线:

setTimeout(() => {
  target.roles.remove(mutedRole); // remove the role
}, <time>) 

获得指定的时间会很棘手。setTimeout()只接受毫秒作为延迟值。你可以:

  • 总是用ms时间参数触发命令
  • 始终使用不是 的时间值触发命令ms,例如秒、小时等。然后,ms在脚本中解析给定的时间
  • 使用一个npm名为ms. 您将能够使用诸如10s12h等值2d

如果您选择第一个选项,那么您几乎完成了命令!只需将<time>上面的代码片段替换args[1],一切都应该正常工作。

如果您选择了第二个选项,那么您需要做更多的事情。如果您选择在几秒钟内静音,请替换<time>args[1] * 1000如果您选择小时,请将其替换为args[1] * 60000等。

如果选择第三个选项,则可以ms通过简单地替换<time>使用来解析时间ms(args[1])

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章