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; namespace ZaoBot { class BotService { private JsonDocument config; static ITelegramBotClient botClient; Dictionary userStates = new Dictionary(); private OpenHab.OpenHabClient openhab; bool shouldRestart = false; public BotService(JsonDocument config) { this.config = config; } public void Run() { var token = config.RootElement.GetProperty("token").GetString(); shouldRestart = false; botClient = new TelegramBotClient(token); openhab = new OpenHab.OpenHabClient(config.RootElement.GetProperty("openhab_url").GetString()); var me = botClient.GetMeAsync().Result; Console.WriteLine($"Hello, World! I am user {me.Id} and my name is {me.FirstName}."); botClient.OnMessage += OnBotMessage; botClient.StartReceiving(); while (!shouldRestart) { Thread.Sleep(1000); } } private async void OnBotMessage(object sender, MessageEventArgs e) { try { if (e.Message.Text != null) { var id = e.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, e); if (state == null) { await botClient.SendTextMessageAsync( chatId: e.Message.Chat, text: "Я запутался, давайте сначала" ); state = new MainMenuUserState(botClient, config, openhab); state = await state.ProcessMessage(state, e); } userStates[id] = state; } } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); Console.WriteLine(ex.StackTrace); Console.WriteLine("Restarting bot"); shouldRestart = true; } } } }