1package main
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "net/http"
9
10 "github.com/bluesky-social/indigo/util"
11)
12
13type SlackWebhookBody struct {
14 Text string `json:"text"`
15}
16
17// sends a simple slack message to a channel via "incoming webhook"
18// The slack incoming webhook must be already configured in the slack workplace.
19func sendSlackMsg(ctx context.Context, msg, webhookURL string) error {
20 // loosely based on: https://golangcode.com/send-slack-messages-without-a-library/
21
22 body, _ := json.Marshal(SlackWebhookBody{Text: msg})
23 req, err := http.NewRequestWithContext(ctx, http.MethodPost, webhookURL, bytes.NewBuffer(body))
24 if err != nil {
25 return err
26 }
27 req.Header.Add("Content-Type", "application/json")
28 client := util.RobustHTTPClient()
29 resp, err := client.Do(req)
30 if err != nil {
31 return err
32 }
33
34 defer resp.Body.Close()
35
36 buf := new(bytes.Buffer)
37 buf.ReadFrom(resp.Body)
38 if resp.StatusCode != 200 || buf.String() != "ok" {
39 return fmt.Errorf("failed slack webhook POST request. status=%d", resp.StatusCode)
40 }
41 return nil
42}