Home > OS >  Role is null after just creating it
Role is null after just creating it

Time:03-13

I'm writing a shadowban command right now, and this code is causing problems, even after creating the shadowban role, var role will be null.

This is probably a really stupid error which I caused in some sort of form, but I just can't figure it out.

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);

I have no idea if some other part of my code could be causing this to happen, so here the whole command

    [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);
    }

CodePudding user response:

The create role function returns the role that's created. Simply store that instead of attempting to fetch it from the roles list. When you create a new role, the cache is not updated until the role created event is fired, so attempting to fetch it immediately after creation will always fail.

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);
  • Related