Garrick
Garrick

Reputation: 1

"Cannot read property 'name' of null" when trying to read server name

When I do console.log(message.guild.name), it works normally, giving me the name of the guild a message was said in. However, for some reason, when running that code while DMing a user, it gives me the following error:

(node:36816) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of null'

Upvotes: 0

Views: 389

Answers (1)

Jason
Jason

Reputation: 821

A DM channel isn't in a guild, so can't have a guild attached to it

You need check the message.channel.type property to identify what type of channel it is. A message can come from any of these channel types TextChannel (aka a guild text channel), DMChannel or GroupDMChannel

When looking at channel.type it'll give you one of the following options:

  • dm - a DM channel
  • group - a Group DM channel
  • text - a guild text channel
  • voice - a guild voice channel
  • category - a guild category channel

The way you could do this is:

switch (message.channel.type) {
    case 'text':
        // Do guild stuff
        break;

    case 'dm':
    case 'group':
        // Do DM stuff
        break;

    default:
        // Do stuff on unexpected channel
        break;
}

Upvotes: 2

Related Questions