如何使Discord Bot确保在命令中对某人执行ping操作

时间:2020-09-17 14:36:21

标签: javascript node.js discord discord.js

我正试图让机器人说出我查过的某人的名字,并给该人一个角色。现在,如果您不对某人执行ping操作,整个机器人就会崩溃。

这是我的代码:

const taggedUser0 = msg.mentions.members.first();
if (!args.length) {
  msg.author.send(`You didn't ping, ${msg.author}!`);
  msg.delete(); // Deletes command
} else if (msg.member.roles.holds(role)) {
    // checks if the person mentioned already has a role
    return;
  } else {
    taggedUser0.roles.add(role); // adds role
  }
  msg.author.send(`${taggedUser0}.`);
  msg.delete(); // Deletes command
}

1 个答案:

答案 0 :(得分:1)

我发现您的代码存在一些问题:


首先,else if()将始终返回错误。

if (false) console.log(false)
else if () console.log(true) // wrong usage

if (false) console.log(false)
else console.log(true) // correct usage


第二,您应该切换以下if语句:

if (!args.length)

// to:

if (!taggedUser0)

有人可以添加arg,但仍然没有提及任何人。


第三,GuildMember.roles返回一个Manager,而不是Collection,因此请确保您通过cache属性:

taggedUser0.roles.cache.holds()

此外,Collection.holds()不是函数。而是使用Collection.has()(并确保传递的参数是角色ID,而不是角色对象):

taggedUser0.roles.cache.has('ID Here');

最后,要ping通某人,您应该使用以下格式:

message.channel.send(`<@${taggedUser0.id}>`);