Notificaciones ntfy
NtfyClientC publica notificaciones push en un topic de ntfy con título, prioridad, Markdown, botones y adjuntos, por separado o conectado a Dinaup.Logs.
NtfyClientC, del módulo dinaup.ntfy, publica notificaciones push en un topic de ntfy. Se usa suelto o conectado a Dinaup.Logs, para que los logs disparen avisos.
Antes de empezar
- Paquete
Dinaupinstalado. Ver SDK .NET. - La URL de un servidor ntfy y, para topics protegidos, un token de acceso.
Crear el cliente
using Dinaup.Ntfy;
var ntfy = new NtfyClientC("https://ntfy.tu-dominio.com", "tk_tu-token"); // el token es opcional
var conOpciones = new NtfyClientC(new NtfyClientOptions
{
ServerUrl = "https://ntfy.tu-dominio.com",
AccessToken = "tk_tu-token",
DefaultTopic = "mi-app",
DefaultPriority = NtfyPriority.Default,
DefaultIcon = "https://cdn.tu-dominio.com/icono.png",
Timeout = TimeSpan.FromSeconds(30)
});Otro constructor recibe además tu propio HttpClient. ServerUrl e IsAuthenticated describen el cliente, que implementa IDisposable.
Enviar
await ntfy.SendAsync("mi-app", "Stock por debajo del mínimo", "Aviso de inventario", NtfyPriority.High);
await ntfy.SendWithActionsAsync("mi-app", "Pedido 1234 pendiente de revisar", new[]
{
NtfyAction.CreateViewAction("Abrir pedido", "https://play.dinaup.com/pedidos/1234"),
NtfyAction.CreateHttpAction("Aprobar", "https://api.tu-dominio.com/pedidos/1234/aprobar", clearOnClick: true)
});Prioridades: Minimum, Low, Default, High y Urgent. Cada envío devuelve un NtfyResult con IsSuccess, ErrorMessage y MessageId, y admite un CancellationToken al final.
| Método | Qué envía |
|---|---|
SendAsync(topic, message), (topic, message, title), (topic, message, title, priority) | Texto plano. |
SendMarkdownAsync(topic, message, title, priority) | Cuerpo en Markdown. |
SendWithClickUrlAsync(topic, message, clickUrl) y (topic, message, title, clickUrl, priority) | Abre una URL al tocar la notificación. |
SendWithActionsAsync(topic, message, actions) y (topic, message, title, priority, actions) | Botones: NtfyAction.CreateViewAction(label, url, clearOnClick) abre una URL y CreateHttpAction(label, url, clearOnClick) hace una petición HTTP. |
SendWithAttachmentUrlAsync(topic, message, attachmentUrl, filename) y (topic, message, title, attachmentUrl, filename, priority) | Adjunto por URL. |
SendWithAttachmentAsync(topic, message, fileBytes, filename, mimeType) y (topic, message, title, fileBytes, filename, mimeType, priority) | Adjunto por bytes. |
SendAppStartupAsync(topic, additionalInfo), SendAppShutdownAsync(topic, reason), SendAppErrorAsync(topic, exception, context) | Arranque, parada y error de la app, con nombre, versión y entorno. |
Conexión con los logs
Pasa el cliente y un topic a Logs.Initialize:
var loki = new Logs.LokiConfig { Endpoint = "https://loki.tu-dominio.com/loki/api/v1/push" };
Logs.Initialize(loki, ntfy, "mi-app-alertas");Desde ahí, cada Logs.Information, Logs.Warning, Logs.Error y Logs.Fatal publica un aviso en segundo plano (la sobrecarga de Information con excepción no publica). El nivel decide el topic y la prioridad:
| Nivel de log | Topic | Prioridad ntfy |
|---|---|---|
Information | mi-app-alertas-inf | Default |
Warning | mi-app-alertas-wrn | Default |
Error | mi-app-alertas-err | High |
Fatal | mi-app-alertas-ftl | Urgent |
El cuerpo lleva el mensaje con sus valores y una línea con nivel, app, versión, entorno, máquina y hora; con excepción, su tipo, su mensaje y los primeros 300 caracteres de la pila. Como mucho salen 60 avisos cada 20 segundos: los que pasan del límite se descartan y el log se escribe igual.
Con Logs conectado, también envías avisos sin pasar por un nivel de log. No lanzan si ntfy no está configurado; Logs.IsNtfyConfigured dice si lo está.
await Logs.SendNotificationAsync("Cierre de caja pendiente", "Recordatorio", NtfyPriority.Default);
await Logs.SendErrorNotificationAsync(ex, "Importador nocturno");
await Logs.SendShutdownNotificationAsync("Despliegue programado");Para avisar a otros sistemas de un cambio en Dinaup (un pedido nuevo, una ficha que cambia), usa los webhooks salientes.