-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
101 lines (90 loc) · 2.07 KB
/
main.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
package main
import (
"bytes"
"fmt"
"log"
"os"
"strings"
"github.com/nlopes/slack"
)
func main() {
apiKey, exists := os.LookupEnv("API_KEY")
if !exists {
log.Fatal("can't get the api key")
}
botUser, exists := os.LookupEnv("BOT_USER")
if !exists {
log.Fatal("can't get the bot username")
}
keyword, exists := os.LookupEnv("KEY_WORD")
if !exists {
keyword = "clippy"
}
api := slack.New(apiKey)
rtm := api.NewRTM()
go rtm.ManageConnection()
for msg := range rtm.IncomingEvents {
switch t := msg.Data.(type) {
case *slack.MessageEvent:
go handleMessage(keyword, botUser, api, t)
default:
}
}
}
func sendReply(api *slack.Client, channel, botUser, message string) {
params := slack.PostMessageParameters{
Markdown: true,
Username: botUser,
UnfurlLinks: true,
}
_, _, err := api.PostMessage(channel, generateMessage(message), params)
if err != nil {
fmt.Printf("error sending reply %s", err)
}
}
func handleMessage(keyword, botUser string, api *slack.Client, message *slack.MessageEvent) {
if strings.HasPrefix(message.Text, keyword) {
go sendReply(api, message.Channel, botUser, message.Text[len(keyword):])
} else {
fmt.Printf("message text %s doesn't have %s prefix\n", message.Text, keyword)
}
}
func generateMessage(message string) string {
var lines bytes.Buffer
words := strings.Split(message, " ")
//word, words := words[0], words[1:]
for len(words) > 0 {
var word string
var line string
for len(words) > 0 && len(line)+len(words[0])+1 < 39 {
word, words = words[0], words[1:]
line = line + " " + word
}
outputLine := fmt.Sprintf(" | %s", line)
filler := 43 - len(outputLine)
for i := 0; i < filler; i++ {
outputLine = outputLine + " "
}
outputLine = outputLine + "|"
lines.WriteString(outputLine)
lines.WriteString("\n")
line = ""
}
header := `
-----------------------------------------
`
footer := ` -----------------------------------------
\
\
__
/ \
| |
@ @
| |
|| |/
|| ||
|\_/|
\___/
`
return "```\n" + header + lines.String() + footer + "\n```"
}