105 lines
3.0 KiB
C#
105 lines
3.0 KiB
C#
using Discord;
|
|
using Discord.WebSocket;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
using Serilog;
|
|
using Serilog.Events;
|
|
|
|
namespace GodReplacementProduct;
|
|
|
|
public class Program
|
|
{
|
|
public static int Main(string[] args)
|
|
{
|
|
Log.Logger = new LoggerConfiguration()
|
|
.MinimumLevel.Debug()
|
|
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
|
|
.Enrich.FromLogContext()
|
|
.WriteTo.Console()
|
|
.CreateLogger();
|
|
|
|
try
|
|
{
|
|
Log.Information("Starting host");
|
|
BuildHost(args).Run();
|
|
return 0;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Log.Fatal(ex, "Host terminated unexpectedly");
|
|
return 1;
|
|
}
|
|
finally
|
|
{
|
|
Log.CloseAndFlush();
|
|
}
|
|
}
|
|
|
|
public static IHost BuildHost(string[] args) => new HostBuilder()
|
|
.ConfigureAppConfiguration((context) => context
|
|
.AddUserSecrets<Program>()
|
|
.Build()
|
|
)
|
|
.ConfigureServices(services => services
|
|
.AddSingleton<DiscordSocketClient>()
|
|
.AddHostedService<GodReplacementBot>()
|
|
)
|
|
.UseSerilog((context, services, loggerConfiguration) => loggerConfiguration
|
|
.ReadFrom.Configuration(context.Configuration)
|
|
.Enrich.FromLogContext()
|
|
.WriteTo.Console())
|
|
.Build();
|
|
}
|
|
|
|
public sealed class GodReplacementBot : IHostedService
|
|
{
|
|
private readonly ILogger<GodReplacementBot> _logger;
|
|
private readonly IConfiguration _config;
|
|
private readonly DiscordSocketClient _client;
|
|
|
|
public GodReplacementBot(
|
|
ILogger<GodReplacementBot> logger,
|
|
IConfiguration config,
|
|
DiscordSocketClient client
|
|
)
|
|
{
|
|
_config = config;
|
|
_client = client;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
var token = _config.GetValue<string>("GodReplacementProject:DiscordToken");
|
|
_client.Log += LogAsync;
|
|
|
|
await _client.LoginAsync(TokenType.Bot, token);
|
|
await _client.StartAsync();
|
|
}
|
|
|
|
public async Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
await _client.StopAsync();
|
|
}
|
|
|
|
private Task LogAsync(LogMessage message) {
|
|
var severity = message.Severity switch
|
|
{
|
|
LogSeverity.Critical => LogLevel.Critical,
|
|
LogSeverity.Error => LogLevel.Error,
|
|
LogSeverity.Warning => LogLevel.Warning,
|
|
LogSeverity.Info => LogLevel.Information,
|
|
LogSeverity.Verbose => LogLevel.Debug,
|
|
LogSeverity.Debug => LogLevel.Trace,
|
|
_ => LogLevel.Information,
|
|
};
|
|
|
|
_logger.Log(severity, message.Exception, "[{Source}] {Message}", message.Source, message.Message);
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
}
|