【问题标题】:Is there a way to add a role to a member as soon as the role is created? (Discord.js v12)有没有办法在创建角色后立即向成员添加角色? (Discord.js v12)
【发布时间】:2020-10-24 13:10:32
【问题描述】:

我试图在运行一次命令时创建一个新角色并将其添加到成员中,但似乎我必须运行该命令两次(一次:创建角色,两次:创建角色加入会员)。

我猜这可能是由于这个错误:TypeError [INVALID_TYPE]: Supplied roles is not an Role, Snowflake or Array or Collection of Roles or Snowflakes.

if (command === 'test') {
  if (!message.mentions.users.size) {
    return message.reply('You need to tag a user!');
  }
  const member = message.mentions.members.first();
  const testRole = message.guild.roles.cache.find(role => role.name === 'TestRole');

  if (!testRole) {
    message.guild.roles.create ({
      data: {
        name: 'TestRole',
        color: 'RANDOM',
      },
    }).catch(() => {
      message.reply('Unable to create role');
    });
  }
  member.roles.add(testRole).catch((error) => {console.log(error);});
}

是否有一种解决方法,以便在角色创建后立即将其添加到成员中?

【问题讨论】:

    标签: javascript node.js discord.js


    【解决方案1】:

    由于roles.create返回了一个promise,你可以使用.then()给成员添加角色

    if (command === 'test') {
      if (!message.mentions.users.size) {
        return message.reply('You need to tag a user!');
      }
      const member = message.mentions.members.first();
      const testRole = message.guild.roles.cache.find(role => role.name === 'TestRole');
    
      if (!testRole) {
        message.guild.roles.create ({
          data: {
            name: 'TestRole',
            color: 'RANDOM',
          },
        })
        .then((role) => {
          member.roles.add(testRole)
        })
        .catch(() => {
          message.reply('Unable to create role');
        });
      } else {
        member.roles.add(testRole).catch((error) => {console.log(error);});
      }
    }
    

    【讨论】:

    • 谢谢!这可行,但是,TypeError [INVALID_TYPE]: Supplied roles is not an Role, Snowflake or Array or Collection of Roles or Snowflakes. 的错误仍然存​​在,有什么解决办法吗?
    • 我更新了答案,如果错误仍然存​​在,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 2020-10-20
    • 2023-03-22
    相关资源
    最近更新 更多