-
Notifications
You must be signed in to change notification settings - Fork 0
/
send_slack_message.go
105 lines (90 loc) · 2.25 KB
/
send_slack_message.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package examples
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"github.com/joho/godotenv"
"github.com/slzhffktm/go-http-test/internal/httpclient"
)
func init() {
// Load the .env file
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
slackClient = httpclient.New(os.Getenv("SLACK_URL"), http.DefaultClient)
}
const (
SlackChatPostMessagePath = "/api/chat.postMessage"
SlackGetPermalinkPath = "/api/chat.getPermalink"
)
var (
slackClient *httpclient.HttpClient
)
// SendSlackMessage sends message to Slack and return the url of the message.
func SendSlackMessage(ctx context.Context, channel, text string) (url_ string, err_ error) {
reqBody := map[string]any{
"channel": channel,
"text": text,
}
reqHeader := map[string]string{
"Content-Type": "application/json",
"Authorization": "Bearer " + os.Getenv("SLACK_TOKEN"),
}
reqBodyByte, err := json.Marshal(&reqBody)
if err != nil {
return "", err
}
res, resBodyByte, err := slackClient.Do(
ctx,
http.MethodPost,
SlackChatPostMessagePath,
reqHeader,
reqBodyByte,
nil,
)
if err != nil {
return "", fmt.Errorf("send slack message: %w", err)
}
if res.StatusCode != http.StatusOK {
return "", fmt.Errorf(
"send slack message: status code %d, res body: %s",
res.StatusCode,
string(resBodyByte),
)
}
var resBody map[string]any
if err := json.Unmarshal(resBodyByte, &resBody); err != nil {
return "", fmt.Errorf("unmarshal res body: %w", err)
}
qParams := url.Values{}
qParams.Add("channel", channel)
qParams.Add("message_ts", resBody["ts"].(string))
permalinkRes, permalinkResBodyByte, err := slackClient.Do(
ctx,
http.MethodGet,
SlackGetPermalinkPath,
reqHeader,
nil,
qParams,
)
if err != nil {
return "", fmt.Errorf("get message permalink: %w", err)
}
if permalinkRes.StatusCode != http.StatusOK {
return "", fmt.Errorf(
"get message permalink: status code %d, res body: %s",
permalinkRes.StatusCode,
string(permalinkResBodyByte),
)
}
var permalinkResBody map[string]any
if err := json.Unmarshal(permalinkResBodyByte, &permalinkResBody); err != nil {
return "", fmt.Errorf("unmarshal permalink res body: %w", err)
}
return permalinkResBody["permalink"].(string), nil
}