-
Notifications
You must be signed in to change notification settings - Fork 67
/
slack.go
115 lines (100 loc) · 2.39 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"fmt"
"log"
"strings"
"github.com/nlopes/slack"
)
const (
// action is used for slack attament action.
actionSelect = "select"
actionStart = "start"
actionCancel = "cancel"
)
type SlackListener struct {
client *slack.Client
botID string
channelID string
}
// LstenAndResponse listens slack events and response
// particular messages. It replies by slack message button.
func (s *SlackListener) ListenAndResponse() {
rtm := s.client.NewRTM()
// Start listening slack events
go rtm.ManageConnection()
// Handle slack events
for msg := range rtm.IncomingEvents {
switch ev := msg.Data.(type) {
case *slack.MessageEvent:
if err := s.handleMessageEvent(ev); err != nil {
log.Printf("[ERROR] Failed to handle message: %s", err)
}
}
}
}
// handleMesageEvent handles message events.
func (s *SlackListener) handleMessageEvent(ev *slack.MessageEvent) error {
// Only response in specific channel. Ignore else.
if ev.Channel != s.channelID {
log.Printf("%s %s", ev.Channel, ev.Msg.Text)
return nil
}
// Only response mention to bot. Ignore else.
if !strings.HasPrefix(ev.Msg.Text, fmt.Sprintf("<@%s> ", s.botID)) {
return nil
}
// Parse message
m := strings.Split(strings.TrimSpace(ev.Msg.Text), " ")[1:]
if len(m) == 0 || m[0] != "hey" {
return fmt.Errorf("invalid message")
}
// value is passed to message handler when request is approved.
attachment := slack.Attachment{
Text: "Which beer do you want? :beer:",
Color: "#f9a41b",
CallbackID: "beer",
Actions: []slack.AttachmentAction{
{
Name: actionSelect,
Type: "select",
Options: []slack.AttachmentActionOption{
{
Text: "Asahi Super Dry",
Value: "Asahi Super Dry",
},
{
Text: "Kirin Lager Beer",
Value: "Kirin Lager Beer",
},
{
Text: "Sapporo Black Label",
Value: "Sapporo Black Label",
},
{
Text: "Suntory Malts",
Value: "Suntory Malts",
},
{
Text: "Yona Yona Ale",
Value: "Yona Yona Ale",
},
},
},
{
Name: actionCancel,
Text: "Cancel",
Type: "button",
Style: "danger",
},
},
}
params := slack.PostMessageParameters{
Attachments: []slack.Attachment{
attachment,
},
}
if _, _, err := s.client.PostMessage(ev.Channel, "", params); err != nil {
return fmt.Errorf("failed to post message: %s", err)
}
return nil
}