Files
aura-crm/production/backend/internal/clientnotify/tg.go
T

50 lines
1.4 KiB
Go

package clientnotify
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
// buildTGSendRequest mirrors internal/notify's buildSendRequest but targets
// an arbitrary per-client chat_id instead of the one fixed staff chat —
// kept as its own small function (not exported from notify) since the two
// packages' failure semantics differ: a client send updates an outbox row,
// a staff send is fire-and-forget.
func buildTGSendRequest(ctx context.Context, text, botToken, chatID, baseURL string) (*http.Request, error) {
payload, err := json.Marshal(map[string]string{"chat_id": chatID, "text": text})
if err != nil {
return nil, err
}
url := baseURL + "/bot" + botToken + "/sendMessage"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
return req, nil
}
type tgSendResponse struct {
OK bool `json:"ok"`
Description string `json:"description"`
Result struct {
MessageID int `json:"message_id"`
} `json:"result"`
}
func parseTGSendResponse(body io.Reader) (string, error) {
var r tgSendResponse
if err := json.NewDecoder(body).Decode(&r); err != nil {
return "", fmt.Errorf("telegram: malformed response: %w", err)
}
if !r.OK {
return "", fmt.Errorf("telegram: %s", r.Description)
}
return fmt.Sprintf("%d", r.Result.MessageID), nil
}