Discord.NET中GetUser返回null,无法为用户添加角色
问题:调用AddRoleAsync时User为null,无法定位服务器内用户
调用await user.AddRoleAsync(role)传入ulong类型的DiscordID时,触发「对象引用未设置到对象实例」错误,确认是user对象为null导致。
我编写了以下测试方法:
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()); } }
但无论手动传入自己的DiscordID,还是从数据库读取ID传入,都会输出「User not found in the guild.」。Console.WriteLine(discordId)能正常打印出正确的ID,但尝试输出user.Id时会得到null。
我已经启用了Server Members Intent,且通过选择菜单实现的同类功能可以正常运行,对应代码如下:
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()); } }
内容的提问来源于stack exchange,提问作者Soggy Meat
相关产品推荐
相关产品推荐

