Created
August 24, 2021 15:16
-
-
Save JulianVennen/7af96c8f2ae556009d6525e041f77a84 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {WebSocket} = require('ws'); | |
const config = require('../config.json'); | |
let heartBeatInterval, | |
sequence = null, | |
debug = false, | |
heartBeatAck = true; | |
const ws = new WebSocket('wss://gateway.discord.gg/?v=9&encoding=json'); | |
ws.on('open', () => { | |
console.log('Websocket connected!') | |
}) | |
ws.on('message', msg => { | |
if (debug) console.log('Websocket message: ' + msg) | |
try { | |
const data = JSON.parse(msg.toString()); | |
if (data.s) | |
sequence = data.s; | |
switch (data.op) { | |
case 0: | |
const event = data.t; | |
console.log(`Event: ${data.t}`); | |
if (event === 'PRESENCE_UPDATE') { | |
console.log(data.d.status, data.d.client_status) | |
} | |
break; | |
case 10: | |
console.log(`Starting heartbeat interval of ${data.d.heartbeat_interval}ms!`) | |
heartBeatInterval = setInterval(() => { | |
if (!heartBeatAck) { | |
console.error(`Last heartbeat wasn't acknowledged!\nQuitting...`) | |
ws.close(-1); | |
process.exit(-1); | |
} | |
if (debug) console.log('Sending heartbeat!') | |
heartBeatAck = false; | |
ws.send(JSON.stringify({ | |
op: 1, | |
d: sequence | |
})) | |
}, data.d.heartbeat_interval); | |
console.log('Identifying...'); | |
ws.send(JSON.stringify({ | |
op: 2, | |
d: { | |
token: config.auth_token, | |
intents: 256, | |
properties: { | |
$os: 'linux', | |
$browser: 'StatusBot', | |
$device: 'StatusBot', | |
} | |
} | |
})); | |
break; | |
case 11: | |
if (debug) console.log('Heartbeat acknowledged!') | |
heartBeatAck = true; | |
break; | |
default: | |
console.log('Unknown opcode ' + data.op, data); | |
break; | |
} | |
} | |
catch (e) { | |
console.error('Failed to parse Websocket message: ', e) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment