我刚接触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。当漫游器响应时,它会将角色读取为null。我已经为此进行了数周的角力,而我的机智已告一段落。有人知道我该如何解决吗?编辑:这是我的意思的示例:
!role top
“最高”是这里的角色名称。
答案 0 :(得分: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);
}