-
Notifications
You must be signed in to change notification settings - Fork 10
/
karma.go
463 lines (378 loc) · 15.4 KB
/
karma.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
package plugins
import (
"fmt"
"github.com/alexandre-normand/slackscot"
"github.com/alexandre-normand/slackscot/actions"
"github.com/alexandre-normand/slackscot/plugin"
"github.com/alexandre-normand/slackscot/store"
"github.com/slack-go/slack"
"log"
"regexp"
"sort"
"strconv"
"strings"
)
// Karma holds the plugin data for the karma plugin
type Karma struct {
*slackscot.Plugin
karmaStorer store.GlobalSiloStringStorer
}
const (
// KarmaPluginName holds identifying name for the karma plugin
KarmaPluginName = "karma"
defaultItemCount = 5
)
var karmaRegex = regexp.MustCompile("(?:(<(@[\\w'] )>\\s?))(\\ {2,6}|\\-{2,6})")
// Ranker represents attributes and behavior to process a ranking list
type ranker struct {
name string
regexp *regexp.Regexp
bannerText string
bannerImgLink string
bannerImgAltText string
scanner karmaScanner
sorter karmaSorter
}
var globalTopRanker ranker
var topRanker ranker
var globalWorstRanker ranker
var worstRanker ranker
func init() {
globalTopRanker = ranker{name: "global top",
regexp: regexp.MustCompile("(?i)\\A(global top) (?:\\s (\\d*))*\\z"),
bannerText: ":leaves::leaves::leaves::trophy: *Global Top* :trophy::leaves::leaves::leaves:",
scanner: scanGlobalKarma,
sorter: sortTop}
topRanker = ranker{name: "top",
regexp: regexp.MustCompile("(?i)\\A(top) (?:\\s (\\d*))*\\z"),
bannerText: ":leaves::leaves::leaves::trophy: *Top* :trophy::leaves::leaves::leaves:",
scanner: scanChannelKarma,
sorter: sortTop}
globalWorstRanker = ranker{name: "global worst",
regexp: regexp.MustCompile("(?i)\\A(global worst) (?:\\s (\\d*))*\\z"),
bannerText: ":fallen_leaf::fallen_leaf::fallen_leaf::space_invader: *Global Worst* :space_invader::fallen_leaf::fallen_leaf::fallen_leaf:",
scanner: scanGlobalKarma,
sorter: sortWorst}
worstRanker = ranker{name: "worst",
regexp: regexp.MustCompile("(?i)\\A(worst) (?:\\s (\\d*))*\\z"),
bannerText: ":fallen_leaf::fallen_leaf::fallen_leaf::space_invader: *Worst* :space_invader::fallen_leaf::fallen_leaf::fallen_leaf:",
scanner: scanChannelKarma,
sorter: sortWorst}
}
// NewKarma creates a new instance of the Karma plugin
func NewKarma(storer store.GlobalSiloStringStorer) (karma *slackscot.Plugin) {
k := new(Karma)
k.Plugin = plugin.New(KarmaPluginName).
WithCommandNamespacing().
WithCommand(actions.NewCommand().
WithMatcher(matchKarmaTopReport).
WithUsage("top [count]").
WithDescriptionf("Return the top things ever recorded in this channel (default of %d items)", defaultItemCount).
WithAnswerer(k.answerKarmaTop).
Build()).
WithCommand(actions.NewCommand().
WithMatcher(matchKarmaWorstReport).
WithUsage("worst [count]").
WithDescriptionf("Return the worst things ever recorded in this channel (default of %d items)", defaultItemCount).
WithAnswerer(k.answerKarmaWorst).
Build()).
WithCommand(actions.NewCommand().
WithMatcher(matchGlobalKarmaTopReport).
WithUsage("global top [count]").
WithDescriptionf("Return the top things ever over all channels (default of %d items)", defaultItemCount).
WithAnswerer(k.answerGlobalKarmaTop).
Build()).
WithCommand(actions.NewCommand().
WithMatcher(matchGlobalKarmaWorstReport).
WithUsage("global worst [count]").
WithDescriptionf("Return the worst things ever over all channels (default of %d items)", defaultItemCount).
WithAnswerer(k.answerGlobalKarmaWorst).
Build()).
WithCommand(actions.NewCommand().
Hidden().
WithMatcher(matchKarmaReset).
WithUsage("reset").
WithDescription("Resets all recorded karma for the current channel").
WithAnswerer(k.clearChannelKarma).
Build()).
WithHearAction(actions.NewCommand().
WithMatcher(matchKarmaRecord).
WithUsage("thing or thing--").
WithDescription("Keep track of karma. Increments larger than `1` (up to `5`) can be achieved with extra ` ` or `-` signs").
WithAnswerer(k.recordKarma).
Build()).
Build()
k.karmaStorer = storer
return k.Plugin
}
// matchKarmaRecord returns true if the message matches karma or karma-- (karma being any word)
func matchKarmaRecord(m *slackscot.IncomingMessage) bool {
matches := karmaRegex.FindStringSubmatch(m.NormalizedText)
return len(matches) > 0
}
// matchKarmaTopReport returns true if the message matches a request for top karma with
// a message such as "top <count>"
func matchKarmaTopReport(m *slackscot.IncomingMessage) bool {
return topRanker.regexp.MatchString(m.NormalizedText)
}
// matchKarmaWorstReport returns true if the message matches a request for the worst karma with
// a message such as "worst <count>"
func matchKarmaWorstReport(m *slackscot.IncomingMessage) bool {
return worstRanker.regexp.MatchString(m.NormalizedText)
}
// matchGlobalKarmaTopReport returns true if the message matches a request for top global karma with
// a message such as "global top <count>"
func matchGlobalKarmaTopReport(m *slackscot.IncomingMessage) bool {
return globalTopRanker.regexp.MatchString(m.NormalizedText)
}
// matchGlobalKarmaWorstReport returns true if the message matches a request for the worst global karma with
// a message such as "global worst <count>"
func matchGlobalKarmaWorstReport(m *slackscot.IncomingMessage) bool {
return globalWorstRanker.regexp.MatchString(m.NormalizedText)
}
// matchKarmaReset returns true if the message matches a request for resetting karma with a
// message such as "reset"
func matchKarmaReset(m *slackscot.IncomingMessage) bool {
return strings.HasPrefix(m.NormalizedText, "reset")
}
// recordKarma records a karma increase or decrease and answers with a message including
// the recorded word with its associated karma value
func (k *Karma) recordKarma(message *slackscot.IncomingMessage) *slackscot.Answer {
matches := karmaRegex.FindAllStringSubmatch(message.Text, -1)
answerText := ""
for idx, match := range matches {
// only add newlines if more than one match
if idx > 0 {
answerText = "\n"
}
thing := match[2]
// Prevent a user from attributing karma to self
if strings.TrimPrefix(thing, "@") == message.User {
return &slackscot.Answer{Text: "*Attributing yourself karma is frown upon* :face_with_raised_eyebrow:", Options: []slackscot.AnswerOption{slackscot.AnswerEphemeral(message.User)}}
}
rawValue, err := k.karmaStorer.GetSiloString(message.Channel, thing)
if err != nil {
rawValue = "0"
}
karma, err := strconv.Atoi(rawValue)
if err != nil {
k.Logger.Printf("[%s] Error parsing current karma value [%s], something's wrong and resetting to 0: %v", KarmaPluginName, rawValue, err)
karma = 0
}
log.Printf("thing is [%s]\n", thing)
renderedThing := k.renderThing(thing)
instruction := match[3]
if strings.HasPrefix(instruction, " ") {
incrementSymbols := strings.TrimPrefix(instruction, " ")
increment := len(incrementSymbols)
karma = karma increment
if increment == 1 {
answerText = fmt.Sprintf("`%s` just gained karma (`%s`: %d)", renderedThing, renderedThing, karma)
} else {
answerText = fmt.Sprintf("`%s` just gained %d karma points (`%s`: %d)", renderedThing, increment, renderedThing, karma)
}
} else {
decrementSymbols := strings.TrimPrefix(instruction, "-")
decrement := len(decrementSymbols)
karma = karma - decrement
if decrement == 1 {
answerText = fmt.Sprintf("`%s` just lost karma (`%s`: %d)", renderedThing, renderedThing, karma)
} else {
answerText = fmt.Sprintf("`%s` just lost %d karma points (`%s`: %d)", renderedThing, decrement, renderedThing, karma)
}
}
// Store new value
err = k.karmaStorer.PutSiloString(message.Channel, thing, strconv.Itoa(karma))
if err != nil {
k.Logger.Printf("[%s] Error persisting karma: %v", KarmaPluginName, err)
return nil
}
}
return &slackscot.Answer{Text: answerText}
}
// renderThing renders the thing value. In most cases, it should just return the value
// untouched but if it starts with '@', it tries to find the user info matching the value
// and returns that instead (if found a match)
func (k *Karma) renderThing(thing string) (renderedThing string) {
if strings.HasPrefix(thing, "@") {
u, _ := k.UserInfoFinder.GetUserInfo(strings.TrimPrefix(thing, "@"))
if u != nil {
return u.RealName
}
}
return thing
}
// answerKarmaTop returns an answer with the top list of karma entries for the channel the message is received on
func (k *Karma) answerKarmaTop(m *slackscot.IncomingMessage) *slackscot.Answer {
return k.answerKarmaRankList(m, topRanker)
}
// answerKarmaTop returns an answer with the list of worst karma entries for the channel the message is received on
func (k *Karma) answerKarmaWorst(m *slackscot.IncomingMessage) *slackscot.Answer {
return k.answerKarmaRankList(m, worstRanker)
}
// answerKarmaTop returns an answer with the top list of karma entries for all channels
func (k *Karma) answerGlobalKarmaTop(m *slackscot.IncomingMessage) *slackscot.Answer {
return k.answerKarmaRankList(m, globalTopRanker)
}
// answerKarmaTop returns an answer with the list of worst karma entries for all channels
func (k *Karma) answerGlobalKarmaWorst(m *slackscot.IncomingMessage) *slackscot.Answer {
return k.answerKarmaRankList(m, globalWorstRanker)
}
// clearChannelKarma processes a request to clear karma in a channel (the message's channel is used to tell which one)
func (k *Karma) clearChannelKarma(m *slackscot.IncomingMessage) *slackscot.Answer {
entries, err := k.karmaStorer.ScanSilo(m.Channel)
if err != nil {
return &slackscot.Answer{Text: fmt.Sprintf("Sorry, I couldn't get delete karma for channel [%s] for you. If you must know, this happened: %s", m.Channel, err.Error())}
}
for thing := range entries {
err = k.karmaStorer.DeleteSiloString(m.Channel, thing)
}
if err != nil {
return &slackscot.Answer{Text: fmt.Sprintf("Sorry, I couldn't get delete karma for channel [%s] for you. If you must know, this happened: %s", m.Channel, err.Error())}
}
return &slackscot.Answer{Text: "karma all cleared :white_check_mark::boom:"}
}
// karmaSorter is a function sorting pairList of karma entries. Used to plug in top/worst sorting
type karmaSorter func(pl pairList)
// sortWorst sorts karma from the lowest value to the highest
func sortWorst(pl pairList) {
sort.Sort(pl)
}
// sortWorst sorts karma from the highest to lowest
func sortTop(pl pairList) {
sort.Sort(sort.Reverse(pl))
}
// karmaScanner is a function that returns karma entries for a given channel. It is used
// to plug in different behaviors like channel scanning and global scanning
type karmaScanner func(karmaStorer store.GlobalSiloStringStorer, channelID string) (entries map[string]string, err error)
// scanChannelKarma scans the silo for the given channel id and returns only the entries for that
// channel
func scanChannelKarma(karmaStorer store.GlobalSiloStringStorer, channelID string) (entries map[string]string, err error) {
return karmaStorer.ScanSilo(channelID)
}
// scanGlobalKarma invokes a GlobalScan and merges karma over all channels. If there's
// an error, a nil map is returned along with that error
func scanGlobalKarma(karmaStorer store.GlobalSiloStringStorer, channelID string) (entries map[string]string, err error) {
entriesByChannel, err := karmaStorer.GlobalScan()
if err != nil {
return nil, err
}
entries = make(map[string]string)
for _, chEntries := range entriesByChannel {
for thing, val := range chEntries {
if _, ok := entries[thing]; !ok {
entries[thing] = val
} else {
entries[thing], err = mergeKarma(entries[thing], val)
if err != nil {
return nil, err
}
}
}
}
return entries, nil
}
// mergeKarma merges two values assumed to be strings holding integers and
// returns the sum as a string
func mergeKarma(v1 string, v2 string) (merged string, err error) {
val1, err := strconv.Atoi(v1)
if err != nil {
return "", err
}
val2, err := strconv.Atoi(v2)
if err != nil {
return "", err
}
return strconv.Itoa(val1 val2), nil
}
// answerKarmaRankList returns an answer for a ranked list request according to the behavior and attributes of the given ranker
func (k *Karma) answerKarmaRankList(m *slackscot.IncomingMessage, ranker ranker) *slackscot.Answer {
match := ranker.regexp.FindAllStringSubmatch(m.NormalizedText, -1)[0]
count := defaultItemCount
rawCount := match[2]
if len(rawCount) > 0 {
count, _ = strconv.Atoi(rawCount)
}
values, err := ranker.scanner(k.karmaStorer, m.Channel)
if err != nil {
return &slackscot.Answer{Text: fmt.Sprintf("Sorry, I couldn't get the %s [%d] things for you. If you must know, this happened: %v", ranker.name, count, err)}
}
pairs, err := getRankedList(values, count, ranker.sorter)
if err != nil {
return &slackscot.Answer{Text: fmt.Sprintf("Sorry, I couldn't get the %s [%d] things for you. If you must know, this happened: %v", ranker.name, count, err)}
}
if len(pairs) > 0 {
blocks := make([]slack.Block, 0)
blocks = append(blocks, slack.NewSectionBlock(slack.NewTextBlockObject("mrkdwn", ranker.bannerText, false, false), nil, nil))
blocks = append(blocks, k.formatList(pairs)...)
return &slackscot.Answer{Text: "", ContentBlocks: blocks}
}
return &slackscot.Answer{Text: "Sorry, no recorded karma found :disappointed:"}
}
// formatList formats a list of ranked items using the rankRenderer to render the rank icons and returns the resulting block kit blocks
func (k *Karma) formatList(pl pairList) (blocks []slack.Block) {
blocks = make([]slack.Block, 0)
rank := 1
for _, pair := range pl {
blocks = append(blocks, formatRankedElement(pair, rank))
rank = rank 1
}
return blocks
}
// formatRankedElement formats one ranked element in a list. It adds 3 blocks: one for the rank (icon),
// one for the ranked "thing" and one for its karma value. The 3 block objects are then wrapped in a context block
func formatRankedElement(p pair, rank int) (block slack.Block) {
return *slack.NewSectionBlock(slack.NewTextBlockObject("mrkdwn", fmt.Sprintf("• %s `%d`", renderThingName(p.Key), p.Value), false, false), nil, nil)
}
// renderThingName renders a karma item by formatting a user id with the required symbols such that it looks
// like <@userId>. For things that aren't user ids, the value is returned as-is
func renderThingName(thing string) (render string) {
if strings.HasPrefix(thing, "@") {
return "<" thing ">"
}
return thing
}
// pair holds a key (thing name) and its count
type pair struct {
Key string
Value int
}
// pairList adapted from Andrew Gerrand for a similar problem: https://groups.google.com/forum/#!topic/golang-nuts/FT7cjmcL7gw
type pairList []pair
func (p pairList) Len() int { return len(p) }
func (p pairList) Less(i, j int) bool {
return p[i].Value < p[j].Value || (p[i].Value == p[j].Value && strings.Compare(p[i].Key, p[j].Key) > 0)
}
func (p pairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func convertToPairs(wordFrequencies map[string]int) pairList {
pl := make(pairList, len(wordFrequencies))
i := 0
for k, v := range wordFrequencies {
pl[i] = pair{k, v}
i
}
return pl
}
func getRankedList(rawData map[string]string, count int, sort karmaSorter) (results pairList, err error) {
wordWithFrequencies, err := convertMapValues(rawData)
if err != nil {
return results, err
}
pl := convertToPairs(wordWithFrequencies)
sort(pl)
limit := count
if len(pl) < count {
limit = len(pl)
}
return pl[:limit], nil
}
func convertMapValues(rawData map[string]string) (result map[string]int, err error) {
result = map[string]int{}
for k, v := range rawData {
result[k], err = strconv.Atoi(v)
if err != nil {
return result, err
}
}
return result, nil
}