我現在正在寫一個 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);
}
uj5u.com熱心網友回復:
create role 函式回傳創建的角色。只需存盤它而不是嘗試從角色串列中獲取它。創建新角色時,快取不會更新,直到角色 created 事件被觸發,因此在創建后立即嘗試獲取它總是會失敗。
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/442254.html
