telegram-bot/Program.cs
2025-03-12 19:38:45 +07:00

83 lines
2.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Data.Sqlite;
using Serilog;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
class Program
{
private static string _botToken = string.Empty;
private static TelegramBotClient _botClient = null!;
static async Task Main()
{
// Загружаем конфигурацию из appsettings.json
var config = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory) // <-- Используем правильный путь
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
_botToken = config["BotToken"] ?? throw new Exception("BotToken не найден в конфигурации!");
// Настраиваем логирование
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
Log.Information("Запуск Telegram-бота...");
_botClient = new TelegramBotClient(_botToken);
var me = await _botClient.GetMe();
Log.Information($"Бот {me.FirstName} запущен!");
var cts = new CancellationTokenSource();
_botClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, cancellationToken: cts.Token);
await Task.Delay(-1); // <-- Заменяем Console.ReadLine()
}
private static async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
if (update.Type != UpdateType.Message || update.Message?.Text == null)
return;
var message = update.Message;
Log.Information($"Сообщение от {message.Chat.Id}: {message.Text}");
if (message.Text == "/start")
{
await botClient.SendMessage(
chatId: message.Chat.Id,
text: "Йоу! Я бот для сбора заявок на ремонт оборудования. Отправь /report для подачи заявки."
);
}
else if (message.Text == "/report")
{
await botClient.SendMessage(
chatId: message.Chat.Id,
text: "Пожалуйста, отправьте описание проблемы."
);
}
else
{
await botClient.SendMessage(
chatId: message.Chat.Id,
text: "Неизвестная команда. Используйте /start."
);
}
}
private static Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{
Log.Error($"Ошибка: {exception.Message}");
return Task.CompletedTask;
}
}