Search code examples
discord.net

Discord.Net Refresh user role


So, I'm working on Discord.Net and want to get if user has certain role
I wrote this code:

public bool IsAlreadyHasAffiliation(SocketGuildUser user)
{
    IReadOnlyCollection<SocketRole> roles = user.Roles;
    foreach(SocketRole role in roles)
    {
        if (SpecifiedRoles.ContainsValue(role.Id)) return true;
    }
    return false;
}

It works fine but has some problem: Don't get the role that added by bot after bot started.

For example after I added "Role1" via bot and execute above function, it work like user don't have Role1. How can I get live update of role in bot?


Solution

  • If you're noticing strange behaviour in relation to users, which you are, then it's most likely down to the recent Privileged Intents update. Discord.NET caches (downloads) users and uses events such as GuildUserUpdated to keep this cache up to date in the background. Without the Guild Members intent Discord.NET can not keep its user cache up to date, causing problems such as this.

    To fix the problem enable the Guild Members privileged intent on the Bot tab of your bot's page on the Discord developer's portal.

    If that doesn't work then use the nightly versions of Discord.NET and specify all of the intents that you need in the DiscordSocketConfig. To use the nightly versions, add https://www.myget.org/F/discord-net/api/v3/index.json as a package source on NuGet package manager.

    Here's a DiscordSocketConfig which specifies gateway intents (only available on nightly):

    new DiscordSocketConfig 
    {
        GatewayIntents = 
            GatewayIntents.Guilds |
            GatewayIntents.GuildMembers |
            GatewayIntents.GuildMessageReactions | 
            GatewayIntents.GuildMessages | 
            GatewayIntents.GuildVoiceStates,
        ...
    });