-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathslack_webhook.go
91 lines (73 loc) · 2.31 KB
/
slack_webhook.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
package main
import (
"encoding/json"
"fmt"
"github.com/nlopes/slack"
"github.com/nlopes/slack/slackevents"
)
// SlackWebhook represents Slack webhook
type SlackWebhook struct {
slackOAuthAccessToken string
gitLabURLParserParams *GitLabURLParserParams
}
// NewSlackWebhook create new SlackWebhook instance
func NewSlackWebhook(slackOAuthAccessToken string, gitLabURLParserParams *GitLabURLParserParams) *SlackWebhook {
return &SlackWebhook{slackOAuthAccessToken: slackOAuthAccessToken, gitLabURLParserParams: gitLabURLParserParams}
}
// Request handles Slack event
func (s *SlackWebhook) Request(body string, verifyToken bool) (string, error) {
option := slackevents.OptionNoVerifyToken()
if verifyToken {
option = slackevents.OptionVerifyToken(&slackevents.TokenComparator{VerificationToken: s.slackOAuthAccessToken})
}
eventsAPIEvent, err := slackevents.ParseEvent(json.RawMessage(body), option)
if err != nil {
return "Failed: slackevents.ParseEvent", err
}
switch eventsAPIEvent.Type {
case slackevents.URLVerification:
var r *slackevents.ChallengeResponse
err := json.Unmarshal([]byte(body), &r)
if err != nil {
return "Failed: json.Unmarshal", err
}
return r.Challenge, nil
case slackevents.CallbackEvent:
p, err := NewGitlabURLParser(s.gitLabURLParserParams)
if err != nil {
return "Failed: NewGitlabURLParser", err
}
innerEvent := eventsAPIEvent.InnerEvent
switch ev := innerEvent.Data.(type) {
case *slackevents.LinkSharedEvent:
unfurls := map[string]slack.Attachment{}
for _, link := range ev.Links {
page, err := p.FetchURL(link.URL)
if err != nil {
return "Failed: FetchURL", err
}
if page == nil {
continue
}
unfurls[link.URL] = slack.Attachment{
Title: page.Title,
TitleLink: link.URL,
AuthorName: page.AuthorName,
AuthorIcon: page.AuthorAvatarURL,
Text: page.Description,
Color: "#fc6d26", // c.f. https://brandcolors.net/b/gitlab
}
}
if len(unfurls) == 0 {
return "do nothing", nil
}
api := slack.New(s.slackOAuthAccessToken)
_, _, _, err := api.UnfurlMessage(ev.Channel, ev.MessageTimeStamp.String(), unfurls)
if err != nil {
return "Failed: UnfurlMessage", err
}
return "ok", nil
}
}
return "", fmt.Errorf("Unknown event type: %s", eventsAPIEvent.Type)
}