我想出了如何让Discord bot在特定用户玩特定游戏时将图像发送到特定频道,但是我还有另一个问题。
应用程序关闭时,出现此错误,提示"Cannot read property 'name' of 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"
]
});
}
}
});
即使应用程序关闭,我也希望代码能够正常工作。相反,它无法读取name
中的null
。如何解决此错误?
答案 0 :(得分:1)
用户停止玩游戏时最有可能引发此错误,因为newMember.presence.game
在逻辑上将是null
。然后,当您尝试读取name
中的newMember.presence.game
时,会收到错误消息。
使用此修改后的代码:
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);
}
});