using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Args; using Telegram.Bot.Types.ReplyMarkups; using ZaoBot.Config; namespace ZaoBot { class BotService { private JsonDocument config; static ITelegramBotClient botClient; Dictionary userStates = new Dictionary(); private OpenHab.OpenHabClient openhab; bool shouldRestart = false; public BotService(IConfig config, OpenHab.OpenHabClient openhab) { this.config = config.Data; this.openhab = openhab; } public void Run() { var token = config.RootElement.GetProperty("token").GetString(); while (true) { shouldRestart = false; botClient = new TelegramBotClient(token); using CancellationTokenSource cts = new CancellationTokenSource(); 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 ); while (!shouldRestart) { Thread.Sleep(1000); } } } private Task OnPollingError(ITelegramBotClient bot, Exception exception, CancellationToken cts) { Console.WriteLine("Error on polling: " + exception.Message); Console.WriteLine("Will restart"); 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 = new MainMenuUserState(botClient, config, openhab); } state = await state.ProcessMessage(state, updateInfo); if (state == null) { await botClient.SendTextMessageAsync( chatId: updateInfo.Message.Chat, text: "Я запутался, давайте сначала" ); state = new MainMenuUserState(botClient, config, openhab); 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; } } } }