TgBots/Program.cs
Dmitrii Prokudin 6918e3c853
All checks were successful
Local Deploy with Docker / build-and-deploy (push) Successful in 17s
Fix bot
2024-12-26 03:41:03 +03:00

80 lines
3.1 KiB
C#

using System;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Dapper;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Npgsql;
using UserOfTheDayBot.Data;
using UserOfTheDayBot.Services;
public class Program
{
public static async Task Main(string[] args)
{
var host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables(); // Добавление переменных среды
})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole(); // Вывод логов в консоль
})
.ConfigureServices((context, services) =>
{
services.AddSingleton<IUserRepository, UserRepository>();
services.AddSingleton<IUserOfTheDayRepository, UserOfTheDayRepository>();
services.AddSingleton<BotService>();
// TelegramBotClient зависит от IConfiguration для получения токена
services.AddSingleton<ITelegramBotClient>(provider =>
{
var configuration = provider.GetRequiredService<IConfiguration>();
var botToken = configuration["BotSettings:BotToken"];
return new TelegramBotClient(botToken);
});
})
.Build();
var logger = host.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Bot is starting...");
var botService = host.Services.GetRequiredService<BotService>();
var botClient = host.Services.GetRequiredService<ITelegramBotClient>();
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, _) => cts.Cancel();
botClient.StartReceiving(
updateHandler: async (bot, update, token) =>
{
// Получение вашего BotService из DI
var botService = host.Services.GetRequiredService<BotService>();
await botService.HandleUpdateAsync(update, token);
},
errorHandler: async (bot, exception, token) =>
{
logger.LogError($"Telegram Bot Error: {exception.Message}");
await Task.CompletedTask;
},
receiverOptions: new Telegram.Bot.Polling.ReceiverOptions
{
AllowedUpdates = Array.Empty<UpdateType>() // Получать все обновления
},
cancellationToken: cts.Token
);
logger.LogInformation("Bot is running. Press Ctrl+C to stop.");
await Task.Delay(Timeout.Infinite, cts.Token);
}
}