Lawyer
Lawyer

Reputation: 19

Discord.js Userinfo command TypeError: Cannot read property 'roles' of null

I apologize for that, I really don't like asking for help, but I can't find a solution.

I am creating a userinfo command for my bot, so far so good, but I want to get information from a user who is not on the server where the command was executed, but he is on another server where the bot is, as I am using a function to collect the positions, I get an error, so I would like that, if the user is not on the bot server, he would return me another embed, containing only the account id, name and creation date information.

  async run({ message, args, prefix, author }, t) {
    moment.locale("pt-BR");

    try {
      const user = 
        this.client.users.cache.get(args[0]) ||
          message.mentions.members.first() ||
          message.author;

      const flags = [];
      this.Flags(user, flags);

      const roles = [];
      this.Roles(user, roles, message);

      let presence;
      if (!user.presence.activities.length) presence = "Não está jogando nada";
      else presence = user.presence.activities.join(", ");

      const device = this.Device(user);
      const joined = `${moment(user.joinedAt).format("L")} ( ${moment(
        user.joinedAt
      )
        .startOf("day")
        .fromNow()} )`;
      const created = `${moment(
        this.client.users.cache.get(user.id).createdAt
      ).format("L")} ( ${moment(this.client.users.cache.get(user.id).createdAt)
        .startOf("day")
        .fromNow()} )`;

      const USERINFO = new ClientEmbed(author)
        .setTitle(flags + ` ${user.username}`)
        .addFields(
          { name: "<:richPresence:843144574234394655>┆**Status:**", value: `\`\`\`diff\n- ${presence}\`\`\`` },
          { name: "**Nome do Usuário:**", value: user.tag, inline: true },
          {
            name: "**Nickname no Servidor:**",
            value: !!user.nickname ? user.nickname : "Nenhum Nickname",
            inline: true,
          },
          { name: "**ID do Usuário:**", 
            value: user.id,
            inline: true
          },
          { name: "**Conta Criada:**", value: created, inline: true },

          { name: "**Entrada no Servidor:**", value: joined, inline: true },
          {
            name: "**Dispositivo:**",
            value: String(device).replace("null", "Nenhum"),
            inline: true,
          },
          {
            name: `**Cargos no Servidor**`,
            value: roles,
          }
        )
        .setThumbnail(user.displayAvatarURL({ dynamic: true }))
        .setFooter(
          `Comando solicitado por ${message.author.tag}`,
          message.author.displayAvatarURL({ dynamic: true })
        );

      message.quote(USERINFO);
    } catch (err) {
      console.log(`ERRO NO COMANDO USERINFO\nERROR: ${err}`);
    }
  }

Upvotes: 0

Views: 160

Answers (2)

abisammy
abisammy

Reputation: 562

I beleive your problem is that you are getting the account information as a User property.

The problem with this is that guild members and users are different. Guild members, hold additional information for a user in a specific server, such as roles.

Currently you get the profile information from this variable:

const user = 
this.client.users.cache.get(args[0]) || // This is a user property
message.mentions.members.first() || // This is a member propery
message.author; // This is a user property

The problem with this, is that it sometimes it will return a user, which doesnt have any roles stored in its data.

Here is a possible fix:

 // We need to make sure they run this in a server so we can access the roles
if (!message.guild) return message.channel.send("This command must be ran in a server")

// This will always return a guild member
const user = 
    message.guild.members.cache.get(args[0]) ||
    message.mentions.members.first() ||
    message.member;

You can read about the User and Member on the discord.js docs

Upvotes: 1

theusaf
theusaf

Reputation: 1802

You can use the Guild.member(User) to fetch the GuildMember from the inputted user, or null.

If the result is null, then the user does not exist in the server.

const user = 
  this.client.users.cache.get(args[0]) ||
  message.mentions.members.first() ||
  message.author;

// you should also probably check that the command is run in a guild channel

const guildMember = message.guild.member(user);

if (guildMember) {
  // include roles in embed
} else {
  // don't include roles in embed
}

Upvotes: 1

Related Questions