C#C
C#2y ago
Rhys

Discord.net help - Trying to access a users roles

Does anybody know a method I can use to access a users discord roles whilst I am logging into my application so I can either allow them into the app or disallow them?

If you have any guides on how I could do this or some examples that would give some ideas on how I can do this as currently my method is not working.

Here is how it looks.

c#
    private async Task<bool> IsUserInServerWithRole(string discordUserId)
    {
        ulong requiredGuildId = 123456790; 
        ulong requiredRoleId = 123456790; 

        // Attempt to get the guild
        var guild = _botService.Client.GetGuild(requiredGuildId);
        if (guild == null)
        {
            _logger.LogWarning("Guild not found.");
            return false;
        }

        var user = guild.GetUser(ulong.Parse(discordUserId));
        if (user != null)
        {
            _logger.LogInformation($"User {user.Username} has {user.Roles.Count} roles.");
            foreach (var role in user.Roles)
            {
                _logger.LogInformation($"Role: {role.Name}, ID: {role.Id}");
                if (role.Id == requiredRoleId)
                {
                    _logger.LogInformation($"Match found for required role ID: {role.Id}");
                }
            }
        }
        else
        {
            _logger.LogWarning("User not found in guild.");
        }

        bool hasRole = user.Roles.Any(role => role.Id == requiredRoleId);
        return hasRole;
    }


Just looking for more ideas about this approach. My brain is starting to run out of them.

Tia
Was this page helpful?
Discord.net help - Trying to access a users roles - C#