This repository has been archived by the owner on Mar 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
79 lines (66 loc) · 1.74 KB
/
handler.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
package eventide
import (
"encoding/json"
"reflect"
"github.com/thefakequake/eventide/discord"
)
type Handler struct {
Callback reflect.Value
}
// Adds an event handler based on the handler's function signature
func (c *Client) AddHandler(h any) {
v := reflect.ValueOf(h)
t := v.Type()
if v.Kind() != reflect.Func {
c.log(LogError, "event handler must be a function")
return
} else if t.NumIn() != 1 {
c.log(LogError, "event handler must only have one argument")
return
} else if t.NumOut() > 0 {
c.log(LogError, "event handler must not return anything")
return
}
eventType := t.In(0)
c.log(LogInfo, "registered event handler for type %s", eventType.String())
c.handlersLock.Lock()
c.handlers[eventType] = append(c.handlers[eventType], Handler{Callback: v})
c.handlersLock.Unlock()
}
func (c *Client) runHandlers(op discord.GatewayPayload[json.RawMessage]) {
e, err := eventCodec.DecodeEvent(op)
if err != nil {
c.log(LogWarn, "failed to decode event: %s", err)
return
}
v := reflect.ValueOf(e)
c.handlersLock.RLock()
for _, h := range c.handlers[v.Type()] {
h.Callback.Call([]reflect.Value{v})
}
c.handlersLock.RUnlock()
}
// Registers built in handlers for the client's internal use
func (c *Client) registerDefaultHandlers() {
c.AddHandler(func(r *discord.ReadyEvent) {
c.Lock()
c.User = r.User
c.sessionID = r.SessionID
c.Unlock()
})
c.AddHandler(func(g *discord.GuildUpdateEvent) {
c.guildsLock.Lock()
c.Guilds[g.ID] = g.Guild
c.guildsLock.Unlock()
})
c.AddHandler(func(g *discord.GuildCreateEvent) {
c.guildsLock.Lock()
c.Guilds[g.ID] = g.Guild
c.guildsLock.Unlock()
})
c.AddHandler(func(g *discord.GuildDeleteEvent) {
c.guildsLock.Lock()
delete(c.Guilds, g.ID)
c.guildsLock.Unlock()
})
}