使Discord bot命令不区分大小写?

时间:2019-03-21 15:29:39

标签: javascript node.js discord.js case-sensitive

我为不和谐的bot创建了一个“ roleinfo”命令。我不确定如何使角色搜索不区分大小写。请参阅下面的代码:

const Discord = require("discord.js");

module.exports.run = async (bot, message, args) => {

    //Message checks
    if (!args[0]) return message.channel.send("You must specify a role name");

    //Grab args and specify as rolename
    let roleName = `${args[0]}`

    //@rolename
    let roleMention = message.guild.roles.find(roles => roles.name === roleName)

    let rolefind = message.guild.roles.find(roles => roles.name === roleName)
    if (!rolefind) return message.channel.send(`Can't find role ${args[0]}`);

    //Filter members for role
    let membersWithRole = message.guild.members.filter(member => {
        return member.roles.find(roles => roles.name === roleName);
    }).map(member => {
        return member.user.username;
    })

    let serverembed = new Discord.RichEmbed()
        .setColor("#FFD700")
        .addField("Role name", roleMention)
        .addField("Number of users with the role", rolefind.members.size)
        .addField("Users with the role", membersWithRole.join("\n"))


    message.channel.send(serverembed);
}

module.exports.help = {
    name: "roleinfo",
    usage: "``prefix`` roleinfo or ``prefix`` roleinfo rolename",
    description: "Displays detailed role information",
}

我知道我必须使用.toLowerCase()或.toUpperCase(),但是我不确定在这种情况下如何使用/在何处使用。有人可以帮我吗?将不胜感激。预先感谢!

3 个答案:

答案 0 :(得分:1)

也许这样的事情对您有用? (干编码,YMMV。)

这个想法是在全局角色列表和每个成员角色列表中,两个用于查看角色名称的过滤语句中使用.toLowerCase()

module.exports.run = async (bot, message, args) => {
  const roleName = args[0];
  //Message checks
  if (!roleName) return message.channel.send("You must specify a role name");

  const roleFind = message.guild.roles.find(roles => roles.name.toLowerCase() === roleName.toLowerCase());
  if (!roleFind) return message.channel.send(`Can't find role ${roleName}`);

  const memberNamesWithRole = [];
  message.guild.members.forEach(member => {
    if (member.roles.some(memberRole => memberRole.name.toLowerCase() === roleName.toLowerCase())) {
      memberNamesWithRole.push(member.user.username);
    }
  });

  const serverembed = new Discord.RichEmbed()
    .setColor("#FFD700")
    .addField("Role name", roleName)
    .addField("Number of users with the role", memberNamesWithRole.length)
    .addField("Users with the role", memberNamesWithRole.join("\n"));

  message.channel.send(serverembed);
};

答案 1 :(得分:0)

就像你自己说的那样,就做

roleMention = message.guild.roles.find(roles => roles.name.toLowerCase() === roleName.toLowerCase())

那将使:

'Role-name' === 'Role-NAME'

'role-name' === 'role-name'

答案 2 :(得分:0)

使用.toLowerCase()或.toUpperCase()可能会产生有关特殊Unicode字符的问题。

因此,请使用:String.prototype.localeCompare() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

对于更改,您只需要编辑委托人roles => roles.name === roleName