角色在刚创建后为null



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

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

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);
}
create role函数返回创建的角色。只需存储它,而不是试图从角色列表中获取它。创建新角色时,在激发角色创建事件之前,缓存不会更新,因此尝试在创建后立即获取缓存总是会失败。
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);

相关内容

  • 没有找到相关文章

最新更新