auspex/mattermost.go

91 lines
2.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"regexp"
"strings"
"time"
)
// mattermostSend отправляет сообщение в Mattermost через Incoming Webhook.
// HTML-теги из Telegram автоматически конвертируются в Markdown.
// Если вебхук не настроен — пишет в лог и не паникует.
func mattermostSend(message string) error {
if !isMattermostConfigured() {
log.Printf("[Mattermost] Не настроен (нужен MATTERMOST_WEBHOOK_URL) — пропускаем")
return fmt.Errorf("mattermost не настроен")
}
mdMessage := mmHTMLToMarkdown(message)
payload := map[string]string{
"text": mdMessage,
}
jsonData, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("marshal error: %w", err)
}
log.Printf("[Mattermost] Отправка вебхук: %s", cfgMattermostWebhookURL)
client := &http.Client{Timeout: 15 * time.Second}
resp, err := client.Post(cfgMattermostWebhookURL, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
return fmt.Errorf("ошибка отправки в Mattermost (webhook: %s): %w", cfgMattermostWebhookURL, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("mattermost webhook error: status %d, body: %s", resp.StatusCode, string(body))
}
return nil
}
// mmHTMLToMarkdown конвертирует HTML-теги Telegram в Markdown для Mattermost.
//
// <b>текст</b> → **текст**
// <i>текст</i> → _текст_
// <code>текст</code> → `текст`
// <pre>текст</pre> → ```текст```
// ━━━ (разделители) → ---
// Остальные теги → удаляются
func mmHTMLToMarkdown(html string) string {
s := html
// <b>...</b> → **...**
s = regexp.MustCompile(`<b>([\s\S]*?)</b>`).ReplaceAllString(s, "**$1**")
// <i>...</i> → _..._
s = regexp.MustCompile(`<i>([\s\S]*?)</i>`).ReplaceAllString(s, "_$1_")
// <code>...</code> → `...`
s = regexp.MustCompile(`<code>([\s\S]*?)</code>`).ReplaceAllString(s, "`$1`")
// <pre>...</pre> → ```...```
s = regexp.MustCompile(`<pre>([\s\S]*?)</pre>`).ReplaceAllString(s, "```$1```")
// HTML-entities
s = strings.ReplaceAll(s, "&lt;", "<")
s = strings.ReplaceAll(s, "&gt;", ">")
s = strings.ReplaceAll(s, "&amp;", "&")
s = strings.ReplaceAll(s, "&quot;", `"`)
// Горизонтальные разделители (━━━...) → ---
s = regexp.MustCompile(`━+`).ReplaceAllString(s, "---")
// Убираем оставшиеся HTML-теги
s = regexp.MustCompile(`<[^>]+>`).ReplaceAllString(s, "")
// Убираем лишние пустые строки (более двух подряд)
s = regexp.MustCompile(`\n{3,}`).ReplaceAllString(s, "\n\n")
return strings.TrimSpace(s)
}