Kikkiu
Kikkiu

Reputation: 85

Cannot read property 'roles' of null

I want my bot to send a private message to the user that joins my server.

To do this I used:

 client.on('guildMemberAdd', member => {
   const channel = member.guild.channels.find(ch => ch.name === 'benvenuto');
  channel.send(`Date il benvenuto a ${member}!`);
  member.send('test');
});

As soon as a user joins the server, I get this error:

TypeError: Cannot read property 'roles' of null
    at Client.client.on.message (C:\Users\Kikkiu\Desktop\BotTuttofare\index.js:9:19)
    [...]

The error brings me to this part of the code:

if(message.member.roles.find(r => r.name === "Admin") || message.member.roles.find(r => r.name === "Mod")) {
  if(!message.author.bot) {

  if(message.content == '.del50')
  message.channel.bulkDelete(50)

  if(message.content == '.del100')
  message.channel.bulkDelete(100)

  if(message.content == '.del1')
  message.channel.bulkDelete(2)

  if(message.content == '.del10')
  message.channel.bulkDelete(10)

  if(message.content == '.del2')
  message.channel.bulkDelete(3)
}}

If I remove the part that sends the private message I don't get this error. What could it be?

Upvotes: 2

Views: 6108

Answers (1)

Mr.Dobby
Mr.Dobby

Reputation: 79

I don't think you can find roles on members like this. You use the .find() on guilds (member.guild.roles.find(r => r.name == "Admin"))

If you want to check if they got the corect role something like this should work:

let adminRole = message.guild.roles.get("ADMIN_ROLE_ID") //same with mod role
if (message.member.roles.has(adminRole.id)) {
//If they have admin & mod role they can do this
} else {
//If they do not have the one of the roles, this happens. Either just do return; or do //something like dm them that they don't have roles/permissions
}

But I do suggest you make a seperate commad for this where you use args or something to define how much you want to bulk in a channel, this is just confusing.

Upvotes: 1

Related Questions