feat: added DI to Client
This commit is contained in:
@@ -1,44 +1,17 @@
|
||||
using Grpc.Net.Client;
|
||||
using Proto = JOBot.Proto;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using JOBot.TClient;
|
||||
using JOBot.TClient.Core.HostedServices;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
var config = new ConfigurationBuilder()
|
||||
.AddJsonFile("appsettings.json")
|
||||
.AddJsonFile("appsettings.Development.json", true)
|
||||
var host = Host.CreateDefaultBuilder(args)
|
||||
.ConfigureServices((context, services) =>
|
||||
{
|
||||
// Настройка DI
|
||||
services.ConfigureServices(context.Configuration);
|
||||
|
||||
// Фоновый сервис для бота
|
||||
services.AddHostedService<BotBackgroundService>();
|
||||
})
|
||||
.Build();
|
||||
|
||||
var botClient = new TelegramBotClient(config.GetValue<string>("TelegramToken")
|
||||
?? throw new MissingFieldException("TelegramToken is not set"));
|
||||
botClient.StartReceiving(HandleUpdate, HandleError);
|
||||
|
||||
Console.WriteLine("Бот запущен. Нажмите Enter для остановки.");
|
||||
Console.ReadLine();
|
||||
|
||||
async Task HandleUpdate(ITelegramBotClient bot, Update update, CancellationToken ct)
|
||||
{
|
||||
using var channel = GrpcChannel.ForAddress(config.GetValue<string>("BackendHost")
|
||||
?? throw new MissingFieldException("Host is not defined"));
|
||||
var userClient = new Proto.User.UserClient(channel);
|
||||
|
||||
if (update.Message?.Text == "/start")
|
||||
{
|
||||
var reply = await userClient.RegisterAsync(new Proto.RegisterRequest
|
||||
{
|
||||
UserId = update.Message.Chat.Id,
|
||||
Username = update.Message.Chat.Username ?? ""
|
||||
});
|
||||
|
||||
await bot.SendMessage(
|
||||
chatId: update.Message.Chat.Id,
|
||||
text: reply.Success ? "✅ Вы зарегистрированы!" : "❌ Ошибка",
|
||||
cancellationToken: ct);
|
||||
}
|
||||
}
|
||||
|
||||
Task HandleError(ITelegramBotClient bot, Exception ex, CancellationToken ct)
|
||||
{
|
||||
Console.WriteLine($"Ошибка: {ex.Message}");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
await host.RunAsync();
|
||||
Reference in New Issue
Block a user