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
|
|
|
|
{
|
2023-03-31 22:49:39 -07:00
|
|
|
private readonly string[] _webhooks;
|
2023-03-05 20:12:59 -08:00
|
|
|
|
|
|
|
public DiscordWebhookClient(string webhook)
|
|
|
|
{
|
2023-03-31 22:49:39 -07:00
|
|
|
_webhooks = new[] { webhook };
|
2023-03-05 20:12:59 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
public DiscordWebhookClient(string[] webhooks)
|
|
|
|
{
|
|
|
|
_webhooks = webhooks;
|
|
|
|
}
|
|
|
|
|
|
|
|
public void SendMessage(DiscordMessage payload)
|
|
|
|
{
|
2023-03-31 22:49:39 -07:00
|
|
|
if (payload.Embeds is not null) MessageValidation.IsEmbedFooterValid(payload.Embeds);
|
2023-03-05 20:12:59 -08:00
|
|
|
|
|
|
|
foreach (var webhook in _webhooks)
|
|
|
|
{
|
2023-03-31 22:49:39 -07:00
|
|
|
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();
|
|
|
|
|
2023-03-31 22:49:39 -07:00
|
|
|
// 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-04-02 08:03:59 -07:00
|
|
|
{
|
2023-03-05 20:12:59 -08:00
|
|
|
throw new Exception("Message was not accepted by the sever.");
|
2023-04-02 08:03:59 -07:00
|
|
|
}
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|