-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.go
90 lines (77 loc) · 2.21 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
/*
Package main provides an example that uses sarah.CurrentStatus() to get current go-sarah and its belonging Bot's status via HTTP server.
In this example two bots, slack and nullBot, are registered to go-sarah and become subject to supervise.
See handler.go for Runner.Status() usage.
*/
package main
import (
"context"
"flag"
"fmt"
"github.com/oklahomer/go-sarah/v3"
"github.com/oklahomer/go-sarah/v3/log"
"github.com/oklahomer/go-sarah/v3/slack"
"github.com/oklahomer/go-sarah/v3/workers"
"os"
"os/signal"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
// Parse and check command line flags
var path = flag.String("config", "", "path to application configuration file.")
flag.Parse()
if *path == "" {
panic("./path/to/executable -config=/path/to/config/app.yml")
}
// Initialize config with given file content
cfg, err := readConfig(*path)
if err != nil {
panic(err)
}
// Setup a bot
nullBot := &nullBot{}
sarah.RegisterBot(nullBot)
// Setup another bot
slackBot, err := setupSlackBot(cfg)
if err != nil {
panic(err)
}
sarah.RegisterBot(slackBot)
// Setup worker
workerReporter := &workerStats{}
reporterOpt := workers.WithReporter(workerReporter)
worker, err := workers.Run(ctx, cfg.Worker, reporterOpt)
if err != nil {
panic(err)
}
sarah.RegisterWorker(worker)
// Setup a Runner to run and supervise above bots
err = sarah.Run(ctx, cfg.Runner)
if err != nil {
panic(err)
}
// Run HTTP server that reports current status
server := newServer(workerReporter)
go server.Run(ctx)
// Wait til signal reception
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
// Stop
log.Info("Stopping due to signal reception.")
cancel()
time.Sleep(1 * time.Second) // Wait a bit til things finish
}
func setupSlackBot(cfg *config) (sarah.Bot, error) {
storage := sarah.NewUserContextStorage(cfg.ContextCache)
slackAdapter, err := slack.NewAdapter(cfg.Slack)
if err != nil {
return nil, fmt.Errorf("failed to initialize Slack adapter: %w", err)
}
slackBot, err := sarah.NewBot(slackAdapter, sarah.BotWithStorage(storage))
if err != nil {
return nil, fmt.Errorf("failed to initialize Bot with given Slack adapter: %w", err)
}
return slackBot, nil
}