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
/
client.go
121 lines (99 loc) · 2.48 KB
/
client.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
package eventide
import (
"fmt"
"net/http"
"os"
"os/signal"
"reflect"
"runtime"
"strings"
"sync"
"syscall"
"time"
"github.com/gorilla/websocket"
"github.com/thefakequake/eventide/discord"
)
type Client struct {
sync.RWMutex
ws *websocket.Conn
wsLock sync.RWMutex
http *http.Client
lastSequence int64
closeListeners []chan int
listenerLock sync.RWMutex
gateway string
sessionID string
handlers map[reflect.Type][]Handler
handlersLock sync.RWMutex
token string
logLevel LogLevel
identifyProperties *discord.IdentifyConnectionProperties
intents discord.Intents
compress bool
User *discord.User
Guilds map[string]*discord.Guild
guildsLock sync.RWMutex
}
// Client configuration
type ClientConfig struct {
// Discord bot token
Token string
// Gateway intents that dictate what events the client will receive, defaults to discord.IntentsDefault
Intents discord.Intents
// If enabled, disables zlib data compression over the Discord Gateway
DisableCompression bool
// Logging level of the client
LogLevel LogLevel
// Gateway identify properties
IdentifyProperties *discord.IdentifyConnectionProperties
}
func NewClient(cfg ClientConfig) *Client {
if !strings.HasPrefix(cfg.Token, "Bot ") {
cfg.Token = "Bot " + cfg.Token
}
if cfg.IdentifyProperties == nil {
cfg.IdentifyProperties = &discord.IdentifyConnectionProperties{
OS: runtime.GOOS,
Browser: "go-eventide",
Device: "go-eventide",
}
}
c := &Client{
http: &http.Client{
Timeout: 10 * time.Second,
},
handlers: make(map[reflect.Type][]Handler),
lastSequence: 0,
token: cfg.Token,
logLevel: cfg.LogLevel,
identifyProperties: cfg.IdentifyProperties,
intents: cfg.Intents,
compress: !cfg.DisableCompression,
Guilds: map[string]*discord.Guild{},
}
c.registerDefaultHandlers()
return c
}
func (c *Client) Run() error {
if err := c.Connect(); err != nil {
return fmt.Errorf("error conneting to gateway: %s", err)
}
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt, syscall.SIGTERM)
listening := c.listenClose()
Loop:
for {
select {
case <-sc:
if err := c.Disconnect(); err != nil {
return fmt.Errorf("error disconnecting from gateway: %s", err)
}
case code := <-listening:
if code != websocket.CloseServiceRestart {
break Loop
}
listening = c.listenClose()
}
}
return nil
}