Search code examples
javascriptdiscord.js

How to get all user roles from interaction?


I'm using discord.js and need to get all current roles from user, which interacted by slash command. How can I do that?

I tried using interaction.guild.members.cache.forEach(r => { currentRoles.push(r) });, but it's didn't worked well.


Solution

  • According to Discord.js Docs V14 a role manager is present for each member instance.

    const memberInstance = interaction.guild.members.cache.get(interaction.user.id);
    const roleArray = member.roles.cache.map(role => { return role.id; });
    

    This snippet in particular loops through all roles the member inherits and returns an Array with all role ids. If you need more data than the id you can modify the return function to your needs.

    Note: Even though we cannot see that the @everyone role is assigned to every user on Discord, it is. Therefor will this snipped above include the everyone role id. If you do not want this role to be included in the Array you need to filter the id. A possible way to do so is modifying the return function:

    const everyoneRoleId = "236236";
    member.roles.cache.map(role => { if (role.id != everyoneRoleId) return role.id; });
    

    The updated snippet does not include the @everyone role anymore.