forked from jamesreiati/chill-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
197 lines (177 loc) · 9.5 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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
using Discord;
using Discord.Interactions;
using Discord.WebSocket;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Reiati.ChillBot.Behavior;
using Reiati.ChillBot.Data;
using Reiati.ChillBot.Services;
using Reiati.ChillBot.Tools;
using System;
namespace Reiati.ChillBot
{
/// <summary>
/// Class containing the main entry point for the application.
/// </summary>
public class Program
{
/// <summary>
/// A logger.
/// </summary>
private static ILogger Logger;
/// <summary>
/// Main entry point for the application.
/// </summary>
public static void Main(string[] args)
{
// Construct a logger separate from the host that can be used when we can't use host's logger
// due to the host being disposed or not yet created.
using var bootstrapLoggerFactory = LoggerFactory.Create(Program.ConfigureBaseLogging);
Program.Logger = bootstrapLoggerFactory.CreateLogger("Bootstrap");
Program.Logger.LogInformation("Bootstrap logger initialized");
Console.CancelKeyPress +=
delegate(object sender, ConsoleCancelEventArgs args)
{
Program.Logger.LogInformation("Shutdown initiated - console");
};
try
{
using IHost host = CreateHostBuilder(args).Build();
// Configure our LogManager with the host's LoggerFactory
LogManager.Configure(host.Services.GetRequiredService<ILoggerFactory>());
var logger = LogManager.GetLogger(typeof(Program));
logger.LogInformation("Host logger initialized");
host.Run();
}
catch (Exception e)
{
Program.Logger.LogError(e, "Shutdown initiated - exception thrown");
}
}
/// <summary>
/// Creates and configures the builder for the host application.
/// </summary>
/// <param name="args">Command line arguments.</param>
/// <returns></returns>
private static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureLogging((host, logging) =>
{
Program.ConfigureBaseLogging(logging);
// Configure Application Insights if a connection string or instrumentation key is provided
string connectionString = host.Configuration[HardCoded.Config.ApplicationInsightsConnectionStringConfigKey];
string instrumentationKey = host.Configuration[HardCoded.Config.ApplicationInsightsInstrumentationKeyConfigKey];
if (!string.IsNullOrEmpty(connectionString) || !string.IsNullOrEmpty(instrumentationKey))
{
logging.AddApplicationInsights(config =>
{
// Prefer using the connection string if provided since the instrumentation key is obsolete.
// See https://github.com/microsoft/ApplicationInsights-dotnet/issues/2560 for more details.
if (!string.IsNullOrEmpty(connectionString))
{
config.ConnectionString = connectionString;
}
else if (!string.IsNullOrEmpty(instrumentationKey))
{
config.InstrumentationKey = instrumentationKey;
}
}, options =>
{
});
}
})
.ConfigureAppConfiguration(configBuilder =>
{
configBuilder.AddJsonFile(HardCoded.Config.DefaultConfigFilePath, optional: true);
configBuilder.AddJsonFile(HardCoded.Config.LocalConfigFilePath, optional: true);
configBuilder.AddEnvironmentVariables(prefix: HardCoded.Config.EnvironmentVariablePrefix);
configBuilder.AddCommandLine(args);
})
.ConfigureServices((host, services) =>
{
services.AddMemoryCache();
// Get the type of guild repository to use, defaulting to GuildRepositoryType.File
GuildRepositoryType guildRepositoryType = host.Configuration.GetValue(HardCoded.Config.GuildRepositoryTypeConfigKey, GuildRepositoryType.File);
// Add a singleton for the guild repository
switch (guildRepositoryType)
{
case GuildRepositoryType.File:
default:
services.AddSingleton<IGuildRepository>(FileBasedGuildRepository.Instance);
break;
case GuildRepositoryType.AzureBlob:
string connectionString = host.Configuration[string.Format(HardCoded.Config.GuildRepositoryConnectionStringConfigKeyFormat, guildRepositoryType)];
string container = host.Configuration[string.Format(HardCoded.Config.GuildRepositoryContainerConfigKeyFormat, guildRepositoryType)];
services.AddSingleton<IGuildRepository>(new AzureBlobGuildRepository(connectionString, container));
break;
}
// Add services and configuration for the Discord client
var socketConfig = new DiscordSocketConfig
{
TotalShards = 1,
LogLevel = Program.GetMinimumDiscordLogLevel(host.Configuration).ToLogSeverity(),
GatewayIntents = (GatewayIntents.AllUnprivileged | GatewayIntents.GuildMembers) ^ (GatewayIntents.GuildScheduledEvents | GatewayIntents.GuildInvites)
};
services.AddSingleton(socketConfig);
services.AddSingleton<DiscordShardedClient>();
// Add services and configuration for the Discord interaction service that handles application commands.
var interactionServiceConfig = new InteractionServiceConfig
{
LogLevel = Program.GetMinimumDiscordLogLevel(host.Configuration).ToLogSeverity(),
};
services.AddSingleton(interactionServiceConfig);
services.AddSingleton<InteractionService>();
// Add services for caching opt-in channels
services.AddSingleton<IOptinChannelCache, OptinChannelMemoryCache>();
services.AddSingleton<IOptinChannelCacheManager, OptinChannelCacheManager>();
// Add services for caching slash commands
services.AddSingleton<ISlashCommandCache, SlashCommandMemoryCache>();
services.AddSingleton<ISlashCommandCacheManager, SlashCommandCacheManager>();
// Add the main service for Chill Bot
services.AddHostedService<ChillBotService>();
})
.UseConsoleLifetime();
}
/// <summary>
/// Get the minimum Discord category log level configured for any <see cref="Microsoft.Extensions.Logging"/> provider.
/// </summary>
/// <param name="configuration">Application configuration.</param>
/// <returns>The minimum log level configured for Discord logs.</returns>
private static LogLevel GetMinimumDiscordLogLevel(IConfiguration configuration)
{
bool logLevelConfigured = false;
LogLevel minimumDiscordLogLevel = LogLevel.None;
foreach (var configSetting in configuration.GetSection(nameof(Microsoft.Extensions.Logging)).AsEnumerable())
{
// Look for config settings assigning a LogLevel to a Discord category name (including subcategories of Discord)
// or to the default logging category.
if (configSetting.Key.Contains($":{nameof(LogLevel)}:{nameof(Discord)}", StringComparison.OrdinalIgnoreCase) ||
configSetting.Key.EndsWith($":{nameof(LogLevel)}:Default", StringComparison.OrdinalIgnoreCase))
{
// Check for a new minimum log level
if (Enum.TryParse(configSetting.Value, out LogLevel logLevel) && logLevel < minimumDiscordLogLevel)
{
minimumDiscordLogLevel = logLevel;
logLevelConfigured = true;
}
}
}
// Return the minimum configured log level or default to LogLevel.Information if not configured.
return logLevelConfigured ? minimumDiscordLogLevel : LogLevel.Information;
}
/// <summary>
/// Configures an <see cref="ILoggingBuilder"/> with the base logging providers.
/// </summary>
/// <param name="loggingBuilder">The logging builder to configure.</param>
private static void ConfigureBaseLogging(ILoggingBuilder loggingBuilder)
{
loggingBuilder.ClearProviders();
loggingBuilder.AddConsole();
loggingBuilder.AddDebug();
loggingBuilder.AddEventSourceLogger();
}
}
}