This repository has been archived by the owner on Apr 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
80 lines (70 loc) · 1.76 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
package main
import (
"bufio"
"fmt"
"github.com/deanveloper/karman"
"github.com/deanveloper/xkcdnews"
"log"
"os"
"strings"
"time"
)
func main() {
bots := map[string]Bot{
"karman": karman.New(log.New(os.Stdout, "[Karman]", log.Ldate|log.Ltime)),
"xkcdnews": xkcdnews.New(log.New(os.Stdout, "[XKCDNews]", log.Ldate|log.Ltime)),
}
// start all bots
for _, bot := range bots {
go bot.Start()
}
// stop all bots when we stop
defer func() {
fmt.Println("Stopping bots gracefully...")
done := make(chan string)
timeout := time.After(5 * time.Second)
for key, bot := range bots {
go func(key string, bot Bot) {
bot.Stop()
done <- key
}(key, bot)
}
for i := 0; i < len(bots); i++ {
select {
case s := <-done:
bots[s] = nil
case <-timeout:
for key := range bots {
fmt.Println("Timed out:", key)
}
}
}
}()
// keep bot running until "stop" is typed
scan := bufio.NewScanner(os.Stdin)
for scan.Scan() {
input := scan.Text()
if input == "stop" {
break
}
split := strings.Split(input, " ")
bot := bots[split[0]]
if bot != nil {
cmdr, ok := bot.(Commander)
if ok {
cmdr.Command(split[1:])
} else {
fmt.Println("That bot does not take commands")
}
} else {
fmt.Println("Command not found:", split[0])
}
}
}
type Bot interface {
Start()
Stop()
}
type Commander interface {
Command(args []string)
}