Skip to content

Instantly share code, notes, and snippets.

@RyosukeCla
Last active April 1, 2020 03:18
Show Gist options
  • Save RyosukeCla/15a3ebc637298a64cdac116f1b92ea99 to your computer and use it in GitHub Desktop.
Save RyosukeCla/15a3ebc637298a64cdac116f1b92ea99 to your computer and use it in GitHub Desktop.
spotify slack integration
{
"name": "spotify-slack-integration",
"version": "1.0.0",
"description": "",
"main": "spotify-slack-integration.js",
"scripts": {
"start": "node spotify-slack-integration.js",
},
"license": "MIT",
"dependencies": {
"node-fetch": "^2.6.0",
},
"engines": {
"node": ">= 10.16.0"
}
}
const fetch = require('node-fetch');
const slack_token = process.env.SLACK_API_TOKEN;
const spotify_token = process.env.SPOTIFY_ACCESS_TOKEN;
if (!slack_token || !spotify_token) {
throw new Error('should set token')
}
async function setSlackProfileStatus({ emoji, message }) {
const res = await fetch('https://slack.com/api/users.profile.set', {
method: 'POST',
body: JSON.stringify({
profile: {
status_text: message,
status_emoji: emoji,
},
}),
headers: {
'Content-type': 'application/json; charset=utf-8',
'Authorization': `Bearer ${slack_token}`,
}
})
if (res.status !== 200) {
console.log('coudnt set slack profile status')
return
}
const json = await res.json()
if (!json.ok) {
console.log('coudnt set slack profile status', json)
}
}
async function getSpotifyCurrentTrack() {
const res = await fetch('https://api.spotify.com/v1/me/player/currently-playing', {
method: 'GET',
headers: {
'Authorization': `Bearer ${spotify_token}`,
"Accept": "application/json",
"Content-Type": "application/json",
},
})
if (res.status !== 200) {
console.log(res.statusText)
return false
}
return await res.json()
}
async function polling(spotify_access_token) {
const spotifyObject = await getSpotifyCurrentTrack(spotify_access_token)
if (!spotifyObject) {
await setSlackProfileStatus({
emoji: '',
message: ''
})
console.log("set emoji: '', message: ''")
return
}
const { item: { artists, name } } = spotifyObject
const artist = artists.length > 0 ? artists[0] : { name: 'unknown' }
const message = `${name} - ${artist.name}`
console.log(`set current playing: ${message}`)
await setSlackProfileStatus({
emoji: ':spotify:',
message
})
}
async function main() {
await polling()
setInterval(() => {
polling().catch(e => console.error(e))
}, 30 * 1000)
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment