-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProgram.cs
151 lines (129 loc) · 6.13 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
using Discord;
using Discord.Interactions;
using Discord.WebSocket;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using SolarisBot.ConfigFiles;
using SolarisBot.Database;
using SolarisBot.Discord.Common.Attributes;
using SolarisBot.Discord.Services;
using System.Reflection;
namespace SolarisBot
{
internal static class Program
{
static async Task Main(string[] args)
{
BotConfig botConfig;
var assembly = Assembly.GetExecutingAssembly();
try
{
botConfig = GetOrCreateBotConfig();
ConfigFileProvider.LoadConfigFiles(assembly);
}
catch (Exception ex)
{
Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
throw;
}
var configuration = CreateConfiguration();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
logger.Information("SolarisBot by PaciStardust is starting");
logger.Information("Initializing hosting, building host");
var host = CreateHost(configuration, botConfig, logger, assembly);
logger.Information("Build complete, starting host");
//Starting DbService before all else
await host.Services.GetRequiredService<DatabaseService>().ReadyAsync();
await host.RunAsync();
}
#region Setup
private static IConfiguration CreateConfiguration()
=> new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(Path.Combine(Utils.PathConfigDirectory, "appsettings.json"), true, true)
.AddJsonFile(Path.Combine(Utils.PathConfigDirectory, $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Unknown"}.json"), true, true)
.AddEnvironmentVariables()
.Build();
private static IHost CreateHost(IConfiguration configuration, BotConfig botConfig, ILogger logger, Assembly assembly)
=> Host.CreateDefaultBuilder()
.ConfigureAppConfiguration(config => config.AddConfiguration(configuration))
.ConfigureServices(services =>
{
services.AddSingleton<DatabaseService>();
services.AddHttpClient();
services.AddSingleton(botConfig);
services.AddSingleton(new DiscordSocketClient(new()
{
GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.MessageContent | GatewayIntents.GuildMembers,
UseInteractionSnowflakeDate = false,
DefaultRetryMode = RetryMode.RetryRatelimit
}));
//Fix for constructor of interaction service being broken (Provided by Discord.NET discord)
services.AddSingleton(x => new InteractionService(x.GetRequiredService<DiscordSocketClient>()));
services.AddHostedService<DiscordClientService>();
LoadServicesFromAssembly(services, assembly, botConfig, logger);
})
.UseSerilog(logger)
.Build();
/// <summary>
/// Loads a config or generates a new one if needed, updates it and saves it
/// </summary>
/// <returns>Updated BotConfig</returns>
private static BotConfig GetOrCreateBotConfig()
{
Console.WriteLine($"Loading config from {Utils.PathConfigFile}");
var botConfig = BotConfig.FromFile(Utils.PathConfigFile) ?? new();
if (string.IsNullOrWhiteSpace(botConfig.Token))
{
Console.Write("Token > ");
botConfig.Token = Console.ReadLine() ?? string.Empty;
}
if (botConfig.MainGuild == 0)
{
Console.Write("Main Guild > ");
botConfig.MainGuild = ulong.Parse(Console.ReadLine() ?? string.Empty);
}
Console.WriteLine("Updating and saving config");
botConfig.Update();
botConfig.SaveAt(Utils.PathConfigFile);
return botConfig;
}
/// <summary>
/// Loads services into servicecollection from assembly
/// </summary>
private static void LoadServicesFromAssembly(IServiceCollection services, Assembly assembly, BotConfig botConfig, ILogger logger)
{
foreach (var service in assembly.GetTypes())
{
var autoLoadAttribute = service.GetCustomAttribute<AutoLoadServiceAttribute>();
if (autoLoadAttribute is null)
continue;
bool isHosted = typeof(IHostedService).IsAssignableFrom(service);
var attribute = service.GetCustomAttribute<ModuleAttribute>();
var moduleNamesText = attribute is null ? "NONE" : string.Join(" + ", attribute.ModuleNames);
if (attribute?.IsDisabled(botConfig.DisabledModules) ?? false)
{
logger.Information("Skipping adding {serviceType} {service} from disabled module {module}", isHosted ? "HostedService" : "Service", service.FullName, moduleNamesText);
continue;
}
logger.Information("Adding {serviceType} {service} from module {module}", isHosted ? "HostedService" : "Service", service.FullName, moduleNamesText);
if (isHosted)
services.AddSingleton(typeof(IHostedService), service);
else
{
switch (autoLoadAttribute.Lifetime)
{
case Lifetime.Transient: services.AddTransient(service); break;
case Lifetime.Scoped: services.AddScoped(service); break;
default: services.AddSingleton(service); break;
}
}
}
}
#endregion
}
}