类型错误:无法使用劈开命令读取NULL的属性(正在读取状态

2022-02-23 00:00:00 javascript discord.js

我使用的是discord.js V13,尝试使用成员在线状态检查其状态时收到以下错误:

错误:

TypeError: Cannot read properties of null (reading 'status')
    at /home/runner/DinBot-Slash-CMDS/slashcmds/utilidad/serverinfo.js:59:76
    at Map.filter (/home/runner/DinBot-Slash-CMDS/node_modules/discord.js/node_modules/@discordjs/collection/dist/index.js:1:2066)
    at Object.run (/home/runner/DinBot-Slash-CMDS/slashcmds/utilidad/serverinfo.js:59:43)
    at Client.<anonymous> (/home/runner/DinBot-Slash-CMDS/index.js:43:18)
    at Client.emit (node:events:390:28)
    at InteractionCreateAction.handle (/home/runner/DinBot-Slash-CMDS/node_modules/discord.js/src/client/actions/InteractionCreate.js:70:12)
    at Object.module.exports [as INTERACTION_CREATE] (/home/runner/DinBot-Slash-CMDS/node_modules/discord.js/src/client/websocket/handlers/INTERACTION_CREATE.js:4:36)
    at WebSocketManager.handlePacket (/home/runner/DinBot-Slash-CMDS/node_modules/discord.js/src/client/websocket/WebSocketManager.js:350:31)
    at WebSocketShard.onPacket (/home/runner/DinBot-Slash-CMDS/node_modules/discord.js/src/client/websocket/WebSocketShard.js:443:22)
    at WebSocketShard.onMessage (/home/runner/DinBot-Slash-CMDS/node_modules/discord.js/src/client/websocket/WebSocketShard.js:300:10)*

编码:

const members = interaction.guild.members.cache;
  .addField('Presencia', 
      `**Conectado:** ${members.filter(member => member.presence.status === 'online').size}
` + 
      `**Ausentes:** ${members.filter(member => member.presence.status === 'idle').size}
` + 
      `**No Molestar:** ${members.filter(member => member.presence.status === 'dnd').size}
` + 
      `**Desconectado:** ${members.filter(member => member.presence.status === 'offline').size}
` + 'u200b'
   )

解决方案

首先,确保启用了GUILD_PRESENCES意图:https://stackoverflow.com/a/68528046/6126373

在V13中,presence属性can now be null,因此请确保还使用optional chaining operator或通过检查member.presence是否为真来进行检查:

members.filter((member) => member.presence?.status === 'online').size;

// OR

members.filter((member) => member.presence && member.presence.status === 'online').size;

相关文章