简体   繁体   中英

Discord.js: Cannot Read Property “Name” of Null - How do I fix this?

I figured out how to make my Discord bot send an image to a certain channel whenever a specific user plays a specific game, but I have another problem.

When the application closes, I get this error saying, "Cannot read property 'name' of null." How do I fix this?

I haven't tried anything because I don't know anything about how I should use null .

// Game Detector \\
client.on("presenceUpdate", (oldMember, newMember) => {
if(newMember.id === '406742915352756235') {
    if(newMember.presence.game.name === 'ROBLOX') { // New Example: ROBLOX
        console.log('ROBLOX detected!');
        client.channels.get('573671522116304901').send('**Joining Game:**', {
            files: [
                "https://cdn.discordapp.com/attachments/567519197052272692/579177282283896842/rblx1.png"
                ]
            });
        }
    }
});

I expected the code to work, even when the application closes. Instead, it cannot read name of null . How can I fix this error?

This error is most likely thrown when the user stops playing a game, because newMember.presence.game will logically be null . Then, when you try to read name of newMember.presence.game , you receive your error.

Use this revised code:

client.on('presenceUpdate', (oldMember, newMember) => {
  if (newMember.id !== '406742915352756235') return; // only check for this user

  if (newMember.presence.game && newMember.presence.game.name === 'ROBLOX') {
    console.log('ROBLOX detected.');

    const channel = client.channels.get('573671522116304901');
    if (!channel) return console.log('Unable to find channel.');

    channel.send('**Joining Game:**', {
      files: ['https://cdn.discordapp.com/attachments/567519197052272692/579177282283896842/rblx1.png']
    }).catch(console.error);
  }    
});

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