-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
84 lines (79 loc) · 2.85 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const { WebClient } = require('@slack/web-api');
const { RTMClient } = require('@slack/rtm-api');
const request = require('request-promise');
const slackWebClient = new WebClient(process.env.SLACK_BOT_TOKEN);
const rtm = new RTMClient(process.env.SLACK_BOT_TOKEN);
let spotifyAccessToken = null;
async function getCurrentlyPlayingTrack() {
try {
const options = {
uri: 'https://api.spotify.com/v1/me/player/currently-playing',
headers: { Authorization: `Bearer ${spotifyAccessToken}` },
json: true,
};
const response = await request.get(options);
return response.item.name;
} catch (error) {
console.error('Error getting currently playing track:', error);
return null;
}
}
async function authorizeSpotify(event) {
try {
const options = {
uri: 'https://accounts.spotify.com/api/token',
form: {
grant_type: 'authorization_code',
code: event.query.code,
redirect_uri: process.env.SPOTIFY_REDIRECT_URI,
},
headers: {
Authorization: `Basic ${Buffer.from(`${process.env.SPOTIFY_CLIENT_ID}:${process.env.SPOTIFY_CLIENT_SECRET}`).toString('base64')}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
json: true,
};
const response = await request.post(options);
spotifyAccessToken = response.access_token;
const message = {
channel: event.state.channel_id,
text: 'Thank you for authorizing me to access your Spotify account.',
};
await slackWebClient.chat.postMessage(message);
} catch (error) {
console.error('Error authorizing Spotify:', error);
const message = {
channel: event.state.channel_id,
text: 'Sorry, I could not authorize your Spotify account.',
};
await slackWebClient.chat.postMessage(message);
}
}
rtm.on('message', async (event) => {
if (event.text && event.text.includes(`<@${rtm.activeUserId}> spotify`)) {
if (!spotifyAccessToken) {
const authUrl = `https://accounts.spotify.com/authorize?client_id=${process.env.SPOTIFY_CLIENT_ID}&response_type=code&redirect_uri=${process.env.SPOTIFY_REDIRECT_URI}&scope=user-read-currently-playing`;
const message = {
channel: event.channel,
text: `Please authorize me to access your Spotify account by visiting this URL: ${authUrl}`,
};
await slackWebClient.chat.postMessage(message);
} else {
const trackName = await getCurrentlyPlayingTrack();
if (trackName) {
const message = {
channel: event.channel,
text: `You're currently listening to: ${trackName}`,
};
await slackWebClient.chat.postMessage(message);
} else {
const message = {
channel: event.channel,
text: 'Unable to retrieve the currently playing track.',
};
await slackWebClient.chat.postMessage(message);
}
}
}
});
rtm.start();