-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProgram.cs
86 lines (73 loc) · 3.01 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using dotenv.net;
using ImageSearchBot.Config;
using ImageSearchBot.ImageSearch;
namespace ImageSearchBot
{
public static class Program
{
private static readonly List<ImgBot> Bots = new List<ImgBot>();
private static readonly ManualResetEvent ExitEvent = new ManualResetEvent(false);
public static void Main(string[] args)
{
DotEnv.Load(new DotEnvOptions(true));
Console.CancelKeyPress += ConsoleOnCancelKeyPress;
var dir = args.Length <= 0 ? Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location) : args[0];
// retrieve bots config inside the directory
var configs = Directory.GetFiles(dir)
.Where(file => Path.GetFileName(file).EndsWith(".botconfig.json", StringComparison.InvariantCultureIgnoreCase)).ToList();
if (!configs.Any())
{
Console.Error.WriteLine("No bots configured. Add one like this mybot.botconfig.json");
Environment.Exit(1);
return;
}
foreach (var config in configs)
{
try
{
CreateAndRunBot(config);
}
catch(Exception ex)
{
// Let's prevent any wrong configuration to crash the app
Console.WriteLine($"Bot run failed: {ex.Message}");
}
}
ExitEvent.WaitOne();
Console.CancelKeyPress -= ConsoleOnCancelKeyPress;
Bots.ForEach(b => b.Stop());
}
private static void CreateAndRunBot(string config)
{
var contents = File.ReadAllText(config);
var cfg = JsonSerializer.Deserialize<RootConfig>(contents,
new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
});
Assert.Check(cfg != null, "Root configuration must be set");
Assert.Check(cfg.ImageSearchConfig != null, "Bot image search configuration must be set");
Assert.Check(cfg.BotConfig != null, "Bot config must be set");
var imageSearchType = Type.GetType(cfg.ImageSearchConfig.Type);
var imageSearch = (IImageSearch)Activator.CreateInstance(imageSearchType, cfg.BotConfig.Prefix, cfg.ImageSearchConfig);
var imgBot = new ImgBot(cfg.BotConfig, imageSearch);
Bots.Add(imgBot);
Task.Run(() => imgBot.Run());
}
private static void ConsoleOnCancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
e.Cancel = true;
ExitEvent.Set();
}
}
}