forked from THE-cattail/qq-bot-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathev.go
86 lines (79 loc) · 1.82 KB
/
ev.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
package qqbotapi
import (
"fmt"
"reflect"
)
type Ev struct {
updatesChannel UpdatesChannel
subscribers map[string][]func(update Update)
}
func NewEv(channel UpdatesChannel) *Ev {
ev := &Ev{
updatesChannel: channel,
subscribers: make(map[string][]func(update Update)),
}
go func() {
for update := range channel {
postType := update.PostType
var detailedType string
switch postType {
case "notice":
detailedType = update.NoticeType
case "message":
detailedType = update.MessageType
case "request":
detailedType = update.RequestType
}
if detailedType != "" {
if update.SubType != "" {
ev.Emit(
fmt.Sprintf("%s.%s.%s", postType, detailedType, update.SubType),
update,
)
}
ev.Emit(
fmt.Sprintf("%s.%s", postType, detailedType),
update,
)
}
ev.Emit(postType, update)
}
}()
return ev
}
type Unsubscribe func()
func (ev *Ev) Emit(event string, update Update) {
if handlers, ok := ev.subscribers[event]; ok {
for _, handler := range handlers {
handler(update)
}
}
}
func (ev *Ev) On(event string) func(func(update Update)) Unsubscribe {
return func(handler func(update Update)) Unsubscribe {
handlers, ok := ev.subscribers[event]
if !ok {
ev.subscribers[event] = make([]func(update Update), 0)
handlers = ev.subscribers[event]
}
ev.subscribers[event] = append(handlers, handler)
return func() {
ev.Off(event)(handler)
}
}
}
func (ev *Ev) Off(event string) func(func(update Update)) {
return func(handler func(update Update)) {
handlers, ok := ev.subscribers[event]
if !ok {
return
}
newHandlers := make([]func(update Update), 0)
for _, h := range handlers {
if reflect.ValueOf(h) != reflect.ValueOf(handler) {
newHandlers = append(newHandlers, h)
}
}
ev.subscribers[event] = newHandlers
}
}