When I try to pass a ulong discordId through await user.AddRoleAsync(role), I get the error that Object reference not set to an instance of an object, meaning that user is null.
I have tried
private async Task GiveRoleAsync(DiscordSocketClient client, ulong discordId, SocketGuild guild)
{
try
{
if (!string.IsNullOrEmpty(discordId.ToString()) && guild != null)
{
Console.WriteLine(discordId);
var role = guild.Roles.FirstOrDefault(x => x.Name == "Acolyte");
var roleId = role?.Id;
if (role != null)
{
var user = guild.GetUser(discordId);
if (user != null)
{
await user.AddRoleAsync(role);
}
else
{
Console.WriteLine("User not found in the guild.");
}
}
else
{
Console.WriteLine("Role not found.");
}
}
else
{
Console.WriteLine("User or Guild ID is null.");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
However, I always receive the error that "User not found in the guild.", even when manually inserting my own discord id via the client. As a note, I am trying to gather discordIds from a database and update roles according to certain parameters, and Console.WriteLine(discordId) works, but Console.WriteLine(user.Id) prints null. Additionally, I have the Server Members Intent enabled as I am able to do something very similar using a select menu.
private async Task GrabRolesHandler(SocketMessageComponent arg)
{
try
{
if (arg.User != null && arg.GuildId != null)
{
var text = (arg.Data.Values);
var userId = arg.User.Id;
Console.WriteLine(userId);
SocketGuild guild = _client.GetGuild(arg.GuildId.Value);
var role = guild.Roles.FirstOrDefault(x => x.Name == text);
var roleId = role?.Id;
if (role != null)
{
var user = guild.GetUser(userId);
if (user != null)
{
if (user.Roles.Contains(role))
{
await user.RemoveRoleAsync(role);
await arg.RespondAsync($"You have **disabled** pings for the <@&{roleId}> role", ephemeral: true);
}
else
{
await user.AddRoleAsync(role);
await arg.RespondAsync($"You have **enabled** pings for the <@&{roleId}> role", ephemeral: true);
}
}
else
{
Console.WriteLine("User not found in the guild.");
}
}
else
{
Console.WriteLine("Role not found.");
await arg.DeferAsync();
}
}
else
{
Console.WriteLine("User or Guild ID is null.");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}