我对 Node.js 相当陌生,目前正在开发一个 Discord 机器人。我试图让我的机器人根据用户传递的参数分配服务器 Angular 色。我知道我可以找到特定 Angular 色的名称,然后根据他们的回答为他们分配该 Angular 色。
但是:我的管理员几乎每周都会创建和删除 Angular 色,而我不能每周编辑代码来更新要分配的可用 Angular 色列表,因此我决定创建一条线的代码将提取用户传递的参数,然后在将 args 作为参数传递时查找 Angular 色名称。
这是我的代码的样子:
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 。当机器人响应时,它会将 Angular 色读取为空。我已经和这个问题斗争了好几个星期了,现在我已经无计可施了。有谁知道我该如何解决这个问题?编辑:这是我的意思的一个例子:
!role top
“Top”是此处的 Angular 色名称。
最佳答案
我认为问题在于您将 Angular 色名称与 Role.toString()
进行比较。使用 Role.toString()
返回一个提及,而 Role.name
只是 Angular 色的名称。
我会这样写:
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);
}
编辑:如果您只想使用 Angular 色的名称,而不提及它,您可以这样做(假设 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);
}
关于javascript - 根据参数为成员分配角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53215748/