Last active
September 30, 2015 16:37
-
-
Save logemann/7391a1ba17ca07f177ff to your computer and use it in GitHub Desktop.
Weather Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module['exports'] = function weather(hook) { | |
console.log("Starting Hook: "+hook.params.hook); | |
var request = require('request'); | |
var store = hook.datastore; | |
var url = "http://api.openweathermap.org/data/2.5/find?q=Osnabrueck&units=metric&lang=de"; | |
var keyName = hook.params.hook+"-lastRunDateMillis"; | |
store.get(keyName, function(error, result) { | |
if(error) { | |
hook.res.end("Fucked up :"+error.message); | |
} else { | |
var now = new Date(); | |
var lastRun = new Date(result); | |
if(now.sameDay(lastRun)) { | |
hook.res.end("Job already fired today"); | |
} else { | |
var millisecsSince1970 = now.getTime(); | |
store.set(keyName,millisecsSince1970 , function(error, result) { | |
if(error) { | |
console.log(error); | |
hook.res.end("Error setting var in DS", error.message); | |
} | |
request.get(url, function(err, res, body){ | |
if (err) { | |
hook.res.end(err.messsage); | |
} else { | |
console.log("Weather Data fetched."); | |
} | |
var jsonRequest = createJson(body); | |
request({ | |
method: 'POST', | |
json: true, | |
body: jsonRequest, | |
uri: hook.env.SLACK_WEBHOOK_URL}, function(err, res, body) { | |
if(err) { | |
hook.res.end("Fucked up :"+err); | |
} else { | |
hook.res.end("normally ended"); | |
} | |
}); | |
}); | |
}); | |
} | |
} | |
}) | |
}; | |
function createJson(json) { | |
var json = JSON.parse(json); | |
return { | |
"channel": "#general", | |
"username": "Wetter", | |
"icon_emoji": ":sunny:", | |
"attachments": [{ | |
"fallback": "Wetter heute: "+json.list[0].weather[0].description, | |
"color": "#36a64f", | |
"author_name": "Wetter heute:", | |
"title": json.list[0].weather[0].description, | |
"title_link": "http://www.wetter.com/wetter_aktuell/aktuelles_wetter/deutschland/osnabrueck/DE0008003.html", | |
"text": "", | |
"fields": [{ | |
"title": "Temp. Min:", | |
"value": json.list[0].main.temp_min, | |
"short": true | |
}, { | |
"title": "Temp. Max:", | |
"value": json.list[0].main.temp_max, | |
"short": true | |
}, { | |
"title": "Luftfeuchte", | |
"value": json.list[0].main.humidity + "%", | |
"short": true | |
}, { | |
"title": "Windgeschw.", | |
"value": json.list[0].wind.speed + " Knoten", | |
"short": true | |
}] | |
}] | |
} | |
} | |
Date.prototype.sameDay = function(d) { | |
return this.getFullYear() === d.getFullYear() | |
&& this.getDate() === d.getDate() | |
&& this.getMonth() === d.getMonth(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment