我最近为我的机器人制作了一个自动角色代码,它读取每个用户的状态,并在他们的状态中有我们的服务器虚荣邀请链接时为他们提供一个角色。代码运行良好,机器人添加了角色,然后删除了它,但这里的问题是它会遍历错误而不会使机器人崩溃:
(node:38) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'includes' of null
(node:38) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 345)
我很确定这是因为机器人无法读取这些离线且没有状态的用户的状态。我会很感激你的帮助,因为我无法解决这个问题。 这是我的代码:
client.on('presenceUpdate', async (oldPresence, newPresence) => {
const role = newPresence.guild.roles.cache.get("832132526302035992");
const member = newPresence.member
const activities = member.user.presence.activities[0];
if (activities && (activities.state.includes( ".gg/moonxile" ) || activities.state.includes("discord.gg/moonxile" ))) {
return newPresence.member.roles.add(role)
.catch(err => {
console.log(err)
return;
})
} else {
if(member.roles.cache.get(role.id)) {
newPresence.member.roles.remove(role)
.catch(err => {
console.log(err)
return;
})
}
}
});
答案 0 :(得分:1)
有些人从存在状态变为无状态时,将没有数据,因此应该进行检查
if (activities && activities.state && (activities.state.includes( ".gg/moonxile" ) || activities.state.includes("discord.gg/moonxile" ))) {
return newPresence.member.roles.add(role)
.catch(err => {
console.log(err)
return;
})
}
答案 1 :(得分:0)
首先检查 activities
,然后检查 activities.state
,最后包括 .include()