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 string[] _webhooks; public DiscordWebhookClient(string webhook) { _webhooks = new string[] { webhook }; } public DiscordWebhookClient(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, Newtonsoft.Json.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(); if (resp.Result.StatusCode != HttpStatusCode.NoContent) { throw new Exception("Message was not accepted by the sever."); } } } }