0

我正在尝试为 Discord 制作一个虚荣机器人,但我不确定我是否使用了正确的事件。这是我的代码:

client.on("presenceUpdate", newPresence => {
    let vanityRole = newPresence.guild.roles.cache.find(role => role.id === "940679835456536596");
  const activity = newPresence.member.user.presence.activities[0].state
  if (activity === null) return;
  if (activity.includes("gg/pm")) {
    let memberTarget = newPresence.guild.members.cache.get(newPresence.member.id);
    memberTarget.roles.add(vanityRole);
    const vanity = new Discord.MessageEmbed()
      .setColor(color)
      .setDescription(`<@${memberTarget.id}>, thanks for putting us in your status <3`);
      message.channel.send(vanity)
  }
  else return;
});

这是我收到的错误: 在这一行:const activity = newPresence.member.user.presence.activities[0].state 错误:[TypeError: Cannot read property 'state' of undefined] repl process died unexpectedly: exit status 1

谢谢

4

1 回答 1

0

您的其中一个项目newPresence.member.user.presence.activities等于一个空的arrayundefined,因此newPresence.member.user.presence.activities[0] === undefined

你可以试试:const activity = newPresence.member.user.presence.activities[0]?.state

可选的链接运算符 (?.) 使您能够读取位于连接对象链深处的属性值,而无需检查链中的每个引用是否有效。

于 2022-02-08T20:30:44.517 回答