washingm
washingm

Reputation: 87

Discord.js, Finding if user has a role by ID from an Array

I am making an equip command for my Discord.js bot, I'm trying to make it search through a user's roles, remove any currently equipped color roles, then equip the one they requested.

I am having trouble on focusing the filter on the array of role IDs, as it just returns a blank array despite the user having that role.

Here's the code I was trying out:

hasRoles = []

for (const x of guildRoles)
    hasRoles.push(x.roleid)

console.log(hasRoles)

let user = interaction.options.getUser('youruseroption') || interaction.user
const guild = client.guilds.cache.get("646074330249429012");
let member = await guild.members.cache.get(user.id);
const memberRoles = member.roles.cache
  .filter((roles) => roles.id == `${hasRoles}`)
  .map((role) => role.toString());

console.log(memberRoles)

// await interaction.followUp({ ephemeral: true, embeds: [embed1] });

Here's a sample of what the role array looks like:

const guildRoles = [
    {
        role: "turquoise",
        color: "#6ba8a8",
        price: 6000,
        roleid: '813152038346817597',
        id: `turquoise`,
        availAt: '10'
    },
    {
        role: 'clay',
        color: "#916d6d",
        price: 6000,
        roleid: '813152807720583180',
        id: `clay`,
        availAt: '10'
    },
    {
        role: 'light brown',
        color: "#c2a289",
        price: 6000,
        roleid: '813153670467944459',
        id: `lbrown`,
        availAt: '10'
    }
]

Upvotes: 1

Views: 844

Answers (1)

Zsolt Meszaros
Zsolt Meszaros

Reputation: 23170

Your hasRoles is an array of IDs and you can't compare a stringified array to a string (i.e. roles.id == `${hasRoles} won't work).

You can however use the Array#includes method to check if the hasRoles array contains the current role.id:

// you can use map here to get an array of roleids
let hasRoles = guildRoles.map((r) => r.roleid);
let user = interaction.options.getUser('youruseroption') || interaction.user;
let guild = client.guilds.cache.get('646074330249429012');
// did you mean fetch?
let member = await guild.members.fetch(user.id);
let memberRoles = member.roles.cache
  .filter((role) => hasRoles.includes(role.id))
  .map((role) => role.toString());

console.log(memberRoles);

Upvotes: 1

Related Questions