-
Notifications
You must be signed in to change notification settings - Fork 0
/
slack.go
344 lines (301 loc) · 9.24 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
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
341
342
343
344
package main
import (
"errors"
"fmt"
"html/template"
"log"
"os"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/slack-go/slack"
"github.com/slack-go/slack/socketmode"
"github.com/gomarkdown/markdown"
"github.com/microcosm-cc/bluemonday"
)
const (
// Callback ID
CSPUpdateStatusPage = "csp_update_status_page"
CSPSetOK = "csp_set_ok"
CSPSetWarn = "csp_set_warn"
CSPSetError = "csp_set_errteamID"
CSPCancel = "csp_cancel"
CSPPin = "pin"
CSPForward = "forward"
)
type CSPSlack struct {
slackAPI *slack.Client
slackSocket *socketmode.Client
channelHistory []slack.Message
shouldUpdate bool
page CSPPage
}
func NewCSPSlack() (app CSPSlack, err error) {
app.slackAPI = slack.New(config.SlackAccessToken, slack.OptionAppLevelToken(config.SlackAppToken))
app.slackSocket = socketmode.New(app.slackAPI,
socketmode.OptionLog(log.New(os.Stdout, "socketmode: ", log.Lshortfile|log.LstdFlags)),
)
// Get the channel history
app.getChannelHistory()
if err != nil {
log.Fatal(err)
}
// Get some deets we'll need from the slack API
authTestResponse, err := app.slackAPI.AuthTest()
config.SlackBotID = authTestResponse.UserID
// Initialize the actual data we need for the status page
err = app.BuildStatusPage()
if err != nil {
log.Fatal(err)
}
return app, nil
}
// Nuke the old slices and re-build them
func (app *CSPSlack) BuildStatusPage() (err error) {
log.Println("Building Status Page...")
app.page.updates = make([]StatusUpdate, 0)
app.page.pinnedUpdates = make([]StatusUpdate, 0)
for _, message := range app.channelHistory {
botID := fmt.Sprintf("<@%s>", config.SlackBotID)
// Ignore messages that don't mention us. Also, ignore messages that
// mention us but are empty!
if !strings.Contains(message.Text, botID) || message.Text == botID {
continue
}
msgUser, err := app.slackSocket.GetUserInfo(message.User)
if err != nil {
log.Println(err)
return err
}
realName := msgUser.RealName
var update StatusUpdate
// Disgusting dependency chain to parse Mrkdwn to HTML
noBots := strings.Replace(message.Text, botID, "", -1)
md := mrkdwnToMarkdown(noBots)
maybeUnsafeHTML := markdown.ToHTML([]byte(md), nil, nil)
html := bluemonday.UGCPolicy().SanitizeBytes(maybeUnsafeHTML)
update.HTML = template.HTML(html)
update.SentBy = realName
update.TimeStamp = slackTSToHumanTime(message.Timestamp)
update.BackgroundClass = ""
update.IconFilename = ""
for _, reaction := range message.Reactions {
// Only take action on our reactions
if botReaction := stringInSlice(reaction.Users, config.SlackBotID); !botReaction {
continue
}
// Use the first reaction sent by the bot that we find
switch reaction.Name {
case config.StatusOKEmoji:
update.BackgroundClass = "list-group-item-success"
update.IconFilename = "checkmark.svg"
case config.StatusWarnEmoji:
update.BackgroundClass = "list-group-item-warning"
update.IconFilename = "warning.svg"
case config.StatusErrorEmoji:
update.BackgroundClass = "list-group-item-danger"
update.IconFilename = "error.svg"
}
}
if len(message.PinnedTo) > 0 {
app.page.pinnedUpdates = append(app.page.pinnedUpdates, update)
} else {
app.page.updates = append(app.page.updates, update)
}
}
return nil
}
// Pass-Thru the interface to the Page object
func (app *CSPSlack) StatusPage(gin *gin.Context) {
app.page.statusPage(gin)
}
func (app *CSPSlack) SendReminders(now bool) error {
fmt.Println("Sending unpin reminders...")
var pinnedMessageLinks []ReminderInfo
for _, message := range app.channelHistory {
if len(message.PinnedTo) > 0 {
ts := slackTSToHumanTime(message.Timestamp)
status := GetPinnedMessageStatus(message.Reactions)
// Don't bother if the message hasn't been up longer than a day
t, err := time.Parse("2006-01-02 15:04:05 MST", ts)
if err == nil {
if time.Since(t) < 24*time.Hour && now == false {
fmt.Println("Message not pinned for long enough. Ignoring.")
continue
}
}
// Grab permalink to send final reminder message.
permalink, err := app.slackSocket.GetPermalink(&slack.PermalinkParameters{
Channel: config.SlackStatusChannelID,
Ts: message.Timestamp,
})
if err != nil {
return err
}
pinnedMessageLinks = append(pinnedMessageLinks, ReminderInfo{message.User, permalink, ts, status})
fmt.Println("Found message.")
}
}
if len(pinnedMessageLinks) == 0 {
fmt.Println("No messages pinned.")
return nil
}
// Send summary message
summaryMessage := fmt.Sprintln("Hello, Admins.\nThe following messages are currently pinned.")
for _, m := range pinnedMessageLinks {
var parsedStatus string
if m.status == "" {
parsedStatus = "•"
} else {
parsedStatus = fmt.Sprintf(":%s:", m.status)
}
summaryMessage += fmt.Sprintf("%s <@%s> <%s|Since %s>\n\n", parsedStatus, m.userID, m.link, m.ts)
}
summaryMessage += fmt.Sprintf("It might be time to unpin them if they are no longer relevant.")
_, _, err := app.slackSocket.PostMessage(
config.SlackStatusChannelID,
slack.MsgOptionText(summaryMessage, false),
)
if err != nil {
return err
}
fmt.Println("success.")
return nil
}
func (app *CSPSlack) Run() {
go func() {
for evt := range app.slackSocket.Events {
e := CSPSlackEvtHandler{app, evt}
switch evt.Type {
case socketmode.EventTypeConnecting:
fmt.Println("Connecting to Slack with Socket Mode...")
case socketmode.EventTypeConnectionError:
fmt.Println("Connection failed. Retrying later...")
case socketmode.EventTypeConnected:
fmt.Println("Connected to Slack with Socket Mode.")
case socketmode.EventTypeEventsAPI:
e.handleEventAPIEvent()
case socketmode.EventTypeInteractive:
e.handleInteractiveEvent()
}
// If necessary, sync our cached Slack messages
// and re-build the page history
if app.shouldUpdate {
var err error
err = app.getChannelHistory()
if err != nil {
log.Println(err.Error())
}
err = app.BuildStatusPage()
if err != nil {
log.Println(err.Error())
}
app.shouldUpdate = false
}
}
}()
app.slackSocket.Run()
}
// Utility functions
// ResolveChannelName retrieves the human-readable channel name from the channel ID.
func (app *CSPSlack) resolveChannelName(channelID string) (string, error) {
info, err := app.slackSocket.GetConversationInfo(&slack.GetConversationInfoInput{
ChannelID: channelID,
IncludeLocale: false,
IncludeNumMembers: false,
})
if err != nil {
return "", err
}
return info.Name, nil
}
func (app *CSPSlack) getThreadConversation(channelID string, threadTs string) (conversation []slack.Message, err error) {
// Get the conversation history
params := slack.GetConversationRepliesParameters{
ChannelID: channelID,
Timestamp: threadTs,
}
conversation, _, _, err = app.slackAPI.GetConversationReplies(¶ms)
if err != nil {
return conversation, err
}
return conversation, nil
}
func (app *CSPSlack) getChannelHistory() (err error) {
log.Println("Fetching channel history...")
limit, _ := strconv.Atoi(config.SlackTruncation)
params := slack.GetConversationHistoryParameters{
ChannelID: config.SlackStatusChannelID,
Oldest: "0", // Retrieve messages from the beginning of time
Inclusive: true, // Include the oldest message
Limit: limit, // Only get 100 messages
}
var history *slack.GetConversationHistoryResponse
history, err = app.slackSocket.GetConversationHistory(¶ms)
app.channelHistory = history.Messages
return err
}
func (app *CSPSlack) getSingleMessage(channelID string, oldest string) (message slack.Message, err error) {
log.Println("Fetching channel history...")
params := slack.GetConversationHistoryParameters{
ChannelID: channelID,
Oldest: oldest,
Inclusive: true,
Limit: 1,
}
var history *slack.GetConversationHistoryResponse
history, err = app.slackSocket.GetConversationHistory(¶ms)
if err != nil {
return message, err
}
if len(history.Messages) == 0 {
return message, errors.New("No messages retrieved.")
}
return history.Messages[0], err
}
func (app *CSPSlack) isBotMentioned(timestamp string) (isMentioned bool, err error) {
history, err := app.slackSocket.GetConversationHistory(
&slack.GetConversationHistoryParameters{
ChannelID: config.SlackStatusChannelID,
Inclusive: true,
Latest: timestamp,
Oldest: timestamp,
Limit: 1,
},
)
if err != nil {
return false, err
}
if len(history.Messages) > 0 {
return strings.Contains(history.Messages[0].Text, config.SlackBotID), nil
}
return false, err
}
func (app *CSPSlack) clearReactions(timestamp string, focusReactions []string) error {
ref := slack.ItemRef{
Channel: config.SlackStatusChannelID,
Timestamp: timestamp,
}
reactions, err := app.slackSocket.GetReactions(ref, slack.NewGetReactionsParameters())
if err != nil {
return err
}
if focusReactions == nil {
for _, itemReaction := range reactions {
err := app.slackSocket.RemoveReaction(itemReaction.Name, ref)
if err != nil && err.Error() != "no_reaction" {
return err
}
}
} else {
// No, I am not proud of this at all.
for _, itemReaction := range focusReactions {
err := app.slackSocket.RemoveReaction(itemReaction, ref)
if err != nil && err.Error() != "no_reaction" {
return err
}
}
}
return nil
}