Created
August 6, 2021 12:48
-
-
Save davidborzek/d2f5650c763f750de39ef534bdd43181 to your computer and use it in GitHub Desktop.
Access the spotify websocket api for real time updates about playback etc. Only works with an offical access token, third-party ones don't work.
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
import axios from 'axios'; | |
import WebSocket from 'ws'; | |
/* | |
Use a spotify acces token from an offical source like open.spotify.com. You can obtain it by using the network inspector in your browser. | |
Third-party access token obtained via OAuth2 will not work because of an api limitation by spotify. | |
*/ | |
const ACCESS_TOKEN = ""; | |
const createWebSocketUrl = (accessToken) => `wss://dealer.spotify.com/?access_token=${accessToken}`; | |
const ws = new WebSocket(createWebSocketUrl(ACCESS_TOKEN)); | |
const ping = () => { | |
ws.send(JSON.stringify({ | |
type: "ping" | |
})); | |
} | |
ws.on('open', function open() { | |
console.log(new Date(), "Connected to spotify's websocket server!") | |
ping(); | |
setInterval(ping, 15000); | |
}); | |
ws.on('message', function incoming(message) { | |
const jsonMessage = JSON.parse(message.toString()); | |
if ('headers' in jsonMessage && jsonMessage.headers['Spotify-Connection-Id'] ) { | |
console.log(new Date(), "Received spotify connection id:\n", jsonMessage.headers['Spotify-Connection-Id'], "\n"); | |
// This will throw 401 if you're not using an offical access token. | |
axios.put("https://api.spotify.com/v1/me/notifications/player", undefined, { | |
params: { | |
connection_id: jsonMessage.headers['Spotify-Connection-Id'] | |
}, | |
headers: { | |
Authorization: `Bearer ${ACCESS_TOKEN}` | |
} | |
}).then(() => console.log(new Date(), "Sent subscription request to https://api.spotify.com/v1/me/notifications/player: \n")); | |
} else { | |
console.log(new Date(), jsonMessage); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment