using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Telegram.Bot; using ZaoBot.Config; namespace ZaoBot { class BotService { private JsonDocument config; static ITelegramBotClient botClient; Dictionary userStates = new Dictionary(); private OpenHab.OpenHabClient openhab; private IServiceProvider services; bool shouldRestart = false; public BotService(IServiceProvider services, IConfig config, OpenHab.OpenHabClient openhab) { this.services = services; this.config = config.Data; this.openhab = openhab; } public void Run() { shouldRestart = false; var botClient = services.GetRequiredService(); using CancellationTokenSource cts = new CancellationTokenSource(); try { var me = botClient.GetMeAsync().Result; Console.WriteLine($"Hello, World! I am user {me.Id} and my name is {me.FirstName}."); botClient.StartReceiving( updateHandler: OnBotUpdateAsync, pollingErrorHandler: OnPollingError, cancellationToken: cts.Token ); while (!shouldRestart) { Thread.Sleep(1000); } } finally { cts.Cancel(); } } private Task OnPollingError(ITelegramBotClient bot, Exception exception, CancellationToken cts) { Console.WriteLine("Error on polling: " + exception.Message); Console.WriteLine("Will restart"); shouldRestart = true; return Task.CompletedTask; } async Task OnBotUpdateAsync(ITelegramBotClient bot, Telegram.Bot.Types.Update updateInfo, CancellationToken cts) { if (updateInfo.Message == null) return; try { if (updateInfo.Message.Text != null) { var id = updateInfo.Message.Chat.Id; IUserState state = null; if (userStates.ContainsKey(id)) { state = userStates[id]; } if (state == null) { state = services.GetService(); } state = await state.ProcessMessage(state, updateInfo); if (state == null) { await botClient.SendTextMessageAsync( chatId: updateInfo.Message.Chat, text: "Я запутался, давайте сначала" ); state = services.GetService(); state = await state.ProcessMessage(state, updateInfo); } userStates[id] = state; } } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); Console.WriteLine(ex.StackTrace); Console.WriteLine("Restarting bot"); shouldRestart = true; } } } }