【问题标题】:Assigning a role to a member based on args根据 args 为成员分配角色
【发布时间】:2019-04-12 10:25:23
【问题描述】:

我对 Node.js 还很陌生,目前正在开发一个 Discord 机器人。我试图让我的机器人根据用户传递的参数分配服务器角色。我知道我可以找到特定角色的名称,然后根据他们的响应为他们分配该角色。

但是:我的管理员几乎每周都会创建和删除角色,我不能每周都编辑我的代码来更新要分配的可用角色列表,所以我决定制作一行代码这将提取用户传递的参数,然后在 将 args 作为参数传递时找到角色名称。
我的代码如下所示:

if (command === 'role'){


    let roleMember = message.member;
    var mentionedRole = args[0];
    let testRole = mentionedRole.toString();

    // Debug message to check if it reads my input
    message.channel.send(`TRYING! YOUR ARGS WERE: ${testRole}`);

    // Define the role
    let finalRole = message.guild.roles.find(r => r.name === testRole);

    // Check if it reads the role successfully
    message.channel.send(`I READ: ${finalRole}`);

    // Add the role to the command author
    roleMember.addRole(top).catch(console.error);


  }

问题是当它返回它为finalRole 读取的内容时,它给了我this error。当机器人响应时,它将角色读取为空。我已经为此苦苦挣扎了好几个星期了,但我已经束手无策了。有谁知道我该如何解决这个问题?编辑:这是我的意思的一个例子: !role top“Top”是这里的角色名称。

【问题讨论】:

    标签: javascript node.js discord.js


    【解决方案1】:

    我认为问题在于您将角色名称与Role.toString() 进行比较。使用 Role.toString() 会返回提及,而 Role.name 只是角色的名称。
    我会这样写:

    if (command === 'role') {
      let roleMember = message.member;
      // I'm getting the Role object directly from the message, so that I don't need to parse it later
      var mentionedRole = message.mentions.roles.first();
    
      // If there was no mentioned Role, or the are any kinds of problems, exit
      if (!mentionedRole) return message.channel.send(`I'm unable to use that role: ${mentionedRole}`);
    
      // Add the role to the command author
      roleMember.addRole(mentionedRole).then(message.channel.send("Role successfully added.")).catch(console.error);
    }
    

    编辑:如果您只想使用角色的名称,而不提及它,您可以这样做(假设args[0] 是参数):

    if (command === 'role') {
      if (!args[0]) return message.reply("Please add the role name.");
    
      let roleMember = message.member;
      // I'm using the first argument to find the role: now it's not case-sensitive, if you want it to be case-sensitive just remove the .toLowerCase()
      var mentionedRole = message.guild.roles.find(r => r.name.toLowerCase() == args[0].toLowerCase());
    
      // If there was no mentioned Role, or the are any kinds of problems, exit
      if (!mentionedRole) return message.channel.send(`I'm unable to use that role: ${args[0]}`);
    
      // Add the role to the command author
      roleMember.addRole(mentionedRole).then(message.channel.send("Role successfully added.")).catch(console.error);
    }
    

    【讨论】:

    • 问题是mentions.roles.first(); 需要该人提及该角色,从而与该角色联系每个人。我怎样才能做到这样我就不用提了,我可以将参数作为参数传递。
    • 很高兴听到这个消息:)
    猜你喜欢
    • 2013-10-20
    • 2022-11-01
    • 1970-01-01
    • 2021-05-10
    • 2021-11-18
    • 2021-10-28
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多