Skip to content

Instantly share code, notes, and snippets.

@vildzi
Created March 22, 2019 21:41
Show Gist options
  • Save vildzi/4e8a2493386623cadb1d3d662a55983a to your computer and use it in GitHub Desktop.
Save vildzi/4e8a2493386623cadb1d3d662a55983a to your computer and use it in GitHub Desktop.
HQ Trivia websocket tutorial
const request = require('request'); // npm i request
const WebSocket = require('ws'); // npm i ws
request('https://api-quiz.hype.space/shows/now`, (err, res, body) => {
const json = JSON.parse(body);
if (json.active) {
const ws = new WebSocket(json.broadcast.socketUrl, { headers: { authorization: '<BEARER TOKEN>' } });
ws.onopen = () => {
const i = setInterval(() => {
if (ws.readyState !== ws.OPEN) return clearInterval(i);
ws.ping();
}, 5000);
};
ws.onmessage = (msg) => {
const data = JSON.parse(msg.data);
if (data.type !== 'interaction') console.log(data);
};
} else console.log('Game not live');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment