- 88
- 3
Короче, делал кое как класс для отправки анкеты пользователю в тг, он их как бы собирает и отправляет, но нужно ждать ответ от пользователя, а он его не ждёт, либо ждёт, но в базу данных добавляет все ид из List<int> idusersDate = new List<int>(); как можно сделать так, что бы он дожидался ответа, а там уже в зависимости от ответа забивал базу одним ид, либо вовсе выходил, вот класс ниже надо починить
Код:
public class UserMediaSender1
{
private readonly string _connectionString;
private readonly ITelegramBotClient _botClient;
public UserMediaSender1(string connectionString, ITelegramBotClient botClient)
{
_connectionString = connectionString;
_botClient = botClient;
}
public async Task SendUserMediaAsync(long userId, ChatId chatId)
{
string userGender = string.Empty;
int userAge = 0;
string userCity = string.Empty;
using (MySqlConnection connection1 = new MySqlConnection(_connectionString))
{
connection1.Open();
using (MySqlCommand command1 = new MySqlCommand("SELECT * FROM Users WHERE id = @id", connection1))
{
command1.Parameters.AddWithValue("@id", userId);
using (MySqlDataReader reader1 = command1.ExecuteReader())
{
if (reader1.Read())
{
userGender = (string)reader1["Gender"];
userAge = (int)reader1["Age"];
userCity = (string)reader1["City"];
}
}
}
}
List<int> idusersDate = new List<int>();
using (MySqlConnection connection = new MySqlConnection(_connectionString))
{
connection.Open();
using (MySqlCommand command = new MySqlCommand("SELECT * FROM Users WHERE Age BETWEEN @minAge AND @maxAge AND City = @city AND Gender != @gender AND id != @id", connection))
{
command.Parameters.AddWithValue("@minAge", userAge - 2);
command.Parameters.AddWithValue("@maxAge", userAge + 2);
command.Parameters.AddWithValue("@city", userCity);
command.Parameters.AddWithValue("@gender", userGender);
command.Parameters.AddWithValue("@id", userId);
using (MySqlDataReader reader1 = command.ExecuteReader())
{
while (reader1.Read())
{
idusersDate.Add((int)reader1["id"]);
string userData = $"Имя: {reader1["Name"]}\n" +
$"Возраст: {reader1["Age"]}\n" +
$"Пол: {reader1["Gender"]}\n" +
$"Город: {reader1["City"]}\n" +
$"О себе: {reader1["About"]}";
}
}
}
}
foreach (int id in idusersDate)
{
List<IAlbumInputMedia> media = new List<IAlbumInputMedia>();
using (MySqlConnection connection = new MySqlConnection(_connectionString))
{
connection.Open();
using (MySqlCommand command = new MySqlCommand("SELECT photo FROM Photos WHERE user_id = @user_id", connection))
{
command.Parameters.AddWithValue("@user_id", id);
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
byte[] photoBytes = (byte[])reader["photo"];
MemoryStream stream = new MemoryStream(photoBytes);
InputFileStream inputFile = new InputFileStream(stream, $"{id}.jpg");
InputMediaPhoto inputMediaPhoto = new InputMediaPhoto(inputFile);
using (MySqlConnection connection1 = new MySqlConnection(_connectionString))
{
connection1.Open();
using (MySqlCommand command1 = new MySqlCommand("SELECT * FROM Users WHERE id = @id", connection1))
{
command1.Parameters.AddWithValue("@id", id);
using (MySqlDataReader reader1 = command1.ExecuteReader())
{
if (reader1.Read())
{
string userData = $"Имя: {reader1["Name"]}\n" +
$"Возраст: {reader1["Age"]}\n" +
$"Пол: {reader1["Gender"]}\n" +
$"Город: {reader1["City"]}\n" +
$"О себе: {reader1["About"]}";
inputMediaPhoto.Caption = userData;
media.Add(inputMediaPhoto);
reader1.Close();
}
}
}
}
}
}
}
}
using (MySqlConnection connection = new MySqlConnection(_connectionString))
{
connection.Open();
using (MySqlCommand command = new MySqlCommand("SELECT video FROM Videos WHERE user_id = @user_id", connection))
{
command.Parameters.AddWithValue("@user_id", id);
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string videoPath = (string)reader["video"];
FileStream fileStream = new FileStream(videoPath, FileMode.Open);
InputFileStream inputFile = new InputFileStream(fileStream, $"{id}.mp4");
InputMediaVideo inputMediaVideo = new InputMediaVideo(inputFile);
using (MySqlConnection connection1 = new MySqlConnection(_connectionString))
{
connection1.Open();
using (MySqlCommand command1 = new MySqlCommand("SELECT * FROM Users WHERE id = @id", connection1))
{
command1.Parameters.AddWithValue("@id", id);
using (MySqlDataReader reader1 = command1.ExecuteReader())
{
if (reader1.Read())
{
string userData = $"Имя: {reader1["Name"]}\n" +
$"Возраст: {reader1["Age"]}\n" +
$"Пол: {reader1["Gender"]}\n" +
$"Город: {reader1["City"]}\n" +
$"О себе: {reader1["About"]}";
inputMediaVideo.Caption = userData;
}
}
}
}
media.Add(inputMediaVideo);
}
}
}
}
await _botClient.SendChatActionAsync(chatId, ChatAction.Typing);
await _botClient.SendMediaGroupAsync(chatId, media);
ReplyKeyboardMarkup replyKeyboard = new ReplyKeyboardMarkup(
new[]
{
new[]
{
new KeyboardButton("❤️"),
new KeyboardButton("👎"),
new KeyboardButton("Отправить сообщение"),
new KeyboardButton("Вернуться назад"),
}
}
)
{
ResizeKeyboard = true,
OneTimeKeyboard = true
};
try
{
await _botClient.SendTextMessageAsync(chatId, "", replyMarkup: replyKeyboard);
}
catch (Exception) { }
await WaitForUserResponse(chatId, id);
}
}
private async Task WaitForUserResponse(ChatId chatId, ChatId intAnket)
{
Console.WriteLine($"{intAnket}:{chatId}");
while (true)
{
var updates = await _botClient.GetUpdatesAsync();
foreach (var update in updates)
{
if (update.Type == UpdateType.Message && update.Message.Chat.Id == chatId)
{
string text = update.Message.Text;
if (text == "❤️")
{
using (MySqlConnection connection = new MySqlConnection("server=127.0.0.1;user=root;password=;database=Diplom_TGBOT"))
{
connection.Open();
string query = "INSERT INTO User_Like (id_user_send, id_user_recipient) VALUES (@id, @Name)";
using (MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.AddWithValue("@id", chatId);
command.Parameters.AddWithValue("@Name", intAnket);
command.ExecuteNonQuery();
}
}
return;
}
if (text == "👎")
{
return;
}
if (text == "Отправить сообщение")
{
return;
}
if (text == "Вернуться назад")
{
return;
}
}
}
await Task.Delay(100);
}
}
}