diff --git a/commands/misc/fm.js b/commands/misc/fm.js index e3d2002..3f97c3b 100644 --- a/commands/misc/fm.js +++ b/commands/misc/fm.js @@ -1,5 +1,6 @@ const fmlogin = require("../../util/lastfm/fmlogin"); const getCurrentScrobble = require("../../util/lastfm/getCurrentScrobble"); +const getCurrentCover = require("../../util/lastfm/getCurrentCover"); const getTopTracks = require("../../util/lastfm/getTopTracks"); const help = require("../info/help"); const parseMention = require("../../util/parseMention"); @@ -26,6 +27,9 @@ module.exports = { args.shift(); sendText.text = await getTopTracks(message.author.id, args); break; + case "cover": + sendText = await getCurrentCover(message.author.id, message.guild); + sendText.embed.get default: sendText.text = `${args[0]} is not a valid subcommand.\nSee \`${prefix}help fm\` for more info.`; break; diff --git a/util/lastfm/getCurrentCover.js b/util/lastfm/getCurrentCover.js new file mode 100644 index 0000000..306b79b --- /dev/null +++ b/util/lastfm/getCurrentCover.js @@ -0,0 +1,61 @@ +const getNickname = require("../getNickname"); +const parseMention = require("../parseMention"); +const getFmUsername = require("./getFmUsername"); +const Discord = require('discord.js'); + +require("dotenv").config(); +module.exports = async function(userID, guild) { + let parse = parseMention(userID, guild) + let user = guild.members.cache.get(parse); + let nickname = getNickname(user, guild) + if(nickname == null){ + nickname = user.user.username; + } + let sendText = {text: "", embed: null} + let scrobble = {}; + const apiKey = process.env.LAST_FM_API_KEY; + let lastfmUsername = await getFmUsername(userID); + if(lastfmUsername != undefined){ + scrobble = await new Promise ((resolve, reject) => { + fetch(`https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=${lastfmUsername}&api_key=${apiKey}&format=json`) + .then(response => response.json()) + .then(data => { + let scrobble = {}; + let track; + try { + track = data.recenttracks.track[0]; + } catch (error) { + scrobble.error = true; + switch(data.error){ + case 6: + scrobble.errorMsg = "User not found. Use `fm set ` to set your last.fm username."; + break; + default: + scrobble.errorMsg = "Last.fm is probably having problems. Try again later."; + break; + } + resolve(scrobble); + } + scrobble.cover = track.image[3]["#text"]; + scrobble.artist = track.artist["#text"]; + scrobble.album = track.album["#text"]; + resolve(scrobble); + }) + .catch(error => { + console.error(error); + reject(error); + }); + }); + if(scrobble.error != null){ + sendText.text = scrobble.errorMsg; + return sendText; + } + const embed = new Discord.MessageEmbed() + .setTitle(`${scrobble.artist} - **${scrobble.album}**`) + .setImage(scrobble.cover) + sendText.embed = embed; + } else { + sendText.text = "You haven't set your last.fm username yet. Use `fm set ` to set it."; + } + return sendText; +} \ No newline at end of file