-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·76 lines (63 loc) · 1.99 KB
/
index.js
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
const { WebSocketServer, WebSocket } = require("ws");
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (ws) => {
const discord = new WebSocket("wss://gateway.discord.gg/?v=10&encoding=json");
let heart;
let s = null;
let acknowledged = true;
ws.on("error", console.error);
ws.on("close", () => {
discord.close();
clearInterval(heart);
});
ws.on("message", (raw) => {
console.log(`[SENT] ${raw}`);
discord.send(raw);
});
discord.on("close", (code, reason) => {
ws.close();
clearInterval(heart);
console.log(`[DISCORD CLOSED] ${reason}`);
});
discord.on("error", console.error);
discord.on("message", (raw) => {
const data = JSON.parse(raw);
console.log(`[RECEIVED] ${raw}`);
if (data.s)
s = data.s;
switch (data.op) {
case 10: {
const heartbeatInterval = data.d.heartbeat_interval;
const timer = heartbeatInterval * Math.random();
console.log(`Waiting ${timer}ms.`);
heart = setTimeout(() => {
heartbeat(discord, s);
setInterval(() => heartbeat(discord, s), heartbeatInterval);
}, heartbeatInterval * Math.random());
break;
}
case 1: {
heartbeat(discord, s);
break;
}
case 11: {
acknowledged = true;
break;
}
}
ws.send(raw);
});
function heartbeat() {
if (!acknowledged) {
console.log("Didn't receive heartbeat acknowledgement? Closing!");
clearInterval(heart);
discord.close();
ws.close();
}
discord.send(JSON.stringify({
op: 1,
d: s
}));
acknowledged = false;
}
});