繁体   English   中英

Discord.js:类型错误:无法读取 null 的属性(读取“状态”)

[英]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') 当我 go 在线然后再次离线时,该命令起作用并输出离线作为我的状态。

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

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是 null 那么它应该抛出离线但没有成功。 我怎样才能使这项工作正常进行?

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

此设置是获取状态更新所必需的

将行替换为:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM