So I'm building a bot that is meant to assign a role when the user dms the bot "!Accept" the problem is when I attempt to test this I receive this error
A MessageReceived handler has thrown an unhandled exception.: System.NullReferenceException: Object reference not set to an instance of an object. at Discord.Commands.SocketCommandContext..ctor(DiscordSocketClient client, SocketUserMessage msg) at UBot_CodeV2.Program.d__9.MoveNext() in C:\Users\sarah\source\repos\UBot_CodeV2\UBot_CodeV2\Program.cs:line 70 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Discord.EventExtensions.d__1`1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Discord.WebSocket.DiscordSocketClient.d__132.MoveNext() Object reference not set to an instance of an object.
[Command("Accept")]
public async Task Accepted()
{
var role = Context.Guild.GetRole(780162818729050114);
if ((Context.Guild.GetUser(Context.User.Id).Roles.Contains(role))) return;
await ((SocketGuildUser)Context.User).AddRoleAsync(role);
await Context.User.SendMessageAsync("Welcome! Your next step is to open a ticket with !ticket open Verification");
}
This is the code I have for the task curently
I tried the similar code that you're using, and mine is working. Here the result and I put some comment in the code for you to debug. I will explain more after the code.
[Command("test")]
public async Task TestAsyync()
{
var guild = Context.Client.GetGuild(759016895390154754); // Debug if it's not null
var role = guild.GetRole(776340732075573310); // Debug if it's not null
var user = Context.Guild.GetUser(Context.User.Id); // Debug if it's not null
if (!user.Roles.Contains(role))
{
await user.AddRoleAsync(role);
LogUtils.Info("Add role");
} else
{
LogUtils.Info("User already have role");
}
}
Case(s)
guild
is null probably your bot doesn't have access to the guildrole
or user
is null, there could be issue regarding your bot intents (Why can't my bot dm users a welcome message? (Discord.net C#))await user.AddRoleAsync(role);
return forbidden, you need to set your bot role above the other roleRed square is my bot role, purple one is the role I want to grant
I actually just learn today about this role hierarchy (Discord.NET assigning roles)