-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslack.go
99 lines (83 loc) · 2.55 KB
/
slack.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
package main
import (
"fmt"
"log"
"regexp"
"strings"
"github.com/nlopes/slack"
)
type SlackListener struct {
client *slack.Client
botID string
}
func (s *SlackListener) ListenAndResponse() {
// Start listening slack events
rtm := s.client.NewRTM()
go rtm.ManageConnection()
// Handle slack events
for msg := range rtm.IncomingEvents {
fmt.Println("Event Reveived: ")
switch ev := msg.Data.(type) {
case *slack.MessageEvent:
if err := s.handleMessageEvent(ev); err != nil {
log.Printf("[ERROR] Failed to handle message: %s", err)
}
log.Print("[INFO] call")
}
}
}
func (s *SlackListener) handleMessageEvent(ev *slack.MessageEvent) error {
// Only response mention to bot. Ignore else.
log.Print(ev.Msg.Text)
if !strings.HasPrefix(ev.Msg.Text, fmt.Sprintf("<@%s> ", s.botID)) {
return nil
}
if regexp.MustCompile(`deploy staging`).MatchString(ev.Msg.Text) {
msgOpt := SelectDeployTarget("staging")
s.client.PostMessage(ev.Msg.Channel, msgOpt)
return nil
}
if regexp.MustCompile(`deploy production`).MatchString(ev.Msg.Text) {
msgOpt := SelectDeployTarget("production")
s.client.PostMessage(ev.Msg.Channel, msgOpt)
return nil
}
return nil
}
func SelectDeployTarget(phase string) slack.MsgOption {
headerText := slack.NewTextBlockObject("mrkdwn", ":jenkins:", false, false)
headerSection := slack.NewSectionBlock(headerText, nil, nil)
apiSection := createDeployButtonSection("API", API, phase)
authSection := createDeployButtonSection("Auth", Auth, phase)
closeAction := CloseButtonAction()
return slack.MsgOptionBlocks(
headerSection,
apiSection,
authSection,
closeAction,
)
}
func createDeployButtonSection(summary string, target Project, phase string) *slack.SectionBlock {
txt := slack.NewTextBlockObject("mrkdwn", "*"+summary+"*", false, false)
btnTxt := slack.NewTextBlockObject("plain_text", "Deploy", false, false)
btn := slack.NewButtonBlockElement("", fmt.Sprintf("deploy_select_%s_%s", target, phase), btnTxt)
section := slack.NewSectionBlock(txt, nil, slack.NewAccessory(btn))
return section
}
func CloseButtonAction() *slack.ActionBlock {
closeBtnTxt := slack.NewTextBlockObject("plain_text", "Close", false, false)
closeBtn := slack.NewButtonBlockElement("", "close", closeBtnTxt)
section := slack.NewActionBlock("", closeBtn)
return section
}
type Project string
const (
API Project = "API"
Auth Project = "Auth"
)
func (p Project) JenkinsJob() string {
return fmt.Sprintf("Deploy-%s", p)
}
func (p Project) GitHubRepository() string {
return fmt.Sprintf("go-%s", strings.ToLower(string(p)))
}