admin
This commit is contained in:
parent
d3ff267d26
commit
d2f06c4527
140
Program.cs
140
Program.cs
@ -15,6 +15,8 @@ class Program
|
|||||||
private static string _botToken = string.Empty;
|
private static string _botToken = string.Empty;
|
||||||
private static TelegramBotClient _botClient = null!;
|
private static TelegramBotClient _botClient = null!;
|
||||||
private static Dictionary<long, bool> usersWaitingForReport = new Dictionary<long, bool>(); // Отслеживаем состояние пользователей
|
private static Dictionary<long, bool> usersWaitingForReport = new Dictionary<long, bool>(); // Отслеживаем состояние пользователей
|
||||||
|
private static HashSet<long> admins = new HashSet<long>(); // Хранение списка администраторов
|
||||||
|
private static string adminPassword = "admin123"; // Простой пароль для администратора
|
||||||
|
|
||||||
static async Task Main()
|
static async Task Main()
|
||||||
{
|
{
|
||||||
@ -95,45 +97,64 @@ class Program
|
|||||||
|
|
||||||
if (message.Text == "/start")
|
if (message.Text == "/start")
|
||||||
{
|
{
|
||||||
await botClient.SendTextMessageAsync(
|
await botClient.SendMessage(chatId: message.Chat.Id, text: "Привет! Я бот для сбора заявок на ремонт оборудования. Отправь /report для подачи заявки.");
|
||||||
chatId: message.Chat.Id,
|
|
||||||
text: "Привет! Я бот для сбора заявок на ремонт оборудования. Отправь /report для подачи заявки."
|
|
||||||
);
|
|
||||||
Log.Information($"Ответ на команду /start отправлен.");
|
Log.Information($"Ответ на команду /start отправлен.");
|
||||||
}
|
}
|
||||||
else if (message.Text == "/report")
|
else if (message.Text == "/report")
|
||||||
{
|
{
|
||||||
usersWaitingForReport[message.Chat.Id] = true; // Отметить, что пользователь должен отправить описание
|
usersWaitingForReport[message.Chat.Id] = true; // Отметить, что пользователь должен отправить описание
|
||||||
await botClient.SendTextMessageAsync(
|
await botClient.SendMessage(chatId: message.Chat.Id, text: "Пожалуйста, отправьте описание проблемы.");
|
||||||
chatId: message.Chat.Id,
|
|
||||||
text: "Пожалуйста, отправьте описание проблемы."
|
|
||||||
);
|
|
||||||
Log.Information("Ответ на команду /report отправлен.");
|
Log.Information("Ответ на команду /report отправлен.");
|
||||||
}
|
}
|
||||||
else if (usersWaitingForReport.ContainsKey(message.Chat.Id) && usersWaitingForReport[message.Chat.Id])
|
else if (message.Text.StartsWith("/admin qwerty"))
|
||||||
{
|
{
|
||||||
// Пользователь отправил описание проблемы
|
string passwordAttempt = message.Text.Substring(7); // Получаем пароль, который ввел пользователь
|
||||||
string problemDescription = message.Text;
|
|
||||||
|
|
||||||
// Сохраняем описание проблемы в базу данных (SQLite)
|
if (passwordAttempt == adminPassword)
|
||||||
await SaveReportToDatabase(message.Chat.Id, problemDescription);
|
{
|
||||||
|
admins.Add(message.Chat.Id); // Назначаем пользователя администратором
|
||||||
// Ответ пользователю, что заявка принята
|
await botClient.SendMessage(chatId: message.Chat.Id, text: "Вы стали администратором.");
|
||||||
await botClient.SendTextMessageAsync(
|
Log.Information($"Пользователь {message.Chat.Id} стал администратором.");
|
||||||
chatId: message.Chat.Id,
|
|
||||||
text: "Спасибо за заявку! Мы обработаем её в ближайшее время."
|
|
||||||
);
|
|
||||||
|
|
||||||
// Сброс состояния
|
|
||||||
usersWaitingForReport[message.Chat.Id] = false;
|
|
||||||
Log.Information($"Заявка пользователя {message.Chat.Id} сохранена в базе данных. Описание: {problemDescription}");
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
await botClient.SendTextMessageAsync(
|
await botClient.SendMessage(chatId: message.Chat.Id, text: "Неверный пароль.");
|
||||||
chatId: message.Chat.Id,
|
Log.Information($"Неудачная попытка входа для пользователя {message.Chat.Id}.");
|
||||||
text: "Неизвестная команда. Используйте /start."
|
}
|
||||||
);
|
}
|
||||||
|
else if (admins.Contains(message.Chat.Id)) // Команды доступны только для администраторов
|
||||||
|
{
|
||||||
|
if (message.Text == "/view_reports")
|
||||||
|
{
|
||||||
|
await ViewReports(botClient, message.Chat.Id);
|
||||||
|
}
|
||||||
|
else if (message.Text.StartsWith("/change_status "))
|
||||||
|
{
|
||||||
|
string[] parts = message.Text.Split(' ', 3);
|
||||||
|
if (parts.Length >= 3)
|
||||||
|
{
|
||||||
|
long reportId = long.Parse(parts[1]);
|
||||||
|
string newStatus = parts[2];
|
||||||
|
await ChangeReportStatus(reportId, newStatus);
|
||||||
|
await botClient.SendMessage(chatId: message.Chat.Id, text: "Статус заявки изменен.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await botClient.SendMessage(chatId: message.Chat.Id, text: "Неверный формат команды. Используйте /change_status <Id> <новый статус>.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (usersWaitingForReport.ContainsKey(message.Chat.Id) && usersWaitingForReport[message.Chat.Id])
|
||||||
|
{
|
||||||
|
string problemDescription = message.Text;
|
||||||
|
await SaveReportToDatabase(message.Chat.Id, problemDescription);
|
||||||
|
await botClient.SendMessage(chatId: message.Chat.Id, text: "Спасибо за заявку! Мы обработаем её в ближайшее время.");
|
||||||
|
usersWaitingForReport[message.Chat.Id] = false;
|
||||||
|
Log.Information($"Заявка пользователя {message.Chat.Id} сохранена в базе данных.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await botClient.SendMessage(chatId: message.Chat.Id, text: "Неизвестная команда. Используйте /start.");
|
||||||
Log.Information("Ответ на неизвестную команду отправлен.");
|
Log.Information("Ответ на неизвестную команду отправлен.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -183,7 +204,6 @@ class Program
|
|||||||
{
|
{
|
||||||
await connection.OpenAsync();
|
await connection.OpenAsync();
|
||||||
|
|
||||||
// Создание таблицы Reports, если она не существует
|
|
||||||
var createTableCommand = connection.CreateCommand();
|
var createTableCommand = connection.CreateCommand();
|
||||||
createTableCommand.CommandText =
|
createTableCommand.CommandText =
|
||||||
@"
|
@"
|
||||||
@ -206,6 +226,70 @@ class Program
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static async Task ViewReports(ITelegramBotClient botClient, long chatId)
|
||||||
|
{
|
||||||
|
string connectionString = "Data Source=bot.db"; // Путь к базе данных
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using (var connection = new SqliteConnection(connectionString))
|
||||||
|
{
|
||||||
|
await connection.OpenAsync();
|
||||||
|
var command = connection.CreateCommand();
|
||||||
|
command.CommandText = "SELECT * FROM Reports";
|
||||||
|
|
||||||
|
using (var reader = await command.ExecuteReaderAsync())
|
||||||
|
{
|
||||||
|
string reportsText = "Список заявок:\n";
|
||||||
|
while (await reader.ReadAsync())
|
||||||
|
{
|
||||||
|
long id = reader.GetInt64(0);
|
||||||
|
long reportChatId = reader.GetInt64(1);
|
||||||
|
string description = reader.GetString(2);
|
||||||
|
string status = reader.GetString(4);
|
||||||
|
|
||||||
|
reportsText += $"ID: {id}, ChatId: {reportChatId}, Описание: {description}, Статус: {status}\n";
|
||||||
|
}
|
||||||
|
await botClient.SendMessage(chatId: chatId, text: reportsText);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log.Error($"Ошибка при просмотре заявок: {ex.Message}");
|
||||||
|
await botClient.SendMessage(chatId: chatId, text: "Ошибка при получении заявок.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task ChangeReportStatus(long reportId, string newStatus)
|
||||||
|
{
|
||||||
|
string connectionString = "Data Source=bot.db";
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using (var connection = new SqliteConnection(connectionString))
|
||||||
|
{
|
||||||
|
await connection.OpenAsync();
|
||||||
|
var command = connection.CreateCommand();
|
||||||
|
command.CommandText =
|
||||||
|
@"
|
||||||
|
UPDATE Reports
|
||||||
|
SET Status = @Status
|
||||||
|
WHERE Id = @Id;
|
||||||
|
";
|
||||||
|
command.Parameters.AddWithValue("@Status", newStatus);
|
||||||
|
command.Parameters.AddWithValue("@Id", reportId);
|
||||||
|
|
||||||
|
await command.ExecuteNonQueryAsync();
|
||||||
|
Log.Information($"Статус заявки с ID {reportId} изменен на {newStatus}.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log.Error($"Ошибка при изменении статуса заявки: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
|
private static Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
Log.Error($"Ошибка в процессе работы с ботом: {exception.Message}");
|
Log.Error($"Ошибка в процессе работы с ботом: {exception.Message}");
|
||||||
|
Loading…
x
Reference in New Issue
Block a user