|
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() |
|
|