forked from go-chat-bot/bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.go
More file actions
168 lines (142 loc) · 3.76 KB
/
Copy pathbot.go
File metadata and controls
168 lines (142 loc) · 3.76 KB
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// Package bot provides a simple to use IRC, Slack and Telegram bot
package bot
import (
"errors"
"log"
"math/rand"
"time"
"github.com/robfig/cron"
)
const (
// CmdPrefix is the prefix used to identify a command.
// !hello would be identified as a command
CmdPrefix = "!"
// MsgBuffer is the max number of messages which can be buffered
// while waiting to flush them to the chat service.
MsgBuffer = 100
)
// Bot handles the bot instance
type Bot struct {
handlers *Handlers
cron *cron.Cron
disabledCmds []string
msgsToSend chan responseMessage
done chan struct{}
}
type responseMessage struct {
target, message string
sender *User
}
// ResponseHandler must be implemented by the protocol to handle the bot responses
type ResponseHandler func(target, message string, sender *User)
// ErrorHandler will be called when an error happens
type ErrorHandler func(msg string, err error)
// Handlers that must be registered to receive callbacks from the bot
type Handlers struct {
Response ResponseHandler
Errored ErrorHandler
}
func logErrorHandler(msg string, err error) {
log.Printf("%s: %s", msg, err.Error())
}
// New configures a new bot instance
func New(h *Handlers) *Bot {
if h.Errored == nil {
h.Errored = logErrorHandler
}
b := &Bot{
handlers: h,
cron: cron.New(),
msgsToSend: make(chan responseMessage, MsgBuffer),
done: make(chan struct{}),
}
// Launch the background goroutine that isolates the possibly non-threadsafe
// message sending logic of the underlying transport layer.
go b.processMessages()
b.startPeriodicCommands()
return b
}
func (b *Bot) startPeriodicCommands() {
for _, config := range periodicCommands {
func(b *Bot, config PeriodicConfig) {
b.cron.AddFunc(config.CronSpec, func() {
for _, channel := range config.Channels {
message, err := config.CmdFunc(channel)
if err != nil {
b.errored("Periodic command failed ", err)
} else if message != "" {
b.SendMessage(channel, message, nil)
}
}
})
}(b, config)
}
if len(b.cron.Entries()) > 0 {
b.cron.Start()
}
}
// MessageReceived must be called by the protocol upon receiving a message
func (b *Bot) MessageReceived(channel *ChannelData, message *Message, sender *User) {
command, err := parse(message.Text, channel, sender)
if err != nil {
b.SendMessage(channel.Channel, err.Error(), sender)
return
}
if command == nil {
b.executePassiveCommands(&PassiveCmd{
Raw: message.Text,
MessageData: message,
Channel: channel.Channel,
ChannelData: channel,
User: sender,
})
return
}
if b.isDisabled(command.Command) {
return
}
switch command.Command {
case helpCommand:
b.help(command)
default:
b.handleCmd(command)
}
}
// SendMessage queues a message for a target recipient, optionally from a particular sender.
func (b *Bot) SendMessage(target string, message string, sender *User) {
message = b.executeFilterCommands(&FilterCmd{
Target: target,
Message: message,
User: sender})
select {
case b.msgsToSend <- responseMessage{target, message, sender}:
default:
b.errored("Failed to queue message to send.", errors.New("Too busy"))
}
}
func (b *Bot) sendResponse(target, message string, sender *User) {
b.handlers.Response(target, message, sender)
}
func (b *Bot) errored(msg string, err error) {
if b.handlers.Errored != nil {
b.handlers.Errored(msg, err)
}
}
func (b *Bot) processMessages() {
for {
select {
case msg := <-b.msgsToSend:
b.sendResponse(msg.target, msg.message, msg.sender)
case <-b.done:
return
}
}
}
// Close will shut down the message sending capabilities of this bot. Call
// this when you are done using the bot.
func (b *Bot) Close() {
close(b.done)
}
func init() {
rand.Seed(time.Now().UnixNano())
}