https://api.slack.com/methods/chat.postMessage
(ctx context.Context, channelID string, webhookContext webhook.Context)
| 198 | |
| 199 | // https://api.slack.com/methods/chat.postMessage |
| 200 | func (p *provider) chatPostMessage(ctx context.Context, channelID string, webhookContext webhook.Context) error { |
| 201 | msg := BuildMessage(webhookContext) |
| 202 | attachmentsJSON, err := json.Marshal(msg.Attachments) |
| 203 | if err != nil { |
| 204 | return errors.Wrapf(err, "failed to marshal attachments") |
| 205 | } |
| 206 | |
| 207 | data := url.Values{} |
| 208 | data.Set("channel", channelID) |
| 209 | if msg.Text != "" { |
| 210 | data.Set("text", msg.Text) |
| 211 | } |
| 212 | data.Set("attachments", string(attachmentsJSON)) |
| 213 | |
| 214 | req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://slack.com/api/chat.postMessage", strings.NewReader(data.Encode())) |
| 215 | if err != nil { |
| 216 | return errors.Wrapf(err, "failed to new request") |
| 217 | } |
| 218 | req.Header.Add("Authorization", "Bearer "+p.token) |
| 219 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 220 | |
| 221 | resp, err := p.c.Do(req) |
| 222 | if err != nil { |
| 223 | return errors.Wrapf(err, "failed to send request") |
| 224 | } |
| 225 | defer resp.Body.Close() |
| 226 | |
| 227 | if resp.StatusCode != http.StatusOK { |
| 228 | return errors.Errorf("received non-200 status code %d", resp.StatusCode) |
| 229 | } |
| 230 | |
| 231 | body, err := io.ReadAll(resp.Body) |
| 232 | if err != nil { |
| 233 | return errors.Wrapf(err, "failed to read body") |
| 234 | } |
| 235 | var res chatPostMessageResponse |
| 236 | if err := json.Unmarshal(body, &res); err != nil { |
| 237 | return errors.Wrapf(err, "failed to unmarshal") |
| 238 | } |
| 239 | if !res.OK { |
| 240 | return errors.Errorf("failed to post message, error: %v", res.Error) |
| 241 | } |
| 242 | |
| 243 | return nil |
| 244 | } |
no test coverage detected