discord.js 成员加入我的服务器时无法为其添加角色

discord.js can't add a role to member when they join my server

我希望我的机器人在人们加入服务器时赋予他们特定的角色。但是我遇到了一些我不太明白的奇怪错误。

这是代码:

const { GuildMember, MessageEmbed } = require("discord.js");

module.exports = {
    name: "guildMemberAdd",
    /**
     * @param {GuildMember} member
     */
    async execute(member){
        let role = member.guild.roles.cache.some(role => role.name === 'Member')
        member.roles.add(role)

        member.guild.channels.cache.get(process.env.WELCOME_MESSAGE_CHANNEL_ID).send({ 
            embeds: [
                new MessageEmbed()
                .setTitle("Welcome! :smiley:")
                .setDescription(`${member.toString()} has joined the server!\n
                                Thanks for joining. Head over to <#${process.env.RULE_CHANNEL_ID}> and verify yourself in <#${process.env.VERIFY_CHANNEL_ID}> to get access to all other channels.`)
                .setThumbnail(member.user.displayAvatarURL())
                .setColor("GREEN")
            ]
        }) 
    }
}

当有人加入时,我收到此错误消息:

TypeError [INVALID_TYPE]: Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes.

问题是 some() returns a boolean (either true or false) and when you try to add a role to the member you pass this boolean value instead of a role ID. You can use the find() 方法而不是 returns 第一项,其中给定函数 returns 为真值(即 role.name 等于 "Member"):

  async execute(member) {
    let role = member.guild.roles.cache.find((role) => role.name === 'Member');

    if (!role)
      return console.log('Cannot find the role with the name "Member"');

    member.roles.add(role);
    member.guild.channels.cache
      .get(process.env.WELCOME_MESSAGE_CHANNEL_ID)
      .send({
        embeds: [
          new MessageEmbed()
            .setTitle('Welcome! :smiley:')
            .setDescription(
              `${member.toString()} has joined the server!\n Thanks for joining. Head over to <#${process.env.RULE_CHANNEL_ID}> and verify yourself in <#${process.env.VERIFY_CHANNEL_ID}> to get access to all other channels.`,
            )
            .setThumbnail(member.user.displayAvatarURL())
            .setColor('GREEN'),
        ],
      });
  }