簡體   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