Skip to content

Instantly share code, notes, and snippets.

@dreygur
Created February 27, 2022 20:08
Show Gist options
  • Select an option

  • Save dreygur/50c4fde1289f7f4d21cad22e0e6776d4 to your computer and use it in GitHub Desktop.

Select an option

Save dreygur/50c4fde1289f7f4d21cad22e0e6776d4 to your computer and use it in GitHub Desktop.
const WebSocket = require('ws');
require('dotenv').config();
// Websocket instance
const ws = new WebSocket('wss://gateway.discord.gg/?v=9&encoding=json');
// Heartbeat interval
const heartBit = (interval) => {
setTimeout(() => {
ws.send(JSON.stringify({
op: 1,
d: null
}));
}, interval);
}
// Websocket event listeners
// Connection Open
ws.on('open', () => {
ws.send(JSON.stringify({
op: 2,
d: {
token: process.env.AUTH_TOKEN,
capabilities: 253,
properties: {
"os": "Linux",
"browser": "Chrome",
"device": "Linux"
}
}
}))
})
// Getting Responses
ws.on('message', (data) => {
let res = JSON.parse(data);
let { op, d, t } = res;
switch (op) {
case 10:
let { heartbeat_interval } = d;
heartBit(heartbeat_interval);
break;
case 11:
console.log(`[${t}]`, 'Recieved heartbeat');
}
switch (t) {
case 'READY':
console.log(`Logged in as ${d.user.username}#${d.user.discriminator}`);
break
case 'MESSAGE_CREATE':
let author = d.author.username;
let authorId = d.author.id;
let content = d.content;
console.log(`[${author}] ${content}`);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment