chore: build

This commit is contained in:
2026-06-12 11:13:47 +02:00
parent cc278ecef5
commit 20da2a560f
8 changed files with 174 additions and 16 deletions
+69
View File
@@ -4,9 +4,11 @@ import (
"bytes"
"encoding/json"
"fmt"
"gestion/models"
"log"
"net/http"
"os"
"sync"
"time"
)
@@ -17,6 +19,8 @@ type TelegramService struct {
webhookSecret string
BotUsername string
notificationsEnabled bool
notifBots []models.TelegramBotConfig
notifMu sync.RWMutex
}
func NewTelegramService() *TelegramService {
@@ -41,6 +45,71 @@ func (t *TelegramService) SetNotificationsEnabled(enabled bool) {
t.notificationsEnabled = enabled
}
// ReloadNotifBots met à jour la liste des bots de notification (thread-safe).
func (t *TelegramService) ReloadNotifBots(bots []models.TelegramBotConfig) {
t.notifMu.Lock()
defer t.notifMu.Unlock()
t.notifBots = bots
log.Printf("✅ [TELEGRAM] %d bot(s) de notification chargé(s)", len(bots))
}
// SendNotif envoie un message HTML en essayant chaque bot de notification dans l'ordre.
// En cas de rate-limit (429) ou d'erreur sur le bot courant, il passe au suivant.
func (t *TelegramService) SendNotif(chatID int64, text string) error {
t.notifMu.RLock()
bots := make([]models.TelegramBotConfig, len(t.notifBots))
copy(bots, t.notifBots)
t.notifMu.RUnlock()
if len(bots) == 0 {
// Fallback : utiliser le bot webhook principal
return t.SendMessage(chatID, text)
}
var lastErr error
for i, bot := range bots {
if err := t.sendWithToken(bot.Token, chatID, text); err != nil {
log.Printf("⚠️ [TELEGRAM] bot %d (%s) échoué: %v — essai suivant", i+1, bot.Username, err)
lastErr = err
continue
}
return nil
}
return fmt.Errorf("tous les bots de notification ont échoué: %w", lastErr)
}
// sendWithToken envoie un message HTML avec un token arbitraire.
func (t *TelegramService) sendWithToken(token string, chatID int64, text string) error {
payload := map[string]interface{}{
"chat_id": chatID,
"text": text,
"parse_mode": "HTML",
}
body, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("marshal: %w", err)
}
url := fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", token)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(body))
if err != nil {
return fmt.Errorf("création requête: %w", err)
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("envoi: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusTooManyRequests {
return fmt.Errorf("rate limit (429)")
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("status %d", resp.StatusCode)
}
return nil
}
// Reload met à jour le token et le username (appelé après UpdateSettings)
func (t *TelegramService) Reload(token, username string) {
if token != "" {