фикс уведов

This commit is contained in:
107 2025-03-20 11:12:10 +07:00
parent f3fe09f6a1
commit 23394de0a6

View File

@ -144,9 +144,15 @@ class Program
command.Parameters.AddWithValue("@userId", chatId); command.Parameters.AddWithValue("@userId", chatId);
var result = await command.ExecuteScalarAsync(); var result = await command.ExecuteScalarAsync();
// Отладочная информация
Log.Information($"[Отладка] Для пользователя {chatId} проверяем настройки уведомлений. Результат из БД: {result}");
if (result != null && result != DBNull.Value) if (result != null && result != DBNull.Value)
{ {
notificationsEnabled = Convert.ToInt32(result) == 1; int dbValue = Convert.ToInt32(result);
notificationsEnabled = dbValue == 1;
Log.Information($"[Отладка] Для пользователя {chatId} настройка уведомлений из БД: {dbValue} => notificationsEnabled={notificationsEnabled}");
} }
else else
{ {
@ -155,6 +161,7 @@ class Program
insertCommand.CommandText = "INSERT INTO UserSettings (UserId, NotificationsEnabled) VALUES (@userId, 1)"; insertCommand.CommandText = "INSERT INTO UserSettings (UserId, NotificationsEnabled) VALUES (@userId, 1)";
insertCommand.Parameters.AddWithValue("@userId", chatId); insertCommand.Parameters.AddWithValue("@userId", chatId);
await insertCommand.ExecuteNonQueryAsync(); await insertCommand.ExecuteNonQueryAsync();
Log.Information($"[Отладка] Создали запись для пользователя {chatId} с notificationsEnabled=true");
} }
} }
@ -162,6 +169,8 @@ class Program
string notificationStatus = notificationsEnabled ? "✅ Включены" : "❌ Отключены"; string notificationStatus = notificationsEnabled ? "✅ Включены" : "❌ Отключены";
string toggleAction = notificationsEnabled ? "toggle_off" : "toggle_on"; string toggleAction = notificationsEnabled ? "toggle_off" : "toggle_on";
Log.Information($"[Отладка] Для пользователя {chatId} показываем статус: {notificationStatus}, toggleAction: {toggleAction}");
var keyboard = new InlineKeyboardMarkup(new[] var keyboard = new InlineKeyboardMarkup(new[]
{ {
new[] new[]
@ -185,9 +194,11 @@ class Program
catch (Exception ex) catch (Exception ex)
{ {
Log.Error($"Ошибка при отображении настроек пользователя: {ex.Message}"); Log.Error($"Ошибка при отображении настроек пользователя: {ex.Message}");
Log.Error($"StackTrace: {ex.StackTrace}");
await botClient.SendMessage(chatId, "Произошла ошибка при загрузке настроек."); await botClient.SendMessage(chatId, "Произошла ошибка при загрузке настроек.");
} }
} }
private static async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) private static async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{ {
try try
@ -724,13 +735,30 @@ class Program
{ {
try try
{ {
// Исправление: правильно интерпретируем action // Проверка текущего состояния перед изменением
bool currentState = true;
using (var connection = new SqliteConnection("Data Source=bot.db"))
{
await connection.OpenAsync();
var checkCommand = connection.CreateCommand();
checkCommand.CommandText = "SELECT NotificationsEnabled FROM UserSettings WHERE UserId = @userId";
checkCommand.Parameters.AddWithValue("@userId", chatId);
var result = await checkCommand.ExecuteScalarAsync();
if (result != null && result != DBNull.Value)
{
currentState = Convert.ToInt32(result) == 1;
}
}
Log.Information($"[Отладка] Переключение уведомлений для пользователя {chatId}: текущее состояние={currentState}, action={action}");
// Если action = "toggle_on", то нужно ВКЛЮЧИТЬ уведомления (установить в БД 1) // Если action = "toggle_on", то нужно ВКЛЮЧИТЬ уведомления (установить в БД 1)
// Если action = "toggle_off", то нужно ВЫКЛЮЧИТЬ уведомления (установить в БД 0) // Если action = "toggle_off", то нужно ВЫКЛЮЧИТЬ уведомления (установить в БД 0)
bool newValue = action == "toggle_on"; bool newValue = action == "toggle_on";
int dbValue = newValue ? 1 : 0; int dbValue = newValue ? 1 : 0;
Log.Information($"Переключение уведомлений для пользователя {chatId}: action={action}, новое значение={newValue}, значение в БД={dbValue}"); Log.Information($"[Отладка] Переключение уведомлений для пользователя {chatId}: action={action}, новое значение={newValue}, значение в БД={dbValue}");
using (var connection = new SqliteConnection("Data Source=bot.db")) using (var connection = new SqliteConnection("Data Source=bot.db"))
{ {
@ -743,7 +771,26 @@ class Program
DO UPDATE SET NotificationsEnabled = @value"; DO UPDATE SET NotificationsEnabled = @value";
command.Parameters.AddWithValue("@userId", chatId); command.Parameters.AddWithValue("@userId", chatId);
command.Parameters.AddWithValue("@value", dbValue); command.Parameters.AddWithValue("@value", dbValue);
await command.ExecuteNonQueryAsync();
int rowsAffected = await command.ExecuteNonQueryAsync();
Log.Information($"[Отладка] Запрос выполнен, затронуто {rowsAffected} строк");
}
// Проверка после изменения
using (var connection = new SqliteConnection("Data Source=bot.db"))
{
await connection.OpenAsync();
var checkCommand = connection.CreateCommand();
checkCommand.CommandText = "SELECT NotificationsEnabled FROM UserSettings WHERE UserId = @userId";
checkCommand.Parameters.AddWithValue("@userId", chatId);
var result = await checkCommand.ExecuteScalarAsync();
bool updatedState = false;
if (result != null && result != DBNull.Value)
{
updatedState = Convert.ToInt32(result) == 1;
}
Log.Information($"[Отладка] После обновления: значение в БД для пользователя {chatId} = {result}, обновленное состояние={updatedState}");
} }
// Показываем обновленные настройки // Показываем обновленные настройки
@ -755,6 +802,7 @@ class Program
catch (Exception ex) catch (Exception ex)
{ {
Log.Error($"Ошибка при изменении настроек уведомлений: {ex.Message}"); Log.Error($"Ошибка при изменении настроек уведомлений: {ex.Message}");
Log.Error($"StackTrace: {ex.StackTrace}");
await botClient.SendMessage(chatId, "Произошла ошибка при обновлении настроек."); await botClient.SendMessage(chatId, "Произошла ошибка при обновлении настроек.");
} }
} }