chaosbot/ChaosBot/Discord/DiscordConnect.cs

115 lines
3.9 KiB
C#

using NLog;
using System;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System.Threading.Tasks;
using ChaosBot.Discord.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ChaosBot.Discord
{
public class DiscordConnect
{
private static DiscordSocketClient _client;
private static ILogger _logger = Program.Logger;
public static async Task StartUp()
{
try
{
using (var services = ConfigureServices())
{
// get the client and assign to client
// you get the services via GetRequiredService<T>
var client = services.GetRequiredService<DiscordSocketClient>();
_client = client;
// setup logging and the ready event
client.Log += Log;
client.Ready += ReadyAsync;
services.GetRequiredService<CommandService>().Log += Log;
// this is where we get the Token value from the configuration file, and start the bot
await client.LoginAsync(TokenType.Bot, Program.AppSettingsHandler.GetValue<string>("Discord:Token"));
await client.StartAsync();
// we get the CommandHandler class here and call the InitializeAsync method to start things up for the CommandHandler service
await services.GetRequiredService<CommandHandler>().InitializeAsync();
TimerHandler.Initialize(services);
await Task.Delay(-1);
}
}
catch (Exception ex)
{
_logger.Error($"DiscordConnect.StartUp: Exception [{ex}] thrown, <[{ex.Message}]>.");
}
}
private static Task ReadyAsync()
{
_logger.Info($"Connected as -> [{_client.CurrentUser}] :)");
return Task.CompletedTask;
}
private static ServiceProvider ConfigureServices()
{
ServiceProvider csInfo = null;
try
{
csInfo = new ServiceCollection()
.AddSingleton<DiscordSocketClient>()
.AddSingleton<CommandService>()
.AddSingleton<CommandHandler>()
.BuildServiceProvider();
}
catch (Exception ex)
{
_logger.Error($"DiscordConnect.ConfigureServices: Exception [{ex}] thrown, <[{ex.Message}]>.");
}
return csInfo;
}
private static Task Log(LogMessage msg)
{
try
{
switch (msg.Severity)
{
case LogSeverity.Critical:
_logger.Fatal(msg.Message);
break;
case LogSeverity.Debug:
_logger.Debug(msg.Message);
break;
case LogSeverity.Error:
_logger.Error(msg.Message);
break;
case LogSeverity.Info:
_logger.Info(msg.Message);
break;
case LogSeverity.Warning:
_logger.Warn(msg.Message);
break;
case LogSeverity.Verbose:
_logger.Trace(msg.Message);
break;
default:
_logger.Trace(msg.Message);
break;
}
}
catch (Exception ex)
{
_logger.Error($"DiscordConnect.Log: Exception [{ex}] thrown, <[{ex.Message}]>.");
}
return Task.CompletedTask;
}
}
}