Arthur Gorbana
Arthur Gorbana

Reputation: 17

Discord js TypeError: Cannot read property members

Hello i have this code,

user = message.guild.members.fetch(id2).then((use,err)

And i have this error

TypeError: Cannot read property 'members' of null

Please can yuo help me ?

Thank you

Upvotes: 0

Views: 902

Answers (2)

tipakA
tipakA

Reputation: 162

Your error occurs because the message object refers to a message that was received as a DM. Because of how DMs work, there is no guild or member property for such message (they are left as nulls).

To avoid that, you should handle direct messages slightly differently. The easiest and most commonly used way is to completely stop direct messages from running your message event code. This can be done by adding

if (message.channel.type === 'dm') return;

at the very top of your event.

As that makes it impossible to initiate commands in DMs, even if they don't need to be executed in a guild to work (like ping command for example), this might be not what you want. In such case, you should implement a way to determine if command someone tried to run in DM is "allowed" to be executed there. Implementations for that vary depending on command handling implementation, but snippet below is basic princinple.

client.on('message', message => {
  if (message.author.bot || !message.startsWith(prefix)) return;
  const args = message.content.slice(prefix.length).split(/ /g);
  const command = args.shift().toLowerCase();

  if (command === 'memberinfo') {
    if (message.channel.type === 'dm') return message.reply('this command cannot be run in DMs.');
    // Actual command code
  }
});

Upvotes: 0

ggordon
ggordon

Reputation: 10035

message.guild is not initialized. You could check if it is null before use eg

if(message.guild){
    user = message.guild.members.fetch(id2).then((use,err) ...
}else{
   //do something when it is not initialized
}

Upvotes: 1

Related Questions