Я создаю бот-диск с функцией, которая может принимать идентификатор или упомянутого пользователя. Однако, когда я пытаюсь получить входные данные из идентификатора, мне нужно преобразовать его в пользователя, но он преобразован неправильно, и пользователь недопустим, поскольку получение значений из объекта пользователя может привести к ошибке: ссылка на объект не установлена на экземпляр объекта.
Использование команды:
[Command("Add")]
[Summary("Adds a user")]
public async Task BlacklistUser(Discord.WebSocket.SocketGuildUser user)
{
User_Flow_control userFlow = new User_Flow_control(Context.Client);
if (await userFlow.AddUser(user.Id, "New User"))
await ReplyAsync($"Successfully added <@!{user.Id}> as New User");
else
{
await userFlow.UpdateUser(user.Id, "New User");
await ReplyAsync($"Successfully updated <@!{user.Id}> as New USer");
}
}
[Command("Add")]
[Summary("Adds a user")]
public async Task BlacklistUser(ulong userId)
{
User_Flow_control userFlow = new User_Flow_control(Context.Client);
SocketUser user = Context.Client.GetUser(userId);
if (await userFlow.AddUser(user.Id, "New User"))
await ReplyAsync($"Successfully added <@!{userId}> as New User");
else
{
await userFlow.UpdateUser(user.Id, "New User");
await ReplyAsync($"Successfully updated <@!{userId}> as New User");
}
}
Функции:
public async Task<bool> AddUser(ulong userId, string status = "New User")
{
Console.WriteLine($"Adding user {_client.GetUser(userId).ToString() /* It would fail here */} ({userId}) to the database.");
// Ensure that a user profile has not already been created.
List<DataRow> serverUsers = new List<DataRow>();
// Start REading database.
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM MemberServerStatus", connectionString))
{
await connection.OpenAsync();
//get the infraction data
DataTable serverUsersTable = new DataTable();
adapter.Fill(serverUsersTable);
serverUsers.Capacity = serverUsersTable.Rows.Count; //resize it to minimum size
foreach (DataRow row in serverUsersTable.Rows)
{
serverUsers.Add(row);
}
}
// Do the check
foreach (DataRow row in serverUsers)
{
if (Convert.ToUInt64(row[1]) == userId)
return false;
}
// Verified not a duplicate
// Add the new user
string query = "INSERT INTO MemberServerStatus VALUES (@Username, @UserId, @Status)";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
await connection.OpenAsync();
//convert user id
long longId = Convert.ToInt64(userId);
//set the values
command.Parameters.AddWithValue("@Username", _client.GetUser(userId).ToString()); // Fail here.
command.Parameters.AddWithValue("@UserId", longId);
command.Parameters.AddWithValue("@Status", status);
//Execute and add the user into the db
command.ExecuteNonQuery();
}
return true;
}
public async Task UpdateUser(ulong userId, string status)
{
Console.WriteLine($"Updating user {_client.GetUser(userId).ToString() /* It would fail here */} ({userId}) from the database.");
string query = "UPDATE MemberServerStatus SET Username = @Username, Status = @Status WHERE UserID = @UserId";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
await connection.OpenAsync();
//convert user id
long longId = Convert.ToInt64(userId);
//set the values
command.Parameters.AddWithValue("@Username", _client.GetUser(userId).Username); // Fail here.
command.Parameters.AddWithValue("@UserId", longId);
command.Parameters.AddWithValue("@Status", status);
//Execute and add the user into the db
command.ExecuteNonQuery();
}
}