So I have a command that outputs user information. Though most fields have no problems, the Status field is rather buggy for me.
This is the code for the command:
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] });
}
}
When executing the command with me (or a user offline since the bot was started), it throws TypeError: Cannot read properties of null (reading 'status')
. When I go online and then offline once again, the command works and outputs offline as my status.
I do have the proper intents enabled.
const client = new SapphireClient({
intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_MEMBERS', 'GUILD_PRESENCES'],
disableMentionPrefix: true,
typing: true,
presence: {
activities: [
{
name: 'Captain\'s commands!',
type: 'LISTENING',
},
],
},
});
I've tried to use an if statement where if userInfo.presence.status
is null then it should throw offline instead but that didn't work out. How can I make this work out properly?
Replaced the line with:
.addField('Status', `${userInfo.presence? userInfo.presence.status : "offline"}`, true) // if presence is truthy, output the string, else, the user is offline
A simple null check that worked. Probably my previous method was wrong.