forked from harvesthq/notable
/
notable.go
70 lines (55 loc) · 1.7 KB
/
notable.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
package notable
import (
"fmt"
slack "github.com/harvesthq/notable/Godeps/_workspace/src/github.com/nlopes/slack"
"log"
"regexp"
"strings"
)
var targetRoom string = "general"
func Record(authorID string, category string, text string, slackToken string) {
var authorName, avatarURL string
api := slack.New(slackToken)
user, err := api.GetUserInfo(authorID)
text, category = effectiveTextAndCategory(text, category)
if err == nil {
authorName = user.Profile.RealName
avatarURL = user.Profile.Image48
} else {
fmt.Printf("Error getting author information from Slack: %s\n", err)
authorName = authorID
avatarURL = ""
}
text = strings.TrimSpace(strings.TrimPrefix(text, category))
note := Note{authorName, avatarURL, category, text}
AddNote(note)
notifyRoom(api, note)
}
func effectiveTextAndCategory(text string, category string) (string, string) {
hashtag := extractHashtag(text)
if len(hashtag) > 0 {
category = hashtag
text = strings.TrimSuffix(text, hashtag)
}
if len(category) == 0 {
category = "notable"
}
return text, strings.Trim(category, ":# ")
}
func extractHashtag(text string) string {
pattern := regexp.MustCompile(` #\w+\z`)
return pattern.FindString(text)
}
func notifyRoom(api *slack.Client, note Note) {
var attachments []slack.Attachment
avatar := slack.Attachment{Text: note.Text, Color: "good"}
heading := fmt.Sprintf("%s Announcement from %s", strings.Title(note.Category), note.Author)
params := slack.PostMessageParameters{Username: heading, IconURL: note.AvatarURL, Attachments: append(attachments, avatar)}
_, _, err := api.PostMessage(fmt.Sprintf("#%s", targetRoom), "", params)
check(err)
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}