Newsbot.Collector/Newsbot.Collector.Services/Notifications/Discord/DiscordWebhookClient.cs

49 lines
1.6 KiB
C#
Raw Normal View History

2023-03-05 20:12:59 -08:00
using System.Net;
using System.Text;
using Newsbot.Collector.Domain.Interfaces;
using Newsbot.Collector.Domain.Models;
using Newtonsoft.Json;
namespace Newsbot.Collector.Services.Notifications.Discord;
public class DiscordWebhookClient : IDiscordNotificatioClient
{
private readonly string[] _webhooks;
2023-03-05 20:12:59 -08:00
public DiscordWebhookClient(string webhook)
{
_webhooks = new[] { webhook };
2023-03-05 20:12:59 -08:00
}
public DiscordWebhookClient(string[] webhooks)
{
_webhooks = webhooks;
}
public void SendMessage(DiscordMessage payload)
{
if (payload.Embeds is not null) MessageValidation.IsEmbedFooterValid(payload.Embeds);
2023-03-05 20:12:59 -08:00
foreach (var webhook in _webhooks)
{
var jsonRaw = JsonConvert.SerializeObject(payload, Formatting.None,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
2023-03-05 20:12:59 -08:00
using StringContent jsonContent = new(jsonRaw, Encoding.UTF8, "application/json");
using var client = new HttpClient();
var resp = client.PostAsync(webhook, jsonContent);
resp.Wait();
// can be 204 or a message, might be 200
Console.WriteLine(resp.Result.StatusCode);
2023-03-05 20:12:59 -08:00
if (resp.Result.StatusCode != HttpStatusCode.NoContent)
{
2023-03-05 20:12:59 -08:00
throw new Exception("Message was not accepted by the sever.");
}
if (resp.Result.StatusCode == HttpStatusCode.BadRequest)
{
throw new Exception("Message was not accepted. Make sure all values are not null");
}
2023-03-05 20:12:59 -08:00
}
}
}