forked from mi-lee/echobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathechobot.go
340 lines (295 loc) · 9.05 KB
/
echobot.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"os"
"strings"
"time"
"github.com/nlopes/slack"
)
// Config file for slack api token and bot token
const (
configJson = "/config/config.dev.json"
MSG_LIMIT = 950
)
// Data variables used throughout the package
// userMessages: map of user messages
// userIDs: map of userids that is generated by slack for its workspace users
// slackChannelIDS: slice of channel ids generated by slack for its workspace channels
// usernames: slice of usernames
// conf: the Config struct
var (
userMessages = make(map[string][]Message)
userIDs = make(map[string]string)
slackChannelIDs []string
usernames []string
conf Config
)
// Config struct, holds your slack API tokens
type Config struct {
//TODO: don't use all caps in Go names. goLint said so
BOT_TOKEN string
API_TOKEN string
}
// UserResponse struct for JSON encoding and decoding
type UserResponse struct {
OK bool `json:"ok"`
Members []Member `json:"members"`
}
// Channel response struct for JSON encoding and decoding
type ChannelResponse struct {
OK bool `json:"ok"`
Channels []Channel `json:"channels"`
}
// Channel struct holds data about the channel
type Channel struct {
Id string `json:"id"`
Name string `json:"name"`
Created int `json:"created"`
IsArchived bool `json:"is_archived"`
Creator string `json:"creator"`
}
// Member type struct includes metadata about the user
type Member struct {
ID string `json:"id"`
TeamID string `json:"team_id"`
Name string `json:"name"`
Color string `json:"color"`
RealName string `json:"real_name"`
Profile Profile
}
// Profile type struct for the user's data displayed on slack
type Profile struct {
RealName string `json:"real_name"`
DisplayName string `json:"display_name"`
StatusText string `json:"status_text"`
StatusEmoji string `json:"status_emoji"`
ImageOriginal string `json:"image_original"`
Email string `json:"email"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
}
// HistoryResponse struct for all the channel history messages
type HistoryResponse struct {
Ok bool `json:"ok"`
Messages []Message `json:"messages"`
HasMore bool `json:"has_more"`
IsLimited bool `json:"is_limited"`
}
// Message type struct representing the message json payload incoming from slack
type Message struct {
Type string `json:"type"`
Subtype string `json:"subtype"`
User string `json:"user"`
Text string `json:"text"`
ClientMsgId string `json:"client_msg_Id"`
Ts string `json:"ts"`
Reactions []Reaction `json:"reactions"`
File File `json:"file"`
}
// Reaction type struct representing the reaction payload coming from slack
type Reaction struct {
Name string `json:"name"`
Users []string `json:"users"`
Count int `json:"count"`
}
// File struct
type File struct {
URLPrivate string `json:"url_private"`
}
// GenericResponse interface, with the filter method
type GenericResponse interface {
filter(word string)
}
// Init function for initialization of the bot
// Gets config params
// Gets slice of users
// Set user messages and write to file
func init() {
getConfig()
getUsers()
setUserMessages()
}
// Call the slack api to list all users in a slack team
// Check if the getResponse got error
// Set userIDs to actual names of the user in the slack team
func getUsers() {
userResp := UserResponse{}
userEndpoint := fmt.Sprintf("https://slack.com/api/users.list?token=%s&pretty=1", conf.API_TOKEN)
getResponse(userEndpoint, &userResp)
err := writeToFile("users", &userResp)
check(err)
setUserIDs(&userResp)
}
// Returns a users ID from the inputted user's name
func getUserIDs(name string) (userID string) {
return userIDs[name]
}
// Calls the slack api to get list of all channels in the team and appends to the slackChannelIDs slice
// returns slice of slackChannelIDs
func getChannels() []string {
channelResp := ChannelResponse{}
channelEndpoint := fmt.Sprintf("https://slack.com/api/channels.list?token=%s&pretty=1", conf.API_TOKEN)
getResponse(channelEndpoint, &channelResp)
err := writeToFile("channels", &channelResp)
check(err)
if channelResp.OK {
for _, c := range channelResp.Channels {
slackChannelIDs = append(slackChannelIDs, c.Id)
}
}
return slackChannelIDs
}
// Get the history of messages and events from a slack channel
// Clean the payload for messages that are calling echobot
func getChannelHistory(chanID string, h *HistoryResponse) {
histEndpoint := fmt.Sprintf("https://slack.com/api/channels.history?token=%s&channel=%s&count=%d&pretty=1", conf.API_TOKEN, chanID, MSG_LIMIT)
getResponse(histEndpoint, h)
cleanEchobotMsg(h)
err := writeToFile(chanID, h)
check(err)
}
// Make the GET call for the urls, sets the response body to one of the response structs
func getResponse(url string, v interface{}) {
resp, err := http.Get(url)
defer resp.Body.Close()
check(err)
body, err := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(body, v)
check(err)
}
// Gets the configuration params from the current working dir + the path defined for the config file in configJson
func getConfig() {
dir, err := os.Getwd()
check(err)
c, err := ioutil.ReadFile(dir + configJson)
check(err)
err = json.Unmarshal([]byte(string(c)), &conf)
check(err)
}
// Set the usernames from the users list response
func setUserIDs(u *UserResponse) {
if u.OK {
for _, c := range u.Members {
name := strings.Split(c.Name, ".")[0]
userIDs[name] = c.ID
usernames = append(usernames, strings.ToLower(name))
}
}
}
// Filter the receiver type of HistoryResponse by the UserID and return a slice of messages by that User.
func (h *HistoryResponse) filterByUser(userID string) (result []Message) {
for _, m := range h.Messages {
if m.User == userID {
if m.Subtype == "file_share" {
m.Text = m.Text + " " + m.File.URLPrivate
}
result = append(result, m)
}
}
return result
}
// Filter the receiver type of HistoryResponse by a string word
func (h *HistoryResponse) filter(word string) {
for i, m := range h.Messages {
if strings.Contains(m.Text, word) {
num := i + 1
if len(h.Messages) >= num {
num = i
}
h.Messages = append(h.Messages[:i], h.Messages[num:]...)
}
}
}
// Write supplied string data type to file
func writeToFile(filename string, v interface{}) (err error) {
str, err := json.MarshalIndent(v, "", " ")
check(err)
dir, err := os.Getwd()
check(err)
file := fmt.Sprintf("%s/data/%s.json", dir, filename)
err = ioutil.WriteFile(file, str, 0644)
check(err)
return err
}
// Filter out echobot messages from the channel history response
func cleanEchobotMsg(v GenericResponse) {
v.filter(getUserIDs("echobot"))
}
// Gets the channel history messages sort by users and write to file:
// userIDs, userMessages and slackChannelIDs
func setUserMessages() {
chanIDs := getChannels()
for _, cID := range chanIDs {
histResp := HistoryResponse{}
getChannelHistory(cID, &histResp)
for _, username := range usernames {
uid := getUserIDs(username)
result := histResp.filterByUser(uid)
userMessages[username] = append(result, userMessages[username]...)
}
}
writeToFile("userIDs", userIDs)
writeToFile("userMessages", userMessages)
writeToFile("slackChannelIDs", slackChannelIDs)
}
// Responds back to Slack Channel, grabs the name of user sent from the channel
// Grab a random message from the slic of userMessages for that user
// Send the message back to the slack channel
func respond(rtm *slack.RTM, msg *slack.MessageEvent, prefix string) {
text := msg.Text
text = strings.TrimPrefix(text, prefix)
text = strings.TrimSpace(text)
text = strings.ToLower(text)
if userMessages[text] != nil {
for i := 0; i < 3; i++ {
length := len(userMessages[text])
responseIndex := rand.Intn(length)
str := strings.Split(userMessages[text][responseIndex].Text, " ")
userMessages[text] = append(userMessages[text][:responseIndex], userMessages[text][responseIndex+1:]...)
response := strings.Join(str, " ")
rtm.SendMessage(rtm.NewOutgoingMessage(response, msg.Channel))
time.Sleep(time.Duration(1) * time.Second)
}
}
}
func main() {
api := slack.New(conf.BOT_TOKEN)
rtm := api.NewRTM()
go rtm.ManageConnection()
// Label to break out of the loop when err
Loop:
for {
select {
case msg := <-rtm.IncomingEvents:
fmt.Print("-- Event Received: ")
switch ev := msg.Data.(type) {
case *slack.ConnectedEvent:
fmt.Println("-- Connection counter:", ev.ConnectionCount)
case *slack.MessageEvent:
//fmt.Printf("-- Message: %v\n", ev)
info := rtm.GetInfo()
prefix := fmt.Sprintf("<@%s> ", info.User.ID)
if ev.User != info.User.ID && strings.HasPrefix(ev.Text, prefix) {
respond(rtm, ev, prefix)
}
case *slack.RTMError:
fmt.Printf("-- Error: %s\n", ev.Error())
case *slack.InvalidAuthEvent:
fmt.Println("-- Invalid credentials")
break Loop
default:
// Take no action
}
}
}
}
func check(e error) {
if e != nil {
fmt.Printf("-- e = %v \n", e)
panic(e)
}
}