docs: Pachca через входящий вебхук вместо API-токена

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Vladimir V Maksimov
2026-06-14 11:05:14 +03:00
parent a638dd9441
commit a6d2f82633
2 changed files with 40 additions and 20 deletions

View File

@@ -99,8 +99,7 @@ type ConfigTelegram struct {
} }
type ConfigPachca struct { type ConfigPachca struct {
Token string `yaml:"token"` WebhookURL string `yaml:"webhook_url"` // входящий вебхук Pachca
ChatID int64 `yaml:"chat_id"`
} }
type ConfigEmail struct { type ConfigEmail struct {
@@ -394,11 +393,17 @@ Expected: FAIL / build error — `formatMarkdown` и `formatHTML` не суще
package main package main
import ( import (
"bytes"
"encoding/json"
"fmt" "fmt"
"html" "html"
"io"
"net"
"net/http"
"net/mail" "net/mail"
"net/smtp" "net/smtp"
"strings" "strings"
"time"
"gitea.mediatoday.ru/mt/notify" "gitea.mediatoday.ru/mt/notify"
) )
@@ -446,17 +451,29 @@ func (t *telegramNotifier) Send(d RequestData) error {
return err return err
} }
// --- Pachca --- // --- Pachca (входящий вебхук) ---
type pachcaNotifier struct { type pachcaNotifier struct {
client *notify.Pachca webhookURL string
chatID int64 client *http.Client
} }
func (p *pachcaNotifier) Send(d RequestData) error { func (p *pachcaNotifier) Send(d RequestData) error {
_, err := p.client.SendMessage(p.chatID, formatMarkdown(d)) payload, err := json.Marshal(map[string]string{"message": formatMarkdown(d)})
if err != nil {
return err return err
} }
resp, err := p.client.Post(p.webhookURL, "application/json", bytes.NewReader(payload))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("pachca webhook: HTTP %d: %s", resp.StatusCode, string(body))
}
return nil
}
// --- Email --- // --- Email ---
@@ -488,9 +505,12 @@ func BuildNotifiers(cfg *Config) (map[string]Notifier, error) {
} }
if cfg.Pachca != nil { if cfg.Pachca != nil {
if cfg.Pachca.WebhookURL == "" {
return nil, fmt.Errorf("pachca: не задан webhook_url")
}
notifiers["pachca"] = &pachcaNotifier{ notifiers["pachca"] = &pachcaNotifier{
client: notify.NewPachca(cfg.Pachca.Token), webhookURL: cfg.Pachca.WebhookURL,
chatID: cfg.Pachca.ChatID, client: &http.Client{Timeout: 30 * time.Second},
} }
} }
@@ -536,14 +556,12 @@ func BuildNotifiers(cfg *Config) (map[string]Notifier, error) {
Добавить хелпер извлечения хоста (в notifier.go, под `BuildNotifiers`): Добавить хелпер извлечения хоста (в notifier.go, под `BuildNotifiers`):
```go ```go
import "net" // добавить в блок импортов notifier.go
func splitHostPortLenient(addr string) (host, port string, err error) { func splitHostPortLenient(addr string) (host, port string, err error) {
return net.SplitHostPort(addr) return net.SplitHostPort(addr)
} }
``` ```
> Примечание: `splitHostPortLenient` — тонкая обёртка над `net.SplitHostPort`; можно вызвать `net.SplitHostPort` напрямую и убрать хелпер. Оставлено для явности. Не забудь добавить `"net"` в импорты notifier.go. > Примечание: `splitHostPortLenient` — тонкая обёртка над `net.SplitHostPort`; можно вызвать `net.SplitHostPort` напрямую и убрать хелпер. Оставлено для явности. `"net"` уже включён в блок импортов выше.
- [ ] **Step 4: Запустить тесты — убедиться, что проходят** - [ ] **Step 4: Запустить тесты — убедиться, что проходят**
@@ -757,8 +775,7 @@ telegram:
disable_ipv6: true # опционально, по умолчанию true disable_ipv6: true # опционально, по умолчанию true
pachca: pachca:
token: "*****" webhook_url: "https://api.pachca.com/webhooks/XXXX" # входящий вебхук
chat_id: 12345
email: email:
smtp_addr: "smtp.example.com:587" smtp_addr: "smtp.example.com:587"

View File

@@ -61,8 +61,13 @@ type Notifier interface {
- **`telegramNotifier{bot *notify.Bot, chatID int64}`** - **`telegramNotifier{bot *notify.Bot, chatID int64}`**
Форматирует тело в ` ``` `-блок (как сейчас), отправляет `bot.SendTextMessage` Форматирует тело в ` ``` `-блок (как сейчас), отправляет `bot.SendTextMessage`
(ParseMode Markdown). (ParseMode Markdown).
- **`pachcaNotifier{client *notify.Pachca, chatID int64}`** - **`pachcaNotifier{webhookURL string, client *http.Client}`**
Форматирует в markdown ` ``` `-блок, отправляет `client.SendMessage(chatID, text)`. Использует **входящий вебхук** Pachca (incoming webhook), а не API-токен.
Форматирует в markdown ` ``` `-блок и POST-ит `{"message": text}` (JSON,
`Content-Type: application/json`) на `webhook_url`. Токен/chat_id не нужны —
идентификатор в URL и есть авторизация; сообщение уходит во все групповые чаты,
где состоит бот. Библиотечный `notify.Pachca` (Bearer API + chat_id) для этого
НЕ используется. Проверено: тестовый POST вернул `200`.
- **`emailNotifier{auth notify.SmtpAuth, from mail.Address, to []mail.Address, subject string}`** - **`emailNotifier{auth notify.SmtpAuth, from mail.Address, to []mail.Address, subject string}`**
Форматирует тело в `<pre>…</pre>` с HTML-экранированием содержимого, отправляет Форматирует тело в `<pre>…</pre>` с HTML-экранированием содержимого, отправляет
`notify.SendEmailHTML(auth, body, subject, from, to...)`. `notify.SendEmailHTML(auth, body, subject, from, to...)`.
@@ -88,8 +93,7 @@ telegram:
disable_ipv6: true # опционально, по умолчанию true disable_ipv6: true # опционально, по умолчанию true
pachca: pachca:
token: "*****" webhook_url: "https://api.pachca.com/webhooks/XXXX" # входящий вебхук
chat_id: 12345
email: email:
smtp_addr: "smtp.example.com:587" smtp_addr: "smtp.example.com:587"
@@ -119,8 +123,7 @@ type ConfigTelegram struct {
} }
type ConfigPachca struct { type ConfigPachca struct {
Token string `yaml:"token"` WebhookURL string `yaml:"webhook_url"` // входящий вебхук Pachca
ChatID int64 `yaml:"chat_id"`
} }
type ConfigEmail struct { type ConfigEmail struct {