Discord.js: TypeError: Cannot read properties of null (reading 'status')

Discord.js: TypeError: Cannot read properties of null (reading 'status')

所以我有一个输出用户信息的命令。虽然大多数字段都没有问题,但 Status 字段对我来说还是有问题的。

这是命令的代码:

import { Command } from '@sapphire/framework';
import { MessageEmbed } from 'discord.js';

export class UserInfoCommand extends Command {
    constructor(context, options) {
        super(context, {
            ...options,
            name: 'userinfo',
            description: 'Retrives user information.',
            aliases: ['user'],
        });
    }

    async messageRun(message, args) {
        const userInfo = await args.pick('member').catch(() => message.member);
        const roleMap = userInfo.roles.cache.mapValues(roles => roles.name);
        const roleArray = Array.from(roleMap.values());

        const userEmbed = new MessageEmbed()
            .setTitle(`Information about ${userInfo.displayName}#${userInfo.user.discriminator}`)
            .setColor(0xC63D85)
            .setThumbnail(userInfo.displayAvatarURL())
            .addField('ID', `${userInfo.id}`, true)
            .addField('Status', `${userInfo.presence.status}`, true)
            .addField('Account Created:', `${userInfo.user.createdAt}`)
            .addField('Joined on:', `${userInfo.joinedAt}`)
            .addField('Server Nickname:', `${userInfo.displayName}`)
            .addField('Server Roles:', `${roleArray.join(', ')}`);
        return message.channel.send({ embeds: [userEmbed] });
    }
}

当和我一起执行命令时(或自机器人启动以来离线的用户),它抛出 TypeError: Cannot read properties of null (reading 'status')。当我在线然后再次离线时,该命令起作用并输出离线作为我的状态。

我确实启用了正确的意图。

const client = new SapphireClient({
    intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_MEMBERS', 'GUILD_PRESENCES'],
    disableMentionPrefix: true,
    typing: true,
    presence: {
        activities: [
            {
                name: 'Captain\'s commands!',
                type: 'LISTENING',
            },
        ],
    },
});

我尝试使用 if 语句,其中如果 userInfo.presence.status 为空,则它应该抛出离线,但没有成功。我怎样才能正确解决这个问题?

确保您在应用程序机器人设置中启用了 PRESENCE INTENT 选项

需要此设置才能获取状态更新

将行替换为:

.addField('Status', `${userInfo.presence? userInfo.presence.status : "offline"}`, true) // if presence is truthy, output the string, else, the user is offline

一个有效的简单空检查。可能是我之前的方法不对