director/HumanCommunication.cs

59 lines
2.1 KiB
C#
Raw Normal View History

using System;
using System.IO;
using System.Net;
namespace Director
{
public class HumanCommunication
{
private static string call_for_humans_discord_webhook{get;set;}
private static HumanCommunication _instance = null;
private static readonly object createLock = new object();
public static void Configure(string call_for_humans_discord_webhook)
{
lock (createLock)
{
if (_instance == null)
{
_instance = new HumanCommunication(call_for_humans_discord_webhook);
}
}
}
public static HumanCommunication Instance
{
get
{
lock (createLock)
{
if (_instance == null)
{
throw new NotInitializedException("Configure me first");
}
}
return _instance;
}
}
private HumanCommunication(string discord_webhook)
{
HumanCommunication.call_for_humans_discord_webhook = discord_webhook;
}
public void Say(string message, LogLevel logLevel = LogLevel.Info)
{
Console.WriteLine($"[{DateTime.Now.ToLongTimeString()}] [{logLevel.ToString()}] {message}");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(call_for_humans_discord_webhook);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write($"{{\"content\":\"[{DateTime.Now.ToLongTimeString()}] [{logLevel.ToString()}] {message}\"}}");
}
httpWebRequest.GetResponse();
}
public enum LogLevel { Trace, Verbose, Info, Warning, Error, Showstopper }
}
public class NotInitializedException : Exception
{
public NotInitializedException(string message) : base(message) { }
}
}