如何解决Discord.net 任务调用问题
我正在尝试在 .NET 中创建一个 discord 机器人,并使用一个命令将用户放在标记上。例如,服务器管理员为用户提供 50 个标记,该用户将删除其所有角色,并获得一个名为“标记”的角色。然后,将出现一个文本通道,用户需要在其中发送 50 条垃圾邮件以删除标记,然后他才能取回所有内容。我已经创建了用于提供标记和删除它们的命令,但是当我尝试通过从 Program.cs 调用该函数来删除某人的标记时,它出于某种原因给出了一个空指针异常。代码如下:
Program.cs 事件:
private async Task MessageRecieved(SocketMessage arg)
{
//Checking if the user has markers
var roles = (arg.Author as SocketGuildUser).Roles;
bool imaMarkere = false;
foreach (var role in roles)
{
if (role.Id == 844558286611152917)
imaMarkere = true;
}
if (arg.Channel.Id == 844558185024585770 && imaMarkere)
{
int markerCount = 0;
using (sqliteConnection con = new sqliteConnection(connectionString))
{
con.open();
string query = $"select markercount from markers";
var com = con.CreateCommand();
com.CommandText = query;
var rdr = com.ExecuteReader();
if (rdr.Read())
{
markerCount += Convert.ToInt32(rdr["markercount"]) - 1;
}
rdr.Close();
//Removing 1 marker per message recieved
if (markerCount > 0)
{
com.CommandText = $"update markers set markercount={markerCount} where userid='{arg.Author.Id}'";
com.ExecuteNonQuery();
}
//If no markers are left returning the user roles
else
{
Commands c = new Commands();
await c.Skini(arg.Author as IGuildUser);
}
con.Close();
}
}
else return;
}
命令.cs
[Command("skini"),RequireUserPermission(GuildPermission.Administrator,ErrorMessage = "Nemate potrebnu dozvolu ``ADMINISTRATOR``")]
public async Task Skini(IGuildUser user = null)
{
if(user == null)
{
await ReplyAsync($"{Context.User.Mention},kome da skinem?");
}
string rolesstring = "";
string[] roles;
using (sqliteConnection con = new sqliteConnection(connectionString))
{
con.open();
var com = con.CreateCommand();
string readQuery = "select pastroles from markers";
com.CommandText = readQuery;
var rdr = com.ExecuteReader();
if (rdr.Read())
{
rolesstring += rdr["pastroles"].ToString();
}
rdr.Close();
string deleteQuery = $"delete from markers where userid = '{user.Id}'";
com.CommandText = deleteQuery;
com.ExecuteNonQuery();
con.Close();
}
roles = rolesstring.Split(",");
foreach (var roleid in roles)
{
var role = Context.Guild.GetRole(Convert.ToUInt64(roleid));//this line is where the exception happens
if(!role.IsEveryone)
await user.AddRoleAsync(role);
}
var roleMarkeri = Context.Guild.GetRole(844558286611152917);
await user.RemoveRoleAsync(roleMarkeri);
var EmbedBuilder = new EmbedBuilder()
.WithTitle("**MARKERI**")
.WithColor(Color.Blue)
.WithDescription($":white_check_mark: {Context.User.Mention} je **skinuo** markere {user.Username}")
.WithFooter(footer =>
{
footer
.WithText("Marker log");
});
Embed embed = EmbedBuilder.Build();
await ReplyAsync(embed: embed);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。