[英]Discord.js add specific roles to array
I am working on a Discord bot that assigns roles to users.我正在开发一个为用户分配角色的 Discord 机器人。 If the pinged user and the user who has executed the command has a specific role, I want to add this to a const.如果 pinged 用户和执行命令的用户具有特定角色,我想将其添加到 const。
const role1 = message.guild.roles.cache.find(role => role.name === "role1")
const role2 = message.guild.roles.cache.find(role => role.name === "role2")
const role3 = message.guild.roles.cache.find(role => role.name === "role3")
const roles = [ role1, role2, role3 ]
let pingedUser = message.mentions.members.first();
const userRole = roles.filter(role => pingedUser.roles.cache.has(role.id))
const ownRole = roles.filter(role => message.member.roles.cache.has(role.id));
console.log(userRole);
console.log(ownRole);
I get this error in the console: "Cannot read property 'roles' of undefined"我在控制台中收到此错误:“无法读取未定义的属性'角色'”
I would be very happy if someone has a solution in mind:)如果有人有解决方案,我会很高兴:)
Edit: This is how I am executing the command (index.js):编辑:这就是我执行命令的方式(index.js):
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'testcommand') {
client.commands.get('testcommand').execute(message, args, Discord, client);
}
});
And this is my whole command-file (commands/testcommand.js):这是我的整个命令文件(commands/testcommand.js):
module.exports = {
name: 'testcommand',
description: "",
async execute(message, args, Discord, client) {
const role1 = message.guild.roles.cache.find(role => role.name === "role1")
const role2 = message.guild.roles.cache.find(role => role.name === "role2")
const role3 = message.guild.roles.cache.find(role => role.name === "role3")
const roles = [ role1, role2, role3 ]
let pingedUser = message.mentions.members.first();
if (!pingedUser) {
return
}
const userRole = roles.filter(role => pingedUser.roles.cache.has(role.id))
const ownRole = roles.filter(role => message.member.roles.cache.has(role.id));
console.log(userRole);
console.log(ownRole);
}
}
GuildMemberRoleManager#cache
returns a Collection<Snowflake, Role>
where Snowflake
( id
) is the key and Role
is the value. GuildMemberRoleManager#cache
返回一个Collection<Snowflake, Role>
其中Snowflake
( id
) 是键, Role
是值。 So, you should be checking if the collection has the role.id
key.因此,您应该检查集合是否具有role.id
键。 And you can simplify your code using Array.prototype.filter
.您可以使用Array.prototype.filter
简化代码。 Make sure pingedUser
exists before computing their roles.在计算他们的角色之前确保pingedUser
存在。
if (!pingedUser) {
return message.reply('User mention missing')
}
const roles = [role1, role2, role3]
const userRoles = roles.filter(role => pingedUser.roles.cache.has(role.id))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.