This repository has been archived by the owner on Jun 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbot.go
112 lines (95 loc) · 2.03 KB
/
bot.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
package bobo
import (
"errors"
"os"
"os/signal"
"syscall"
"github.com/eure/bobo/engine"
"github.com/eure/bobo/errorcode"
"github.com/eure/bobo/log"
)
// Bot is core struct for a bot.
type Bot struct {
logger log.Logger
engine engine.Engine
// flags
status bool
signal chan os.Signal
}
// NewBot returns initialized Bot.
func NewBot() (*Bot, error) {
return NewBotWithConfig(Config{})
}
// NewBot returns initialized Bot from Config.
func NewBotWithConfig(conf Config) (*Bot, error) {
if conf.CommandSet == nil {
return nil, errors.New("You must set CommandSet for bot")
}
e := conf.Engine
if e == nil {
return nil, errors.New("You must set an engine for bot platform")
}
err := e.Init(conf)
if err != nil {
return nil, err
}
bot := &Bot{
engine: e,
logger: conf.GetLogger(),
status: true,
signal: make(chan os.Signal, 1),
}
go bot.catchSignal()
return bot, nil
}
// Run starts to run engine.
func (b *Bot) Run() (errCode int) {
return b.engine.Run()
}
// SetStatus sets active status.
// if it's false, bot does not react to any message from a user.
func (b *Bot) SetStatus(f bool) {
b.status = f
}
// LogInfo logs info level log.
func (b Bot) LogInfo(typ, msg string, v ...interface{}) {
b.logger.Infof(typ, msg, v...)
}
// catchSignal handles OS signals.
func (b *Bot) catchSignal() {
signal.Notify(b.signal,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
for {
s := <-b.signal
switch s {
case syscall.SIGHUP:
b.LogInfo("catchSignal", "syscall.SIGHUP")
return
case syscall.SIGINT:
b.LogInfo("catchSignal", "syscall.SIGINT")
b.exit()
return
case syscall.SIGTERM:
b.LogInfo("catchSignal", "syscall.SIGTERM")
b.exit()
return
case syscall.SIGQUIT:
b.LogInfo("catchSignal", "syscall.SIGQUIT")
b.exit()
return
}
}
}
// func (b *Bot) reload() {
// b.LogInfo("reload", "reloading...")
// b.engine.Reload()
// signal.Stop(b.signal)
// }
func (b *Bot) exit() {
b.LogInfo("exit", "closing...")
signal.Stop(b.signal)
b.engine.Close(errorcode.Exit)
}