-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
123 lines (99 loc) · 2.37 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"bufio"
"fmt"
"log"
"os"
"os/signal"
"regexp"
"syscall"
"text/template"
"github.com/slack-go/slack"
"github.com/slack-go/slack/socketmode"
)
var respTpl string = `
<@{{.User}}> {{.Response}}
{{ if .Titles }}*References:*
{{ range .Titles }}> {{.}}
{{end}}{{end}}> (contexts: {{.Contexts}}, history: {{.History}})
`
var responseTemplate *template.Template
var IDPattern = regexp.MustCompile(`<@([A-Z0-9]+)>`)
func main() {
if len(os.Args) < 2 {
log.Fatal("lurch requires at least one argument of a bot configuration, e.g. `./lurch ./bots/tyk`")
}
s, err := getSettings(os.Args[1])
if err != nil {
log.Fatal(err)
}
responseTemplate = template.New("learn-tpl")
responseTemplate, err = responseTemplate.Parse(respTpl)
if err != nil {
log.Fatal(err)
}
lurch := &LurchBot{}
lurch.Init(s)
err = StartBot(lurch)
if err != nil {
log.Fatal(err)
}
}
func StartBot(lurch *LurchBot) error {
appToken := os.Getenv("SLACK_APP_TOKEN")
botToken := os.Getenv("SLACK_BOT_TOKEN")
if appToken == "" || botToken == "" {
log.Fatal("SLACK_APP_TOKEN and SLACK_BOT_TOKEN must be set")
}
api := slack.New(
botToken,
slack.OptionDebug(false),
slack.OptionLog(log.New(os.Stdout, "api: ", log.Lshortfile|log.LstdFlags)),
slack.OptionAppLevelToken(appToken),
)
client := socketmode.New(
api,
socketmode.OptionDebug(false),
socketmode.OptionLog(log.New(os.Stdout, "socketmode: ", log.Lshortfile|log.LstdFlags)),
)
lurch.SlackClient = client
if len(os.Args) == 3 {
if os.Args[2] == "chat" {
handleChatinterface(lurch)
return nil
}
}
var gracefulStop = make(chan os.Signal)
signal.Notify(gracefulStop, syscall.SIGTERM)
signal.Notify(gracefulStop, syscall.SIGINT)
go func() {
sig := <-gracefulStop
fmt.Printf("caught sig: %+v\n", sig)
fmt.Println("marking bot as offline")
err := lurch.SlackClient.SetUserPresence("away")
if err != nil {
log.Println(err)
}
os.Exit(0)
}()
go handleEvents(client, lurch)
err := client.Run()
if err != nil {
return err
}
return nil
}
func handleChatinterface(lurch *LurchBot) {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("\nInput: ")
text, _ := reader.ReadString('\n')
response, err := lurch.Chat("User", text)
if err != nil {
log.Printf("failed to call chat: %v", err)
response = err.Error()
}
// Show the response
fmt.Printf("\n" + response + "\n\n")
}
}