itfx/src/InterfaceForward.Domain.Shared/FeiShu/FeiShuNoticer.cs
2024-05-21 00:20:28 +09:00

78 lines
2.3 KiB
C#

using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace InterfaceForward.Domain.Shared.FeiShu;
public class FeiShuNoticer : IFeiShuNoticer
{
private readonly FeiShuNoticeOptions _options;
private readonly HttpClient _httpClient;
private readonly ILogger<FeiShuNoticer> _logger;
public FeiShuNoticer(IOptions<FeiShuNoticeOptions> options, HttpClient httpClient, ILogger<FeiShuNoticer> logger)
{
_options = options.Value;
_httpClient = httpClient;
_logger = logger;
}
public async Task NoticeAsync(string content, string subTitle = "")
{
try
{
if (_options.Webhook.IsNullOrWhiteSpace())
{
_logger.LogWarning("未配置飞书webhook");
return;
}
var title = subTitle.IsNullOrWhiteSpace()
? _options.TitlePrefix
: _options.TitlePrefix + "_" + subTitle;
await HandleNoticeAsync(content, title);
}
catch (Exception e)
{
// 这里失败不应该影响业务
_logger.LogWarning($"飞书通知失败,{e.Message}");
}
}
private async Task HandleNoticeAsync(string content, string title)
{
var message = new
{
msg_type = "post",
content = new
{
post = new
{
zh_cn = new
{
title,
content = new List<object>()
{
new List<object>()
{
new
{
tag = "text",
text = content + Environment.NewLine
}
}
}
}
}
}
};
var httpContent = new StringContent(JsonSerializer.Serialize(message), Encoding.UTF8);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
await _httpClient.PostAsync(_options.Webhook, httpContent);
}
}