-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwelcomebot.go
229 lines (197 loc) · 5.88 KB
/
welcomebot.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package main
import (
"encoding/json"
"fmt"
"os"
"strings"
"github.com/nlopes/slack"
log "github.com/sirupsen/logrus"
)
type slackResponse struct {
Channel string `json:"channel"`
Raw bool `json:"raw_response"`
Response string `json:"response"`
}
type Config struct {
PublicResponses []slackResponse `json:"responses"`
DmResponses []slackResponse `json:"dmresponses"`
EphResponses []slackResponse `json:"ephresponses"`
}
var (
botId string
)
func main() {
token := os.Getenv("SLACK_TOKEN")
config := loadConfig("config.json")
api := slack.New(
token,
slack.OptionDebug(true),
)
rtm := api.NewRTM()
go rtm.ManageConnection()
// Return a slice of all channels from config.json
allChans := getChannelList(config.PublicResponses, config.DmResponses, config.EphResponses)
// Because duplicates are possible, make a new slice without duplicates
cleanSlice := removeDuplicates(allChans)
// Range over the cleaned up slice and join channels
for _, v := range cleanSlice {
_, err := api.JoinChannel(v)
if err != nil {
log.Errorf("Error joining public channel %s: %s", v, err)
}
}
Loop:
for {
select {
case msg := <-rtm.IncomingEvents:
switch ev := msg.Data.(type) {
case *slack.ConnectedEvent:
botId = ev.Info.User.ID
log.Infof("Connection counter:", ev.ConnectionCount)
case *slack.MessageEvent:
//only interested in public channels
cInfo, err := api.GetChannelInfo(ev.Channel)
if err == nil {
if ev.SubType == "channel_join" {
log.Infof("channel_join seen on channel: %s", ev.Msg.Channel)
respondToJoin(rtm, ev, cInfo.Name, config)
}
if ev.User != botId && strings.HasPrefix(ev.Text, "<@"+botId+">") {
log.Infof("message seen on public channel: %s", ev.Msg.Channel)
respondToMessage(rtm, ev, cInfo.Name, config)
}
}
case *slack.RTMError:
log.Errorf("Error: %s\n", ev.Error())
case *slack.InvalidAuthEvent:
log.Fatal("Invalid credentials")
break Loop
default:
//Take no action
}
}
}
}
func sendMessage(rtm *slack.RTM, channel string, message string, raw bool) (string, string, error) {
return rtm.PostMessage(
channel,
slack.MsgOptionText(message, !raw),
slack.MsgOptionAsUser(true),
)
}
// From https://github.com/nlopes/slack/issues/191#issuecomment-355394946
func postEphemeral(rtm *slack.RTM, channel, user, text string, raw bool) (string, error) {
return rtm.PostEphemeral(
channel,
user,
slack.MsgOptionText(text, !raw),
slack.MsgOptionAsUser(true),
)
}
func respondToMessage(rtm *slack.RTM, ev *slack.MessageEvent, name string, config Config) {
acceptedGreetings := map[string]bool{
"help": true,
}
text := ev.Msg.Text
prefix := fmt.Sprintf("<@%s> ", botId)
text = strings.TrimPrefix(text, prefix)
text = strings.TrimSpace(text)
text = strings.ToLower(text)
if acceptedGreetings[text] {
for _, publicResponse := range config.PublicResponses {
if publicResponse.Channel == name {
publicMsg := fmt.Sprintf("*Public response for this channel*:\n\n%s", publicResponse.Response)
_, _, err := sendMessage(rtm, ev.Msg.Channel, publicMsg, publicResponse.Raw)
if err != nil {
log.Warnf("Error sending message: %s", err)
}
}
}
for _, dmResponse := range config.DmResponses {
if dmResponse.Channel == name {
dmMsg := fmt.Sprintf("*DM response for this channel*:\n\n%s", dmResponse.Response)
_, _, err := sendMessage(rtm, ev.Msg.Channel, dmMsg, dmResponse.Raw)
if err != nil {
log.Warnf("Error sending message: %s", err)
}
}
}
for _, ephResponse := range config.EphResponses {
if ephResponse.Channel == name {
ephMsg := fmt.Sprintf("*Ephemeral response for this channel*:\n\n%s", ephResponse.Response)
_, _, err := sendMessage(rtm, ev.Msg.Channel, ephMsg, ephResponse.Raw)
if err != nil {
log.Warnf("Error sending message: %s", err)
}
}
}
}
}
func respondToJoin(rtm *slack.RTM, ev *slack.MessageEvent, name string, config Config) {
for _, publicResponse := range config.PublicResponses {
if publicResponse.Channel == name {
log.Infof("Sending public reply to channel %s", name)
_, _, err := sendMessage(rtm, ev.Msg.Channel, publicResponse.Response, publicResponse.Raw)
if err != nil {
log.Warnf("Error sending message: %s", err)
}
}
}
for _, dmResponse := range config.DmResponses {
if dmResponse.Channel == name {
sta, stb, channel, err := rtm.OpenIMChannel(ev.User)
if err != nil && sta && stb {
log.Warnf("Failed to open IM channel to user: %s", err)
}
log.Infof("Sending DM to user %s", ev.User)
_, _, err = sendMessage(rtm, channel, dmResponse.Response, dmResponse.Raw)
if err != nil {
log.Warnf("Error sending message: %s", err)
}
}
}
for _, ephResponse := range config.EphResponses {
if ephResponse.Channel == name {
log.Infof("Sending ephemeral reply to %s in channel %s", ev.User, name)
_, err := postEphemeral(rtm, ev.Msg.Channel, ev.User, ephResponse.Response, ephResponse.Raw)
if err != nil {
log.Warnf("Error sending message: %s", err)
}
}
}
}
func loadConfig(file string) Config {
var config Config
configFile, err := os.Open(file)
defer configFile.Close()
if err != nil {
log.Fatalf("Error opening config file %s", err.Error())
}
jsonParser := json.NewDecoder(configFile)
jsonParser.Decode(&config)
return config
}
func getChannelList(publicSlice, dmSlice, ephSlice []slackResponse) []string {
var newSlice []string
for _, v := range publicSlice {
newSlice = append(newSlice, v.Channel)
}
for _, v := range dmSlice {
newSlice = append(newSlice, v.Channel)
}
for _, v := range ephSlice {
newSlice = append(newSlice, v.Channel)
}
return newSlice
}
func removeDuplicates(channelSlice []string) []string {
k := make(map[string]bool)
slice := []string{}
for _, entry := range channelSlice {
if _, value := k[entry]; !value {
k[entry] = true
slice = append(slice, entry)
}
}
return slice
}