简体   繁体   中英

Roles checker bot - Discord.js - ReferenceError: member is not defined

I'm trying to set up a bot for my Discord server. Basically, whenever anyone type "test" to a specific channel (help-channel) the bot will display their roles. If they have a role, say, Baker, the bot will say "You're all set, enjoys them sweet cakes!". If they don't, the bot will say "You do not have the Baker role."

Here's my code:

client.on('message', (message) => {
 if (message.content === 'test') {
  if (member.roles.cache.some((role) => role.name === '<Baker>'))
   message.reply("You're all set , enjoys them sweet cakes !");
  else message.reply('You do not have the Baker role.');
 }
});

I can't get it to work; the error log said:

ReferenceError: member is not defined.

Also, I have multiple roles on the server (Baker, Tester, Chief, etc.). So, do I have to write the code for each of them?

You're getting this error because member is in fact, not defined. Instead, you'll want to use message.member


As for your second question, probably yes. Something that comes to mind would be creating an array of every role name and then creating a for...of loop.

const roles = ['<Baker>', '<Dancer>', '<Programmer>', '<Actor>'];

// iterate a loop through all elements in the array
for (role of roles) {
 if (message.member.roles.cache.some((r) => r.name === role))
  console.log(`${message.author.username} has the ${role} role.`);
}

You could also mess around with the .filter() method.

const roles = ['<Baker>', '<Dancer>', '<Programmer>', '<Actor>'];

console.log(
 `Out of the roles in the array, ${
  message.author.username
 } has these roles: ${roles
  .filter((role) => message.member.roles.cache.some((r) => r.name === role))
  .join('\n')}`
);

member is not defined that's right. If you want member to be the person who initiated the command you would need to use message.member , if you want to get a specified member you could use message.guild.members.cache.get(<user id here>) .

And you can shorten your code, by checking for roles using roles' ids, then it would look like if(message.member.roles.cache.has(<role id>) . It would also prevent from checking for roles that have same names

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM