DiscordJS - refreshing a member's role cache

Viewed 15

I have some code that's supposed to assign a role but only if a user doesn't have the role yet (don't want to spam the discord api with redundant role assignments).

let member = await guild.members.fetch(user.discord_id);
if (member.roles.cache.find(role => role.id == roleId)) {
    continue;
}
let role = guild.roles.cache.find(role => role.id == roleId);
await member.roles.add(role);

This works the first time (ie it only assigns the role if the user didn't have it at the start of my script), but the problem is that member.roles.cache never seems to update. So even after assigning the role, it doesn't contain it, or if I manually add/remove the role in the discord app, the cache never reflects this change.

I haven't been able to find a way to refresh the cache during my program's lifecycle.

Any help would be greatly appreciated. Thanks!

1 Answers

And just after I post this, I find the answer :

let member = (await guild.members.fetch({ user: user.discord_id, force: true }));

This makes sure it's bypassing the cache when fetching the member's data.

Related