Переделал всё на DI

This commit is contained in:
ftc
2024-01-20 18:37:52 +03:00
parent 2a8348df44
commit d641de9689
5 changed files with 66 additions and 35 deletions
+20 -16
View File
@@ -1,13 +1,10 @@
using System;
using Microsoft.Extensions.DependencyInjection;
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
@@ -18,42 +15,49 @@ namespace ZaoBot
static ITelegramBotClient botClient;
Dictionary<long, IUserState> userStates = new Dictionary<long, IUserState>();
private OpenHab.OpenHabClient openhab;
private IServiceProvider services;
bool shouldRestart = false;
public BotService(IConfig config, OpenHab.OpenHabClient openhab)
public BotService(IServiceProvider services, IConfig config, OpenHab.OpenHabClient openhab)
{
this.services = services;
this.config = config.Data;
this.openhab = openhab;
}
public void Run()
{
var token = config.RootElement.GetProperty("token").GetString();
while (true)
shouldRestart = false;
var botClient = services.GetRequiredService<ITelegramBotClient>();
using CancellationTokenSource cts = new CancellationTokenSource();
try
{
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
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;
}
@@ -72,7 +76,7 @@ namespace ZaoBot
}
if (state == null)
{
state = new MainMenuUserState(botClient, config, openhab);
state = services.GetService<MainMenuUserState>();
}
state = await state.ProcessMessage(state, updateInfo);
if (state == null)
@@ -81,7 +85,7 @@ namespace ZaoBot
chatId: updateInfo.Message.Chat,
text: "Я запутался, давайте сначала"
);
state = new MainMenuUserState(botClient, config, openhab);
state = services.GetService<MainMenuUserState>();
state = await state.ProcessMessage(state, updateInfo);
}
userStates[id] = state;