-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.js
348 lines (327 loc) · 7.83 KB
/
bot.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
require('dotenv').config(); // process.env to store API keys/tokens
const command = require('./command');
const CronJob = require('cron').CronJob;
const Discord = require('discord.js');
const client = new Discord.Client();
const firebase = require('firebase');
firebase.initializeApp({
apiKey: process.env.firebase_key,
databaseURL: process.env.firebase_url,
projectId: process.env.firebase_project_id,
});
const database = firebase.database();
const SpotifyWebApi = require('spotify-web-api-node');
const spotifyApi = new SpotifyWebApi({
clientId: process.env.spotify_client_id,
clientSecret: process.env.spotify_client_secret,
});
const channelID = process.env.channel_ID;
const prefix = process.env.prefix;
let artistDict = {};
let dictSize;
client.on('ready', async () => {
console.log('Discord Client Ready');
await fillArtistDict();
await refreshAccessToken();
const statusInterval = setInterval(setStatus, 3600000);
let checkMusicAtMidnightJob = new CronJob(
'1 */12 * * *',
() => {
// cron job everyday at 12:01 AM and 12:01 PM
console.log('Running cron job');
client.channels.cache.get(channelID).send(`${prefix}check`);
},
undefined,
true,
'America/New_York'
);
checkMusicAtMidnightJob.start();
command(client, 'add', (message) => {
let artistName = message.content.replace(`${prefix}add `, '');
if (message.content === `${prefix}add` || !artistName) {
message.channel.send(
`Enter a valid artist name. i.e. \'${prefix}add Drake\'`
);
} else {
spotifyApi
.searchArtists(artistName, {
limit: 1,
})
.then(
(data) => {
let artistData = data.body.artists.items[0];
if (artistData) {
message.channel.send(`Adding: ${artistData.name}`);
addNewArtist(
artistData.name
.replace('$', 'S')
.replace(',', ''),
artistData.uri.replace('spotify:artist:', '')
);
fillArtistDict();
} else {
message.channel.send(
`Enter a valid artist name.\ni.e. \'${prefix}add Drake\'`
);
}
},
(err) => {
console.error(err);
}
);
}
});
command(client, 'rm', (message) => {
let artistName = message.content.replace(`${prefix}rm `, '');
if (message.content === `${prefix}add` || !artistName) {
message.channel.send(
`Enter a valid artist name.\ni.e. \'${prefix}remove Drake\'`
);
} else {
spotifyApi
.searchArtists(artistName, {
limit: 1,
})
.then(
(data) => {
let artistData = data.body.artists.items[0];
if (artistData) {
let artistName = artistData.name;
if (
artistName &&
artistDict.hasOwnProperty(artistName)
) {
artistName.replace('$', 'S').replace(',', '');
message.channel.send(
`Removing: ${artistName}`
);
removeArtist(artistName);
fillArtistDict();
} else {
message.channel.send(
`Artist does not exist in your list of artists.\nTry \'${prefix}ls\' to list your added artists.`
);
}
} else {
message.channel.send(
`Enter a valid artist name.\ni.e. \'${prefix}rm Drake\'`
);
}
},
(err) => {
console.error(err);
}
);
}
});
command(client, 'check', (message) => {
let newMusicRole = message.guild.roles.cache.find(
(role) => role.name === 'New Music'
);
getNewMusic(newMusicRole).then(
(embed) => {
if (embed.fields[0])
message.channel.send({
embed,
});
else {
let embed = {
title: 'No Music Today :(',
color: '1DB954',
fields: [],
};
message.channel.send({
embed,
});
}
},
(err) => {
console.error(err);
}
);
});
command(client, ['ls', 'list'], (message) => {
let embed = {
title: '**__Artists__**',
color: '1DB954',
fields: [],
};
let str = '';
for (const [name, uri] of Object.entries(artistDict)) {
str += `${name}\n`;
}
embed.description = str;
message.channel.send({
embed,
});
});
command(client, ['h', 'help'], (message) => {
let embed = {
title: '**__Commands__**',
color: '1DB954',
fields: [
{
name: `${prefix}add`,
value: 'Add artist to your list of artists.',
},
{
name: `${prefix}remove (rm)`,
value: 'Remove artist to your list of artists.',
},
{
name: `${prefix}list (ls)`,
value: 'List all artists in your list of artists.',
},
{
name: `${prefix}check`,
value: 'Check for new music from your list of artists.',
},
],
};
message.channel.send({
embed,
});
});
});
client.login(process.env.discord_token);
async function addNewArtist(name, uri) {
await database.ref('artists/').child(name).set(uri);
}
async function removeArtist(name) {
await database
.ref(`artists/${name}`)
.remove()
.then((err) => {
if (err) {
console.error(err);
} else {
delete artistDict[name];
console.log('Successfully removed artist.');
}
});
}
async function getNewMusic(roleID) {
const date = getFormattedDate();
let embed = {
title: '**__New Music Today__**',
description: `${roleID}`,
color: '1DB954',
fields: [],
};
for (const [name, uri] of Object.entries(artistDict)) {
let newMusicStr = '';
await spotifyApi
.getArtistAlbums(uri, {
album_type: 'album',
limit: 1,
})
.then(
(data) => {
let album = data.body.items[0];
if (album && album.release_date === date) {
newMusicStr += `New Album:\n${album.name}\n[Link](${album.external_urls.spotify})\n\v`;
}
},
(err) => {
console.error(err);
}
);
await spotifyApi
.getArtistAlbums(uri, {
album_type: 'single',
limit: 1,
})
.then(
(data) => {
let single = data.body.items[0];
if (single && single.release_date === date) {
newMusicStr += `New Single:\n${single.name}\n[Link](${single.external_urls.spotify})\n\v`;
}
},
(err) => {
console.error(err);
}
);
if (newMusicStr)
embed.fields.push({
name: name,
value: newMusicStr,
});
}
return embed;
}
function getFormattedDate() {
let formattedDate = '';
let date = new Date().toLocaleDateString('en-US', {
timeZone: 'America/New_York',
});
let firstIndex = date.indexOf('/');
let lastIndex = date.lastIndexOf('/');
let month = date.slice(0, firstIndex);
let day = date.slice(firstIndex + 1, lastIndex);
let year = date.slice(lastIndex + 1, date.length);
formattedDate += `${year}-`;
if (month < 10) formattedDate += `0${month}-`;
else formattedDate += `${month}-`;
if (day < 10) formattedDate += `0${day}`;
else formattedDate += `${day}`;
return formattedDate;
// return '2020-12-11'; // Test date. Man on the Moon III came out.
}
function getRandomArtist() {
let artist = null;
let randomIndex = Math.floor(Math.random() * dictSize);
let count = 0;
for (const [name, uri] of Object.entries(artistDict)) {
if (count === randomIndex) {
artist = name;
break;
}
count++;
}
return artist;
}
async function fillArtistDict() {
artistDict = {};
await database.ref('artists/').once(
'value',
(snapshot) => {
let counter = 0;
dictSize = snapshot.numChildren();
snapshot.forEach((childSnapshot) => {
artistDict[
Object.keys(snapshot.val())[counter]
] = childSnapshot.val();
counter++;
});
},
(err) => {
console.error(err);
}
);
}
function setStatus() {
artist = getRandomArtist();
if (artist)
client.user.setActivity(`${artist}`, {
type: 'LISTENING',
});
else
client.user.setActivity(`${prefix}help`, {
type: 'LISTENING',
});
}
async function refreshAccessToken() {
await spotifyApi.clientCredentialsGrant().then(
(data) => {
spotifyApi.setAccessToken(data.body['access_token']);
},
(err) => {
console.error(
'Something went wrong when retrieving an access token',
err
);
}
);
}
let interval = setInterval(refreshAccessToken, 3600000);