Files
zaobot/BotService.cs
T
2024-01-20 18:37:52 +03:00

104 lines
2.6 KiB
C#

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<long, IUserState> userStates = new Dictionary<long, IUserState>();
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<ITelegramBotClient>();
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<MainMenuUserState>();
}
state = await state.ProcessMessage(state, updateInfo);
if (state == null)
{
await botClient.SendTextMessageAsync(
chatId: updateInfo.Message.Chat,
text: "Я запутался, давайте сначала"
);
state = services.GetService<MainMenuUserState>();
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;
}
}
}
}