99 lines
2.6 KiB
C#
99 lines
2.6 KiB
C#
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<long, IUserState> userStates = new Dictionary<long, IUserState>();
|
|
private OpenHab.OpenHabClient openhab;
|
|
|
|
bool shouldRestart = false;
|
|
|
|
public BotService(JsonDocument config)
|
|
{
|
|
this.config = config;
|
|
}
|
|
|
|
public void Run()
|
|
{
|
|
var token = config.RootElement.GetProperty("token").GetString();
|
|
openhab = new OpenHab.OpenHabClient(config.RootElement.GetProperty("openhab_url").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;
|
|
}
|
|
}
|
|
}
|
|
}
|