85 lines
2.5 KiB
C#
85 lines
2.5 KiB
C#
using Microsoft.Extensions.DependencyInjection;
|
|
using System;
|
|
using System.Globalization;
|
|
using System.IO;
|
|
using System.Reflection;
|
|
using System.Text.Json;
|
|
using System.Threading;
|
|
using Telegram.Bot;
|
|
using ZaoBot.Config;
|
|
using ZaoBot.OpenHab;
|
|
using ZaoBot.Problems;
|
|
|
|
namespace ZaoBot
|
|
{
|
|
class Program
|
|
{
|
|
static BotService bot;
|
|
static JsonDocument config;
|
|
|
|
static ServiceCollection services;
|
|
|
|
static void Main(string[] args)
|
|
{
|
|
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
|
|
config = LoadConfig();
|
|
services = new ServiceCollection();
|
|
services.AddSingleton<IConfig, Config.Config>(CreateConfig);
|
|
services.AddSingleton<OpenHabClient, OpenHabClient>();
|
|
services.AddSingleton<NotificationReceiver, NotificationReceiver>();
|
|
services.AddSingleton<StatusManager, StatusManager>();
|
|
|
|
services.AddScoped<BotService, BotService>();
|
|
services.AddScoped<IServiceProvider, IServiceProvider>(p => p);
|
|
services.AddScoped<ITelegramBotClient, TelegramBotClient>(CreateTelegramBot);
|
|
|
|
services.AddTransient<MainMenuUserState, MainMenuUserState>();
|
|
services.AddTransient<StatusMenuUserState, StatusMenuUserState>();
|
|
services.AddTransient<CamerasMenuUserState, CamerasMenuUserState>();
|
|
using (var provider = services.BuildServiceProvider())
|
|
{
|
|
var receiver = provider.GetRequiredService<NotificationReceiver>();
|
|
var notificationThread = new Thread(new ThreadStart(receiver.Run));
|
|
notificationThread.Start();
|
|
while (true)
|
|
{
|
|
try
|
|
{
|
|
using (var scope = provider.CreateScope())
|
|
{
|
|
bot = scope.ServiceProvider.GetRequiredService<BotService>();
|
|
bot.Run();
|
|
}
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
// Тут ловим всё, при ошибках просто заново поднимаем бота
|
|
Console.WriteLine("Exception: " + e.Message);
|
|
Console.WriteLine(e.StackTrace);
|
|
Console.WriteLine("Restarting bot");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private static TelegramBotClient CreateTelegramBot(IServiceProvider arg)
|
|
{
|
|
var token = config.RootElement.GetProperty("token").GetString();
|
|
return new TelegramBotClient(token);
|
|
}
|
|
|
|
private static Config.Config CreateConfig(IServiceProvider arg)
|
|
{
|
|
return new Config.Config(config);
|
|
}
|
|
|
|
private static JsonDocument LoadConfig()
|
|
{
|
|
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
|
|
var config = Path.Combine(assemblyFolder, "zaobot.json");
|
|
string configStr = File.ReadAllText(config);
|
|
return JsonDocument.Parse(configStr);
|
|
}
|
|
}
|
|
}
|