From 51e810264c9cf4b3cd5151fda32e287dc0e21095 Mon Sep 17 00:00:00 2001 From: SileNce5k Date: Thu, 7 Mar 2024 11:18:21 +0100 Subject: [PATCH] FM: Add a toptracks feature --- commands/misc/fm.js | 5 ++++- util/lastfm/getTopTracks.js | 38 +++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 util/lastfm/getTopTracks.js diff --git a/commands/misc/fm.js b/commands/misc/fm.js index 284cca3..d789ae9 100644 --- a/commands/misc/fm.js +++ b/commands/misc/fm.js @@ -1,6 +1,6 @@ const fmlogin = require("../../util/lastfm/fmlogin"); const getCurrentScrobble = require("../../util/lastfm/getCurrentScrobble"); - +const getTopTracks = require("../../util/lastfm/getTopTracks"); module.exports = { name: 'fm', description: 'Last fm commands. See `help fm` for more info.', @@ -14,6 +14,9 @@ module.exports = { case "set": sendText = await fmlogin(message.author.id, args[1]); break; + case "toptracks": + case "tt": + sendText = await getTopTracks(message.author.id, args); default: break; } diff --git a/util/lastfm/getTopTracks.js b/util/lastfm/getTopTracks.js new file mode 100644 index 0000000..997dafb --- /dev/null +++ b/util/lastfm/getTopTracks.js @@ -0,0 +1,38 @@ +// http://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=username&api_key=YOUR_API_KEY&format=json + +const getFmUsername = require("./getFmUsername") + +module.exports = async function (userID, options) { + let lastfmUsername = await getFmUsername(userID); + let sendText = ""; + let tracks = []; + const apiKey = process.env.LAST_FM_API_KEY; + if(lastfmUsername != undefined){ + tracks = await new Promise ((resolve, reject) => { + fetch(`https://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=${lastfmUsername}&api_key=${apiKey}&format=json`) + .then(response => response.json()) + .then(data => { + for(let i = 0; i < 10; i++){ + let track = {} + let currentTrack = data.toptracks.track[i]; + track.artist = currentTrack.artist.name; + track.song = currentTrack.name; + track.playcount = currentTrack.playcount; + tracks.push(track); + } + resolve(tracks); + }) + .catch(error => { + console.error(error); + reject(error); + }); + }); + sendText = `Your top 10 tracks are:\n`; + for(let i = 0; i < tracks.length; i++){ + sendText += `${i}. ${tracks[i].artist} - ${tracks[i].song} (${tracks[i].playcount} plays)\n`; + } + } else { + sendText = "You haven't set your last.fm username yet. Use `fm set ` to set it."; + } + return sendText; +} \ No newline at end of file