繁体   English   中英

在 Discord.js 中添加一个角色

[英]Add a role in 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

您的代码有几个错误。 我不确定您尝试使用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');
    }
  }
});

您似乎使用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语句,因为您的控制台会收到垃圾邮件

暂无
暂无

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

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