| 165 | } |
| 166 | |
| 167 | func sendMessage(context webhook.Context) error { |
| 168 | text := getMarkdownText(context) |
| 169 | mentionUsersByPhone := []string{} |
| 170 | |
| 171 | if len(context.MentionEndUsers) > 0 { |
| 172 | var ats []string |
| 173 | for _, user := range context.MentionEndUsers { |
| 174 | phone, err := getDingTalkMobileFromUser(user) |
| 175 | if err != nil { |
| 176 | slog.Warn("failed to parse user phone", log.BBError(err), slog.String("user", user.Name)) |
| 177 | continue |
| 178 | } |
| 179 | if phone != "" { |
| 180 | ats = append(ats, fmt.Sprintf("@%s", phone)) |
| 181 | } |
| 182 | } |
| 183 | text += "\n" + strings.Join(ats, " ") |
| 184 | } |
| 185 | |
| 186 | post := Message{ |
| 187 | MessageType: "markdown", |
| 188 | Markdown: MessageMarkdown{ |
| 189 | Title: context.TitleZh, |
| 190 | Text: text, |
| 191 | }, |
| 192 | } |
| 193 | if len(mentionUsersByPhone) > 0 { |
| 194 | post.Mention.Mobiles = append(post.Mention.Mobiles, mentionUsersByPhone...) |
| 195 | } |
| 196 | |
| 197 | body, err := json.Marshal(post) |
| 198 | if err != nil { |
| 199 | return errors.Wrapf(err, "failed to marshal webhook POST request to %s", context.URL) |
| 200 | } |
| 201 | req, err := http.NewRequest("POST", |
| 202 | context.URL, bytes.NewBuffer(body)) |
| 203 | if err != nil { |
| 204 | return errors.Wrapf(err, "failed to construct webhook POST request to %s", context.URL) |
| 205 | } |
| 206 | |
| 207 | req.Header.Set("Content-Type", "application/json") |
| 208 | client := &http.Client{ |
| 209 | Timeout: webhook.Timeout, |
| 210 | } |
| 211 | resp, err := client.Do(req) |
| 212 | if err != nil { |
| 213 | return errors.Wrapf(err, "failed to POST webhook to %s", context.URL) |
| 214 | } |
| 215 | |
| 216 | b, err := io.ReadAll(resp.Body) |
| 217 | if err != nil { |
| 218 | return errors.Wrapf(err, "failed to read POST webhook response from %s", context.URL) |
| 219 | } |
| 220 | defer resp.Body.Close() |
| 221 | |
| 222 | if resp.StatusCode != http.StatusOK { |
| 223 | return errors.Errorf("failed to POST webhook %s, status code: %d, response body: %s", context.URL, resp.StatusCode, b) |
| 224 | } |