在 Discord.js 中添加角色

时间:2021-03-01 13:35:43

标签: javascript node.js discord discord.js

我是 JS 的新手,我正在尝试让我的机器人为特定成员分配特定角色。

如果你能帮助我,请这样做。

代码:

bot.on("message", (msg) => {
    if ((msg.content === "!give", role, member))
        var role = msg.guild.roles.cache.find((r) => {
            return r.name === "convidado astolfofo";
        });
    var member = msg.mentions.members.first();
    member.roles.add(role);
    console.log(member);
    console.log(role);
});

我遇到的错误:

(node:2364) UnhandledPromiseRejectionWarning: TypeError [INVALID_TYPE]: Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes.
TypeError: Cannot read property 'add' of undefined discord.js

2 个答案:

答案 0 :(得分:1)

您的代码有几个错误。我不确定你试图用 if ((msg.content === "!give", role, member)) 做什么——可能是检查消息是否以 !give 开头,以及是否有角色和成员——但它不会像这样工作JavaScript。一旦定义了这些变量,您需要单独检查它们。

如果您检查是否 msg.content === "!give" 但您还希望该成员提及某个成员,则永远不会为真。如果整个消息只是 !give,则没有提及用户。如果有提及的用户,msg.content 将超过 !give。尝试检查 message.content 是否以 "!give" 开头。

接下来,如果在 if 语句后不使用花括号,则只有下一行在该语句内。因此,您尝试检查命令是否为 !give,如果是,则搜索角色,但检查添加角色位置的以下几行不在此语句中。这意味着,它在每条传入消息上运行。尝试使用花括号。

检查权限并发送回复让用户知道是否有任何遗漏也是一个好主意。

检查下面的工作示例,我添加了注释以使其更容易理解:

bot.on('message', async (msg) => {
  if (msg.content.startsWith('!give')) {
    // check if the message author has the permission to add a role
    if (!msg.member.hasPermission('MANAGE_ROLES')) {
      return msg.reply('You need `MANAGE_ROLES` permission to add a role');
    }

    // check if the bot has the permission to add a role
    if (!msg.guild.me.hasPermission('MANAGE_ROLES')) {
      return msg.reply('I do not have `MANAGE_ROLES` permission to add a role');
    }

    // check if there is a member mentioned
    const member = msg.mentions.members.first();
    // if there is none, send a reply
    if (!member) {
      return msg.reply("Don't forget to mention someone!");
    }

    // search for the role
    // don't forget that it's case-sensitive
    const role = msg.guild.roles.cache.find((r) => r.name === 'convidado astolfofo');

    // check if the role exists
    if (!role) {
      return msg.reply("Oh-oh, I can't find the role `convidado astolfofo`");
    }

    // try to add a role
    try {
      await member.roles.add(role);
      msg.reply(`Role added to ${member}`);
    } catch (error) {
      console.log(error);
      msg.reply('Oops, role not added, there was an error');
    }
  }
});

答案 1 :(得分:0)

您似乎错误地使用了 return。试试这个:

bot.on("message", (msg) => {
    if ((msg.content === "!give", role, member))
        var role = msg.guild.roles.cache.find(r => r.id === "<role id goes here>");
        var member = msg.mentions.members.first();
        member.roles.add(role);
        console.log(member.username);
        console.log(role.name);
});

我还更改了您的 console.log 语句,因为您的控制台会收到垃圾邮件