113 lines
3.7 KiB
C#
113 lines
3.7 KiB
C#
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
|
|
{
|
|
public static DiscordSocketClient _client = null;
|
|
|
|
public static async Task StartUp()
|
|
{
|
|
try
|
|
{
|
|
using (var services = ConfigureServices())
|
|
{
|
|
// get the client and assign to client
|
|
// you get the services via GetRequiredService<T>
|
|
DiscordSocketClient 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)
|
|
{
|
|
LoggingFacade.Exception(ex);
|
|
}
|
|
}
|
|
|
|
private static Task ReadyAsync()
|
|
{
|
|
LoggingFacade.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)
|
|
{
|
|
LoggingFacade.Exception(ex);
|
|
}
|
|
|
|
return csInfo;
|
|
}
|
|
|
|
private static Task Log(LogMessage msg)
|
|
{
|
|
try
|
|
{
|
|
switch (msg.Severity)
|
|
{
|
|
case LogSeverity.Critical:
|
|
LoggingFacade.Fatal(msg.Message);
|
|
break;
|
|
case LogSeverity.Debug:
|
|
LoggingFacade.Debug(msg.Message);
|
|
break;
|
|
case LogSeverity.Error:
|
|
LoggingFacade.Error(msg.Message);
|
|
break;
|
|
case LogSeverity.Info:
|
|
LoggingFacade.Info(msg.Message);
|
|
break;
|
|
case LogSeverity.Warning:
|
|
LoggingFacade.Warn(msg.Message);
|
|
break;
|
|
case LogSeverity.Verbose:
|
|
LoggingFacade.Trace(msg.Message);
|
|
break;
|
|
default:
|
|
LoggingFacade.Trace(msg.Message);
|
|
break;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LoggingFacade.Exception(ex);
|
|
}
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
}
|