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
|
package discord
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log"
"math/rand"
"net/http"
"time"
"github.com/gorilla/websocket"
)
const DISCORD_URl = "https://discord.com/api/v9/"
const USER_AGENT = "DiscordBot (https://jinx.rnrd.eu/, v0.0.0) Jinx"
type Discord struct {
Token string
Conn *websocket.Conn
}
func NewClient(token string) *Discord {
return &Discord{
Token: token,
Conn: nil,
}
}
func (d *Discord) Connect(ctx context.Context) error {
gatewayURL, err := d.getGateway()
if err != nil {
return err
}
fmt.Printf("gateway: %s\n", gatewayURL)
connectHeader := http.Header{}
d.Conn, _, err = websocket.DefaultDialer.Dial(gatewayURL, connectHeader)
if err != nil {
return err
}
var helloMsg GatewayPayload[GatewayHelloMsg]
if err = d.Conn.ReadJSON(&helloMsg); err != nil {
return err
}
fmt.Printf("connection response Payload: %+v\n", helloMsg)
if helloMsg.Op != GATEWAY_OP_HELLO {
return fmt.Errorf("expected opcode %d, got %d", GATEWAY_OP_HELLO, helloMsg.Op)
}
go d.startHeartbeat(ctx, helloMsg.Data.HeartbeatInterval)
if err = d.identify(); err != nil {
return err
}
return nil
}
func (d *Discord) Disconnect() error {
if d.Conn == nil {
return errors.New("not connected")
}
return d.Conn.Close()
}
func (d *Discord) getGateway() (string, error) {
url := DISCORD_URl + "gateway"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
req.Header.Set("Authorization", d.Token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", USER_AGENT)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
var buf bytes.Buffer
_, err = buf.ReadFrom(resp.Body)
if err != nil {
return "", err
}
switch resp.StatusCode {
case 200:
default:
return "", errors.New("gateway response status code: " + resp.Status)
}
body := struct {
URL string `json:"url"`
}{}
err = json.Unmarshal(buf.Bytes(), &body)
if err != nil {
return "", err
}
url = body.URL + "?v=9&encoding=json"
return url, nil
}
func (d *Discord) startHeartbeat(ctx context.Context, interval uint64) {
// REF: heartbeat_interval * jitter
jitter := rand.Intn(int(interval))
time.Sleep(time.Duration(jitter) * time.Millisecond)
ticker := time.NewTicker(time.Duration(interval) * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
fmt.Println("sending heartbeat.")
msg := GatewayPayload[any]{
Op: GATEWAY_OP_HEARTBEAT,
}
if err := d.Conn.WriteJSON(msg); err != nil {
log.Fatalf("error sending heartbeat: %s\n", err)
}
}
}
}
func (d *Discord) identify() error {
msg := GatewayPayload[GatewayIdentifyMsg]{
Op: GATEWAY_OP_IDENTIFY,
Data: GatewayIdentifyMsg{
Token: d.Token,
Properties: GatewayIdentifyProperties{
OS: "linux",
Browser: "jinx",
Device: "jinx",
},
},
Sequence: 0,
}
if err := d.Conn.WriteJSON(msg); err != nil {
return err
}
var res GatewayPayload[GatewayReadyMsg]
if err := d.Conn.ReadJSON(&res); err != nil {
return err
}
fmt.Printf("identify response payload: %+v\n", res)
if res.Op != GATEWAY_OP_DISPATCH {
return fmt.Errorf("expected opcode %d, got %d", GATEWAY_OP_DISPATCH, res.Op)
}
if res.EventName != "READY" {
return fmt.Errorf("expected event name %s, got %s", "READY", res.EventName)
}
return nil
}
|