wabbajack/Wabbajack.Server/Services/DiscordWebHook.cs

83 lines
2.2 KiB
C#
Raw Normal View History

using System;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Wabbajack.BuildServer;
using Wabbajack.Common;
2021-09-27 12:42:46 +00:00
using Wabbajack.DTOs.JsonConverters;
using Wabbajack.Server.DTOs;
2021-10-23 16:51:17 +00:00
namespace Wabbajack.Server.Services;
public enum Channel
{
2021-10-23 16:51:17 +00:00
// High volume messaging, really only useful for internal devs
Spam,
// Low volume messages designed for admins
Ham
}
public class DiscordWebHook : AbstractService<DiscordWebHook, int>
{
private readonly HttpClient _client;
private readonly DTOSerializer _dtos;
private readonly Random _random = new();
public DiscordWebHook(ILogger<DiscordWebHook> logger, AppSettings settings, QuickSync quickSync, HttpClient client,
DTOSerializer dtos) : base(logger, settings, quickSync, TimeSpan.FromHours(1))
{
2021-10-23 16:51:17 +00:00
_settings = settings;
_logger = logger;
_client = client;
_dtos = dtos;
2022-01-18 21:47:36 +00:00
Task.Run(async () =>
{
2022-01-18 21:47:36 +00:00
var message = new DiscordMessage
{
Content = $"\"{await GetQuote()}\" - Sheogorath (as he brings the server online)"
};
await Send(Channel.Ham, message);
await Send(Channel.Spam, message);
});
2021-10-23 16:51:17 +00:00
}
2021-10-23 16:51:17 +00:00
public async Task Send(Channel channel, DiscordMessage message)
{
try
{
var url = channel switch
{
2021-10-23 16:51:17 +00:00
Channel.Spam => _settings.SpamWebHook,
Channel.Ham => _settings.HamWebHook,
_ => null
};
if (url == null) return;
2021-10-23 16:51:17 +00:00
await _client.PostAsync(url,
new StringContent(_dtos.Serialize(message), Encoding.UTF8, "application/json"));
}
2021-10-23 16:51:17 +00:00
catch (Exception ex)
{
2021-10-23 16:51:17 +00:00
_logger.LogError(ex, "While sending discord message");
}
2021-10-23 16:51:17 +00:00
}
2021-10-23 16:51:17 +00:00
private async Task<string> GetQuote()
{
var lines =
await Assembly.GetExecutingAssembly()!.GetManifestResourceStream("Wabbajack.Server.sheo_quotes.txt")!
2021-09-27 12:42:46 +00:00
.ReadLinesAsync()
.ToList();
2021-10-23 16:51:17 +00:00
return lines[_random.Next(lines.Count)].Trim();
}
2021-10-23 16:51:17 +00:00
public override async Task<int> Execute()
{
return 0;
}
2021-10-23 16:51:17 +00:00
}