-
Notifications
You must be signed in to change notification settings - Fork 17
/
glossary.go
79 lines (62 loc) · 1.81 KB
/
glossary.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
// Package glossary provides some common terms that might be handy for a Gopher
// to know.
package glossary
import (
"fmt"
"strings"
"github.com/gobridge/gopherbot/handler"
"github.com/gobridge/gopherbot/workqueue"
)
// Prefix is the prefix that's intended to be used by the handler.
const Prefix = "define "
// Terms represents the glossary.
type Terms struct {
entries map[string][]string
aliases map[string]string
prefix string
}
// New generates a new set of glossary terms, from those it returns Terms.
func New(prefix string) Terms {
t := &Terms{
entries: make(map[string][]string),
aliases: make(map[string]string),
prefix: prefix,
}
for _, tfn := range terms {
tfn(t)
}
return *t
}
// DefineHandler satisfiees handler.MessageActionFn. It handles finding definitions for specific terms.
func (t Terms) DefineHandler(ctx workqueue.Context, m handler.Messenger, r handler.Responder) error {
if !m.BotMentioned() {
return nil
}
term := m.Text()[len(t.prefix):]
// this probably isn't possible with how Slack sends messages
// but let's have it just in case...
if len(term) == 0 {
return r.RespondTo(ctx, "You need to specify a term to define")
}
lterm := strings.ToLower(term)
lt := lterm
if lterm == "define" {
return r.RespondTo(ctx, `:notsureif:`)
}
if v, ok := t.aliases[lterm]; ok {
lt = v
}
d, ok := t.entries[lt]
if !ok {
msg := "I'm sorry, I don't have a definition for that.\n\nPlease consider defining that term here and opening a PR: <https://github.com/gobridge/gopherbot/blob/master/glossary/terms.go#L5>"
return r.RespondTo(ctx, msg)
}
ds := strings.Join(d, "\n")
var msg string
if lt != lterm { // alias was used
msg = fmt.Sprintf("`%s`, or `%s`, is %s", lt, lterm, ds)
} else {
msg = fmt.Sprintf("`%s` is %s", lt, ds)
}
return r.RespondMentions(ctx, msg)
}