-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
86 lines (74 loc) · 1.86 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
package main
import (
"fmt"
"log"
"os"
"os/signal"
"strings"
"time"
"github.com/boltdb/bolt"
_ "github.com/lib/pq"
"github.com/spf13/viper"
"github.com/willis7/golossary/models"
"github.com/willis7/slack"
)
type App struct {
DB *bolt.DB
}
func init() {
viper.SetConfigName("app_config")
viper.AddConfigPath(".")
if err := viper.ReadInConfig(); err != nil {
panic(fmt.Errorf("fatal error config file: %s", err))
}
}
func main() {
db, err := models.InitDB(viper.GetString("database.path"))
if err != nil {
}
defer db.Close()
app := &App{DB: db}
mux := slack.NewEventMux()
mux.Handle("message", RTMMessage(app))
token := viper.GetString("slack.token")
client := slack.NewClient(token, mux)
client.Connect()
defer client.Close()
go client.Dispatch()
sigterm := make(chan os.Signal)
signal.Notify(sigterm, os.Interrupt)
for {
select {
case <-sigterm:
log.Println("terminate signal recvd")
err := client.Shutdown()
if err != nil {
log.Println("write close:", err)
return
}
select {
case <-time.After(time.Second):
}
client.Close()
return
}
}
}
// RTMMessage is app HandlerFunc implementation which handles the "message" event
func RTMMessage(app *App) slack.Handler {
return slack.HandlerFunc(func(msg *slack.Message, c*slack.Client) {
parts := strings.Fields(msg.Text)
switch parts[1] {
case "define":
result := models.Get(app.DB, parts[2])
c.PostMessage(&slack.Message{Type: msg.Type, Channel: msg.Channel, Text: fmt.Sprintf("%s means - %s", parts[2], result)})
case "insert":
word := models.Word{Name: parts[2], Description: strings.Join(parts[3:], " ")}
models.Update(app.DB, word)
c.PostMessage(&slack.Message{Type: msg.Type, Channel: msg.Channel, Text: fmt.Sprintf("%s added ", parts[2])})
default:
msg.Text = fmt.Sprintf("sorry, that does not compute\n")
c.PostMessage(msg)
}
})
}