刚刚创建后角色为空

Role is null after just creating it

我现在正在写一个 shadowban 命令,这段代码会导致问题,即使在创建 shadowban 角色之后,var 角色将为空。

这可能是我以某种形式造成的一个非常愚蠢的错误,但我就是想不通。

if (!Context.Guild.Roles.Any(x => x.Name == shadowRoleName))
   {
    await Context.Guild.CreateRoleAsync(shadowRoleName, null, Color.DarkerGrey, false, null);
   }
var role = Context.Guild.Roles.FirstOrDefault(x => x.Name == shadowRoleName);

我不知道我的代码的其他部分是否会导致这种情况发生,所以这里是整个命令

    [Command("shadowron")]
    [RequireUserPermission(GuildPermission.Administrator, ErrorMessage = "Koa adminrechte, nt aroun")]
    public async Task ShadowBanUserAsync(SocketGuildUser user = null)
    {
        const string shadowRoleName = "shadowron";
        bool alreadyShadowBanned = false;

        if (user == null)
        {
            await ReplyAsync("wer soll shadowbanned wöra?");
            return;
        }

        if (!Context.Guild.Roles.Any(x => x.Name == shadowRoleName))
        {
            await Context.Guild.CreateRoleAsync(shadowRoleName, null, Color.DarkerGrey, false, null);
        }
        var role = Context.Guild.Roles.FirstOrDefault(x => x.Name == shadowRoleName);

        foreach (SocketRole userRole in user.Roles)
        {
            if (userRole.Name == shadowRoleName)
            {
                alreadyShadowBanned = true;
                continue;
            }

            if (userRole.IsEveryone)
            {
                continue;
            }
            await user.RemoveRoleAsync(userRole.Id);
        }

        if (alreadyShadowBanned)
        {
            await ReplyAsync($"Da {user.Mention} isch scho shadowbanned rip");
            return;
        }

        await ReplyAsync($"Da {user.Mention} isch jetz shadowbanned uff");
        await user.AddRoleAsync(role);
    }

创建角色函数returns创建的角色。只需存储它而不是尝试从角色列表中获取它。当您创建一个新角色时,缓存在角色创建事件被触发之前不会更新,因此尝试在创建后立即获取它总是会失败。

IRole role = Context.Guild.Roles.FirstOrDefault(x => x.Name == shadowRoleName);

if (role == null) 
    role = await Context.Guild.CreateRoleAsync(shadowRoleName, null, Color.DarkerGrey, false, null);

// rest of code...

await user.AddRoleAsync(role);