简体   繁体   English

Javascript Discord,给提到的用户一个角色

[英]Javascript Discord, give a mentioned user a role

I just wanted to ask how I add a command that gives a person a role.我只是想问我如何添加一个命令来给一个人一个角色。 So that you can type in: "addRole @user#1234" and the user get the role.这样您就可以输入:“addRole @user#1234”并且用户获得角色。

Since you didn't give any example codes, I'm going to show you the approach of doing so myself.由于您没有提供任何示例代码,我将向您展示自己这样做的方法。

Firstly, you have to get two variables, one for the role you want to give, and one for the member you are giving.首先,您必须获得两个变量,一个用于您想要赋予的角色,另一个用于您赋予的成员
You can get a role by its id (also by name but using Collection#find )您可以通过其 id 获取角色(也可以通过名称,但使用Collection#find
You can get a member from a mention in a message by the using Message#mentions您可以通过使用Message#mentions从消息中的提及中获取成员

let role = message.guild.roles.get('roleIdBetweenQuotes');
let member = message.mentions.members.first();
// A message can have more than one mention, which results in giving us a collection of members.
// So we have to use first() to get the first member in that collection.

After getting both variables, you will have to add the role to the member by using the GuildMember#addRole function.获得这两个变量后,您必须使用GuildMember#addRole函数将角色添加到成员中

member.addRole(role)
  .then(memberAdded => { // Optional
    message.channel.send(`Added role ${role.name} to ${member.displayName}`);
  })
  .catch(error => {
    console.log(error);
  });

We add the role to the member.我们将角色添加到成员。 The GuildMember#addRole function returns a promise , so in order to send a message after it, you have to wait till the promise gets resolved, then sending a confirmation message. GuildMember#addRole函数返回一个promise ,所以为了在它之后发送消息,你必须等到 promise 得到解决,然后发送确认消息。 Also, you can log an error if the promise gets rejected.此外,如果承诺被拒绝,您可以记录错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM