-
Notifications
You must be signed in to change notification settings - Fork 73
/
bot.go
503 lines (469 loc) · 12.3 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
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
package zero
import (
"encoding/json"
"hash/crc64"
"runtime/debug"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/FloatTech/ttl"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"github.com/wdvxdr1123/ZeroBot/message"
"github.com/wdvxdr1123/ZeroBot/utils/helper"
)
// Config is config of zero bot
type Config struct {
NickName []string `json:"nickname"` // 机器人名称
CommandPrefix string `json:"command_prefix"` // 触发命令
SuperUsers []int64 `json:"super_users"` // 超级用户
RingLen uint `json:"ring_len"` // 事件环长度 (默认关闭)
Latency time.Duration `json:"latency"` // 事件处理延迟 (延迟 latency 再处理事件,在 ring 模式下不可低于 1ms)
MaxProcessTime time.Duration `json:"max_process_time"` // 事件最大处理时间 (默认4min)
MarkMessage bool `json:"mark_message"` // 自动标记消息为已读
KeepAtMeMessage bool `json:"keep_at_me_message"` // 是否保留at me的原始消息
Driver []Driver `json:"-"` // 通信驱动
}
// APICallers 所有的APICaller列表, 通过self-ID映射
var APICallers callerMap
// APICaller is the interface of CallAPI
type APICaller interface {
CallAPI(request APIRequest) (APIResponse, error)
}
// Driver 与OneBot通信的驱动,使用driver.DefaultWebSocketDriver
type Driver interface {
Connect()
Listen(func([]byte, APICaller))
}
// BotConfig 运行中bot的配置,是Run函数的参数的拷贝
var BotConfig Config
var (
evring eventRing // evring 事件环
isrunning uintptr
)
func runinit(op *Config) {
if op.MaxProcessTime == 0 {
op.MaxProcessTime = time.Minute * 4
}
BotConfig = *op
if op.RingLen == 0 {
return
}
evring = newring(op.RingLen)
evring.loop(op.Latency, op.MaxProcessTime, processEventAsync)
}
func (op *Config) directlink(b []byte, c APICaller) {
go func() {
if op.Latency != 0 {
time.Sleep(op.Latency)
}
processEventAsync(b, c, op.MaxProcessTime)
}()
}
// Run 主函数初始化
func Run(op *Config) {
if !atomic.CompareAndSwapUintptr(&isrunning, 0, 1) {
log.Warnln("[bot] 已忽略重复调用的 Run")
}
runinit(op)
linkf := op.directlink
if op.RingLen != 0 {
linkf = evring.processEvent
}
for _, driver := range op.Driver {
driver.Connect()
go driver.Listen(linkf)
}
}
// RunAndBlock 主函数初始化并阻塞
//
// preblock 在所有 Driver 连接后,调用最后一个 Driver 的 Listen 阻塞前执行本函数
func RunAndBlock(op *Config, preblock func()) {
if !atomic.CompareAndSwapUintptr(&isrunning, 0, 1) {
log.Warnln("[bot] 已忽略重复调用的 RunAndBlock")
}
runinit(op)
linkf := op.directlink
if op.RingLen != 0 {
linkf = evring.processEvent
}
switch len(op.Driver) {
case 0:
return
case 1:
op.Driver[0].Connect()
if preblock != nil {
preblock()
}
op.Driver[0].Listen(linkf)
default:
i := 0
for ; i < len(op.Driver)-1; i++ {
op.Driver[i].Connect()
go op.Driver[i].Listen(linkf)
}
op.Driver[i].Connect()
if preblock != nil {
preblock()
}
op.Driver[i].Listen(linkf)
}
}
var (
triggeredMessages = ttl.NewCache[int64, []message.ID](time.Minute * 5)
triggeredMessagesMu = sync.Mutex{}
)
type messageLogger struct {
msgid message.ID
caller APICaller
}
// CallAPI 记录被触发的回复消息
func (m *messageLogger) CallAPI(request APIRequest) (rsp APIResponse, err error) {
rsp, err = m.caller.CallAPI(request)
if err != nil {
return
}
id := rsp.Data.Get("message_id")
if id.Exists() {
mid := m.msgid.ID()
triggeredMessagesMu.Lock()
defer triggeredMessagesMu.Unlock()
triggeredMessages.Set(mid,
append(
triggeredMessages.Get(mid),
message.NewMessageIDFromString(id.String()),
),
)
}
return
}
// GetTriggeredMessages 获取被 id 消息触发的回复消息 id
func GetTriggeredMessages(id message.ID) []message.ID {
triggeredMessagesMu.Lock()
defer triggeredMessagesMu.Unlock()
return triggeredMessages.Get(id.ID())
}
// processEventAsync 从池中处理事件, 异步调用匹配 mather
func processEventAsync(response []byte, caller APICaller, maxwait time.Duration) {
var event Event
_ = json.Unmarshal(response, &event)
event.RawEvent = gjson.Parse(helper.BytesToString(response))
var msgid message.ID
messageID, err := strconv.ParseInt(helper.BytesToString(event.RawMessageID), 10, 64)
if err == nil {
event.MessageID = messageID
msgid = message.NewMessageIDFromInteger(messageID)
} else if event.MessageType == "guild" {
// 是 guild 消息,进行如下转换以适配非 guild 插件
// MessageID 填为 string
event.MessageID, _ = strconv.Unquote(helper.BytesToString(event.RawMessageID))
// 伪造 GroupID
crc := crc64.New(crc64.MakeTable(crc64.ISO))
crc.Write(helper.StringToBytes(event.GuildID))
crc.Write(helper.StringToBytes(event.ChannelID))
r := int64(crc.Sum64() & 0x7fff_ffff_ffff_ffff) // 确保为正数
if r <= 0xffff_ffff {
r |= 0x1_0000_0000 // 确保不与正常号码重叠
}
event.GroupID = r
// 伪造 UserID
crc.Reset()
crc.Write(helper.StringToBytes(event.TinyID))
r = int64(crc.Sum64() & 0x7fff_ffff_ffff_ffff) // 确保为正数
if r <= 0xffff_ffff {
r |= 0x1_0000_0000 // 确保不与正常号码重叠
}
event.UserID = r
if event.Sender != nil {
event.Sender.ID = r
}
msgid = message.NewMessageIDFromString(event.MessageID.(string))
}
switch event.PostType { // process DetailType
case "message", "message_sent":
event.DetailType = event.MessageType
case "notice":
event.DetailType = event.NoticeType
preprocessNoticeEvent(&event)
case "request":
event.DetailType = event.RequestType
}
if event.PostType == "message" {
preprocessMessageEvent(&event)
}
ctx := &Ctx{
Event: &event,
State: State{},
caller: &messageLogger{msgid: msgid, caller: caller},
}
matcherLock.Lock()
if hasMatcherListChanged {
matcherListForRanging = make([]*Matcher, len(matcherList))
copy(matcherListForRanging, matcherList)
hasMatcherListChanged = false
}
matcherLock.Unlock()
go match(ctx, matcherListForRanging, maxwait)
}
// match 匹配规则,处理事件
func match(ctx *Ctx, matchers []*Matcher, maxwait time.Duration) {
if BotConfig.MarkMessage && ctx.Event.MessageID != nil {
ctx.MarkThisMessageAsRead()
}
gorule := func(rule Rule) <-chan bool {
ch := make(chan bool, 1)
go func() {
defer func() {
close(ch)
if pa := recover(); pa != nil {
log.Errorf("[bot] execute rule err: %v\n%v", pa, helper.BytesToString(debug.Stack()))
}
}()
ch <- rule(ctx)
}()
return ch
}
gohandler := func(h Handler) <-chan struct{} {
ch := make(chan struct{}, 1)
go func() {
defer func() {
close(ch)
if pa := recover(); pa != nil {
log.Errorf("[bot] execute handler err: %v\n%v", pa, helper.BytesToString(debug.Stack()))
}
}()
h(ctx)
ch <- struct{}{}
}()
return ch
}
t := time.NewTimer(maxwait)
defer t.Stop()
loop:
for _, matcher := range matchers {
if !matcher.Type(ctx) {
continue
}
for k := range ctx.State { // Clear State
delete(ctx.State, k)
}
m := matcher.copy()
ctx.ma = m
// pre handler
if m.Engine != nil {
for _, handler := range m.Engine.preHandler {
c := gorule(handler)
for {
select {
case ok := <-c:
if !ok { // 有 pre handler 未满足
if m.Break { // 阻断后续
break loop
}
continue loop
}
case <-t.C:
if m.NoTimeout { // 不设超时限制
t.Reset(maxwait)
continue
}
log.Warnln("[bot] preHandler 处理达到最大时延, 退出")
break loop
}
break
}
}
}
for _, rule := range m.Rules {
c := gorule(rule)
for {
select {
case ok := <-c:
if !ok { // 有 Rule 的条件未满足
if m.Break { // 阻断后续
break loop
}
continue loop
}
case <-t.C:
if m.NoTimeout { // 不设超时限制
t.Reset(maxwait)
continue
}
log.Warnln("[bot] rule 处理达到最大时延, 退出")
break loop
}
break
}
}
// mid handler
if m.Engine != nil {
for _, handler := range m.Engine.midHandler {
c := gorule(handler)
for {
select {
case ok := <-c:
if !ok { // 有 mid handler 未满足
if m.Break { // 阻断后续
break loop
}
continue loop
}
case <-t.C:
if m.NoTimeout { // 不设超时限制
t.Reset(maxwait)
continue
}
log.Warnln("[bot] midHandler 处理达到最大时延, 退出")
break loop
}
break
}
}
}
if m.Handler != nil {
c := gohandler(m.Handler)
for {
select {
case <-c: // 处理事件
case <-t.C:
if m.NoTimeout { // 不设超时限制
t.Reset(maxwait)
continue
}
log.Warnln("[bot] Handler 处理达到最大时延, 退出")
break loop
}
break
}
}
if matcher.Temp { // 临时 Matcher 删除
matcher.Delete()
}
if m.Engine != nil {
// post handler
for _, handler := range m.Engine.postHandler {
c := gohandler(handler)
for {
select {
case <-c:
case <-t.C:
if m.NoTimeout { // 不设超时限制
t.Reset(maxwait)
continue
}
log.Warnln("[bot] postHandler 处理达到最大时延, 退出")
break loop
}
break
}
}
}
if m.Block { // 阻断后续
break loop
}
}
}
// preprocessMessageEvent 返回信息事件
func preprocessMessageEvent(e *Event) {
msgs := message.ParseMessage(e.NativeMessage)
if len(msgs) > 0 {
filtered := make([]message.Segment, 0, len(msgs))
// trim space after at and remove empty text segment
for i := range msgs {
if i < len(msgs)-1 && msgs[i].Type == "at" && msgs[i+1].Type == "text" {
msgs[i+1].Data["text"] = strings.TrimLeft(msgs[i+1].Data["text"], " ")
}
if msgs[i].Type != "text" || msgs[i].Data["text"] != "" {
filtered = append(filtered, msgs[i])
}
}
e.Message = filtered
}
processAt := func() { // 处理是否at机器人
e.IsToMe = false
if len(e.Message) == 0 {
return
}
for i, m := range e.Message {
if m.Type == "at" {
qq, _ := strconv.ParseInt(m.Data["qq"], 10, 64)
if qq == e.SelfID {
e.IsToMe = true
if !BotConfig.KeepAtMeMessage {
e.Message = append(e.Message[:i], e.Message[i+1:]...)
}
return
}
}
}
if len(e.Message) == 0 || e.Message[0].Type != "text" {
return
}
first := e.Message[0]
first.Data["text"] = strings.TrimLeft(first.Data["text"], " ") // Trim!
text := first.Data["text"]
for _, nickname := range BotConfig.NickName {
if strings.HasPrefix(text, nickname) {
e.IsToMe = true
first.Data["text"] = text[len(nickname):]
return
}
}
}
switch {
case e.DetailType == "group":
log.Infof("[bot] 收到群(%v)消息 %v : %v", e.GroupID, e.Sender.String(), e.RawMessage)
processAt()
case e.DetailType == "guild" && e.SubType == "channel":
log.Infof("[bot] 收到频道(%v)(%v-%v)消息 %v : %v", e.GroupID, e.GuildID, e.ChannelID, e.Sender.String(), e.Message)
processAt()
default:
e.IsToMe = true // 私聊也判断为at
log.Infof("[bot] 收到私聊消息 %v : %v", e.Sender.String(), e.RawMessage)
}
if len(e.Message) > 0 && e.Message[0].Type == "text" { // Trim Again!
e.Message[0].Data["text"] = strings.TrimLeft(e.Message[0].Data["text"], " ")
}
}
// preprocessNoticeEvent 更新事件
func preprocessNoticeEvent(e *Event) {
if e.SubType == "poke" || e.SubType == "lucky_king" {
e.IsToMe = e.TargetID == e.SelfID
} else {
e.IsToMe = e.UserID == e.SelfID
}
}
// GetBot 获取指定的bot (Ctx)实例
func GetBot(id int64) *Ctx {
caller, ok := APICallers.Load(id)
if !ok {
return nil
}
return &Ctx{caller: caller}
}
// RangeBot 遍历所有bot (Ctx)实例
//
// 单次操作返回 true 则继续遍历,否则退出
func RangeBot(iter func(id int64, ctx *Ctx) bool) {
APICallers.Range(func(key int64, value APICaller) bool {
return iter(key, &Ctx{caller: value})
})
}
// GetFirstSuperUser 在 qqs 中获得 SuperUsers 列表的首个 qq
//
// 找不到返回 -1
func (op *Config) GetFirstSuperUser(qqs ...int64) int64 {
m := make(map[int64]struct{}, len(qqs)*4)
for _, qq := range qqs {
m[qq] = struct{}{}
}
for _, qq := range op.SuperUsers {
if _, ok := m[qq]; ok {
return qq
}
}
return -1
}