Skip to content

Instantly share code, notes, and snippets.

@himynameisdave
Created March 16, 2016 03:11
Show Gist options
  • Save himynameisdave/4b81af728f74841fa0f0 to your computer and use it in GitHub Desktop.
Save himynameisdave/4b81af728f74841fa0f0 to your computer and use it in GitHub Desktop.
Microservice that tweets my most played song each week
module.exports = function songOfTheWeek(hook) {
var req = require("request-promise");
var Twitter = require('twitter');
var lastFmUrl = "http://ws.audioscrobbler.com/2.0/?method=user.getweeklytrackchart&user=himynameisdave9&api_key="+hook.env.sotw_lastfm+"&format=json";
var client = new Twitter({
consumer_key: hook.env.sotw_ckey,
consumer_secret: hook.env.sotw_csecret,
access_token_key: hook.env.sotw_atkey,
access_token_secret: hook.env.sotw_atsecret
});
var isTweetTooLong = function(tweetContent){ return tweetContent.length > 106; };
var getRandom = function(arr){ return arr[Math.floor(Math.random()*arr.length)]};
var craftTweet = function( song, artist, plays, url ) {
var playSynonyms = ["played", "played", "spun", "bumped"]; // doubled played for extra likelyhood
var songSynonyms = ["song", "song", "track", "jam"];
var atWith = ["at", "with"];
var potentialTweets = [
"My most "+getRandom(playSynonyms)+" "+getRandom(songSynonyms)+" of the past week is '"+song+"' by "+artist+", "+getRandom(atWith)+" "+plays+" plays: ",
"This week I "+getRandom(playSynonyms)+" "+artist+"'s '"+song+"' "+plays+" times: ",
"My top "+getRandom(songSynonyms)+" of the week is '"+song+"' by "+artist+" "+getRandom(atWith)+" "+plays+" plays: ",
"Check out my most "+getRandom(playSynonyms)+" "+getRandom(songSynonyms)+" this week, "+artist+"'s '"+song+"' "
];
var content = getRandom(potentialTweets);
// try 10 times to correct length before moving on
for(i=0;i<10;i++){
if ( isTweetTooLong(content) ){
content = getRandom(potentialTweets);
}
}
return getRandom(potentialTweets)+url+" #goodtrack";
};
// Promisifies tweeting
var tweet = function( tweetContent ) {
return new Promise( function(res, rej){
client.post('statuses/update', { status: tweetContent }, function(e, tweet, response){
if (e) return rej(e);
res("Successfully tweeted the song of the week!");
});
});
};
req(lastFmUrl)
.then(function(lastfmData){
var topSong = JSON.parse(lastfmData).weeklytrackchart.track[0];
var tweetContent = craftTweet( topSong.name, topSong.artist['#text'], topSong.playcount, topSong.url );
return tweet(tweetContent);
})
.then(function(response){
console.log(response);
hook.res.end(JSON.stringify({ message: response }, true, 2))
})
.catch(function(e){
console.log(e);
hook.res.end(JSON.stringify(e, true, 2));
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment