JOBot/JOBot.TClient/Program.cs

44 lines
1.5 KiB
C#

using Grpc.Net.Client;
using Proto = JOBot.Proto;
using Telegram.Bot;
using Telegram.Bot.Types;
using Microsoft.Extensions.Configuration;
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile("appsettings.Development.json", true)
.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;
}