|
7 | 7 | "html/template" |
8 | 8 | "log" |
9 | 9 | "net/http" |
| 10 | + "strconv" |
| 11 | + "strings" |
| 12 | + "time" |
10 | 13 | ) |
11 | 14 |
|
12 | 15 | func debug(s string, x ...interface{}) { |
@@ -69,3 +72,167 @@ func send_msg_to_telegram(msg string, bot_token string, chat_id string, thread_i |
69 | 72 | defer resp.Body.Close() |
70 | 73 | } |
71 | 74 | } |
| 75 | + |
| 76 | +// DiscordPayload represents a Discord webhook payload that can include embeds. |
| 77 | +type DiscordPayload struct { |
| 78 | + Username string `json:"username,omitempty"` |
| 79 | + AvatarURL string `json:"avatar_url,omitempty"` |
| 80 | + Content string `json:"content,omitempty"` |
| 81 | + Embeds []DiscordEmbed `json:"embeds,omitempty"` |
| 82 | +} |
| 83 | + |
| 84 | +type DiscordEmbed struct { |
| 85 | + Title string `json:"title,omitempty"` |
| 86 | + Description string `json:"description,omitempty"` |
| 87 | + Color int `json:"color,omitempty"` |
| 88 | + Timestamp string `json:"timestamp,omitempty"` |
| 89 | + Footer *DiscordEmbedFooter `json:"footer,omitempty"` |
| 90 | +} |
| 91 | + |
| 92 | +type DiscordEmbedFooter struct { |
| 93 | + Text string `json:"text,omitempty"` |
| 94 | +} |
| 95 | + |
| 96 | +// format_discord_embeds builds one or more embeds from GotifyMessage. |
| 97 | +// It will split long descriptions into multiple embeds if necessary. |
| 98 | +func format_discord_embeds(msg *GotifyMessage) []DiscordEmbed { |
| 99 | + title := template.HTMLEscapeString(msg.Title) |
| 100 | + body := template.HTMLEscapeString(msg.Message) |
| 101 | + |
| 102 | + // decide color by priority (example mapping) |
| 103 | + color := 0x2ECC71 // green default |
| 104 | + switch msg.Priority { |
| 105 | + case 5: |
| 106 | + color = 0xFF0000 // red |
| 107 | + case 4: |
| 108 | + color = 0xFFA500 // orange |
| 109 | + case 3: |
| 110 | + color = 0xFFFF00 // yellow |
| 111 | + case 2: |
| 112 | + color = 0x3498DB // blue |
| 113 | + } |
| 114 | + |
| 115 | + // Discord embed description limit is 4096 chars; split into chunks safely |
| 116 | + maxDesc := 3800 |
| 117 | + runes := []rune(body) |
| 118 | + var embeds []DiscordEmbed |
| 119 | + for i := 0; i < len(runes); i += maxDesc { |
| 120 | + end := i + maxDesc |
| 121 | + if end > len(runes) { |
| 122 | + end = len(runes) |
| 123 | + } |
| 124 | + desc := string(runes[i:end]) |
| 125 | + embed := DiscordEmbed{ |
| 126 | + Title: title, |
| 127 | + Description: desc, |
| 128 | + Color: color, |
| 129 | + Timestamp: time.Now().UTC().Format(time.RFC3339), |
| 130 | + Footer: &DiscordEmbedFooter{ |
| 131 | + Text: fmt.Sprintf("Gotify Id: %d | Date: %s", msg.Id, msg.Date), |
| 132 | + }, |
| 133 | + } |
| 134 | + // For subsequent chunks, omit the title to avoid repetition |
| 135 | + if i > 0 { |
| 136 | + embed.Title = "" |
| 137 | + } |
| 138 | + embeds = append(embeds, embed) |
| 139 | + } |
| 140 | + return embeds |
| 141 | +} |
| 142 | + |
| 143 | +// send_msg_to_discord posts embeds to a Discord webhook. It will send multiple requests if given multiple embeds. |
| 144 | +func send_msg_to_discord(embeds []DiscordEmbed, webhookURL string, username string, avatarURL string) { |
| 145 | + if webhookURL == "" { |
| 146 | + return |
| 147 | + } |
| 148 | + |
| 149 | + // Discord allows multiple embeds in one payload; however to keep payload sizes safe |
| 150 | + // we will send up to 5 embeds per request (Discord limit is 10 embeds per request). |
| 151 | + maxEmbedsPerRequest := 5 |
| 152 | + client := &http.Client{Timeout: 10 * time.Second} |
| 153 | + for start := 0; start < len(embeds); start += maxEmbedsPerRequest { |
| 154 | + end := start + maxEmbedsPerRequest |
| 155 | + if end > len(embeds) { |
| 156 | + end = len(embeds) |
| 157 | + } |
| 158 | + |
| 159 | + payload := DiscordPayload{ |
| 160 | + Username: username, |
| 161 | + AvatarURL: avatarURL, |
| 162 | + Embeds: embeds[start:end], |
| 163 | + } |
| 164 | + |
| 165 | + payloadBytes, err := json.Marshal(payload) |
| 166 | + if err != nil { |
| 167 | + log.Println("Create discord json false") |
| 168 | + return |
| 169 | + } |
| 170 | + body := bytes.NewReader(payloadBytes) |
| 171 | + |
| 172 | + req, err := http.NewRequest("POST", webhookURL, body) |
| 173 | + if err != nil { |
| 174 | + log.Println("Create discord request false") |
| 175 | + return |
| 176 | + } |
| 177 | + req.Header.Set("Content-Type", "application/json") |
| 178 | + |
| 179 | + // Retry loop with exponential backoff and special handling for 429 |
| 180 | + var resp *http.Response |
| 181 | + var attempt int |
| 182 | + maxRetries := 5 |
| 183 | + for attempt = 0; attempt <= maxRetries; attempt++ { |
| 184 | + resp, err = client.Do(req) |
| 185 | + if err != nil { |
| 186 | + // network error, retry |
| 187 | + backoff := time.Duration(1<<attempt) * 200 * time.Millisecond |
| 188 | + time.Sleep(backoff) |
| 189 | + continue |
| 190 | + } |
| 191 | + |
| 192 | + // handle 429 (rate limit) |
| 193 | + if resp.StatusCode == 429 { |
| 194 | + ra := resp.Header.Get("Retry-After") |
| 195 | + resp.Body.Close() |
| 196 | + var wait time.Duration |
| 197 | + if ra != "" { |
| 198 | + // try seconds first |
| 199 | + if secs, parseErr := strconv.Atoi(strings.TrimSpace(ra)); parseErr == nil { |
| 200 | + wait = time.Duration(secs) * time.Second |
| 201 | + } else if t, parseErr2 := http.ParseTime(ra); parseErr2 == nil { |
| 202 | + wait = time.Until(t) |
| 203 | + if wait < 0 { |
| 204 | + wait = time.Second |
| 205 | + } |
| 206 | + } else { |
| 207 | + wait = time.Duration(1<<attempt) * 500 * time.Millisecond |
| 208 | + } |
| 209 | + } else { |
| 210 | + wait = time.Duration(1<<attempt) * 500 * time.Millisecond |
| 211 | + } |
| 212 | + time.Sleep(wait) |
| 213 | + continue |
| 214 | + } |
| 215 | + |
| 216 | + // retry on 5xx server errors |
| 217 | + if resp.StatusCode >= 500 && resp.StatusCode < 600 { |
| 218 | + resp.Body.Close() |
| 219 | + backoff := time.Duration(1<<attempt) * 500 * time.Millisecond |
| 220 | + time.Sleep(backoff) |
| 221 | + continue |
| 222 | + } |
| 223 | + |
| 224 | + // other status codes (2xx or 4xx) - do not retry |
| 225 | + resp.Body.Close() |
| 226 | + break |
| 227 | + } |
| 228 | + |
| 229 | + if err != nil { |
| 230 | + fmt.Printf("Send discord request false: %v\n", err) |
| 231 | + return |
| 232 | + } |
| 233 | + // if we exhausted retries, log and continue to next batch |
| 234 | + if attempt > maxRetries { |
| 235 | + fmt.Printf("Send discord request failed after %d attempts\n", maxRetries) |
| 236 | + } |
| 237 | + } |
| 238 | +} |
0 commit comments