forked from JStalnac/DirtBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
156 lines (140 loc) · 6.14 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
using DirtBot.Database;
using DirtBot.Logging;
using DirtBot.Services;
using DirtBot.Services.Options;
using DirtBot.Translation;
using Discord.Addons.Hosting;
using Discord.WebSocket;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using StackExchange.Redis;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace DirtBot
{
internal class Program
{
public static IServiceProvider Services { get; private set; }
public static ConnectionMultiplexer Redis { get; private set; }
public static async Task Main(string[] args)
{
if (!Directory.Exists("logs"))
Directory.CreateDirectory("logs");
// Enable file output
Logger.LogFile = LogFileUpdaterService.GetLogFile(DateTime.Now);
Logger.UseTypeFullName = true;
var log = Logger.GetLogger("Main");
log.Important("Starting! Hello World!");
try
{
using var host = CreateHostBuilder(args).Build();
if (Redis is null)
{
log.Critical("Redis is not connected.");
return;
}
Services = host.Services;
log.Info("Starting host...");
await host.StartAsync();
log.Info("Host started");
await host.WaitForShutdownAsync();
}
catch (OptionsValidationException ex)
{
log.Critical($"Option {ex.OptionsType} failed to validate: {String.Join('\n', ex.Failures)}");
}
catch (Exception ex)
{
log.Critical("The application threw an unhandled exception.", ex);
}
}
public static IHostBuilder CreateHostBuilder(string[] args)
=> Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(x =>
{
x.SetBasePath(Directory.GetCurrentDirectory())
.AddCommandLine(args)
.AddEnvironmentVariables()
.AddJsonFile("appsettings.json");
})
.ConfigureLogging(o =>
{
o.ClearProviders();
})
.ConfigureDiscordHost<DiscordSocketClient>((context, config) =>
{
config.SocketConfig = new DiscordSocketConfig
{
ExclusiveBulkDelete = true,
LogLevel = Discord.LogSeverity.Debug
};
config.Token = context.Configuration["Token"];
})
.UseCommandService((context, config) =>
{
config.DefaultRunMode = Discord.Commands.RunMode.Async;
})
.ConfigureServices((c, services) =>
{
// Set log level from appsettings
Enum.TryParse(typeof(Logging.LogLevel), c.Configuration["LogLevel"], out object logLevel);
Logger.MinimumLogLevel = logLevel != null ? (Logging.LogLevel)logLevel : Logging.LogLevel.Info;
// Connect to Redis
var logger = Logger.GetLogger<Program>();
logger.Info("Configuring services...");
// Database
services.AddDbContextPool<DatabaseContext>(options => options.UseSqlite(c.Configuration.GetConnectionString("Sqlite")));
ConnectionMultiplexer redis = null;
try
{
string connectionString = c.Configuration.GetConnectionString("Redis");
if (String.IsNullOrEmpty(connectionString))
logger.Critical("Redis connection string not specified");
else
{
logger.Info("Connecting to Redis");
redis = ConnectionMultiplexer.Connect(connectionString);
logger.Info("Connected to Redis");
}
}
catch (Exception ex)
{
logger.Critical("Failed to connect to Redis", ex);
}
if (redis is null)
{
// So that you can migrate EF without a Redis connection.
logger.Critical("Redis is not connected so other services will not be loaded.");
return;
}
Redis = redis;
services.AddSingleton(redis);
logger.Info("Loading translations...");
TranslationManager.LoadTranslations().Wait();
logger.Info("Translations loaded");
var section = c.Configuration.GetSection("Services");
// Required services
services.AddSingleton<CategoryManagerService>();
services.AddSingleton<PrefixManagerService>()
.Configure<PrefixManagerOptions>(options =>
{
options.DefaultPrefix = c.Configuration["DefaultPrefix"];
});
services.AddSingleton<HelpProviderService>();
services.AddHostedService<CommandHandlerService>();
services.AddHostedService<LogFileUpdaterService>()
.Configure<LogFileUpdaterOptions>(section.GetSection("LogFileUpdater"));
// Other services
services.AddHostedService<CustomStatusService>()
.Configure<CustomStatusServiceOptions>(section.GetSection("CustomStatusService"));
services.AddHostedService<LoggingService>();
logger.Info("Services configured");
});
}
}