简体   繁体   English

Discord.js:无法读取Null的属性“名称”-我该如何解决?

[英]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. 我想出了如何让我的Discord机器人每当特定用户玩特定游戏时将图像发送到特定频道,但是我还有另一个问题。

When the application closes, I get this error saying, "Cannot read property 'name' of null." 当应用程序关闭时,出现此错误,提示"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 . 我没有尝试过任何东西,因为我不知道如何使用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 . 相反,它无法读取null name 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 . 用户停止玩游戏时最有可能引发此错误,因为newMember.presence.game在逻辑上将为null Then, when you try to read name of newMember.presence.game , you receive your error. 然后,当您尝试读取newMember.presence.game name时,会收到错误消息。

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);
  }    
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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