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

49 lines
1.5 KiB
C#

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 DiscordClient : IDiscordClient
{
private readonly string[] _webhooks;
public DiscordClient(string webhook)
{
_webhooks = new[] { webhook };
}
public DiscordClient(string[] webhooks)
{
_webhooks = webhooks;
}
public void SendMessage(DiscordMessage payload)
{
if (payload.Embeds is not null) MessageValidation.IsEmbedFooterValid(payload.Embeds);
foreach (var webhook in _webhooks)
{
var jsonRaw = JsonConvert.SerializeObject(payload, Formatting.None,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
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);
if (resp.Result.StatusCode != HttpStatusCode.NoContent)
{
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");
}
}
}
}