From 100ba3b1f13e6ce44a9a5fa35143cb3c8af8d543 Mon Sep 17 00:00:00 2001 From: lanxu Date: Tue, 1 Sep 2015 22:44:55 +0300 Subject: [PATCH] Refactorization --- .hgignore | 1 + app.js | 458 ++++++++++------------------------------ appTest.js | 88 ++++++++ config.kulmapaikka.js | 67 ++++++ owmapi.js | 4 +- plugins/getCharacter.js | 40 ++++ plugins/getDice.js | 36 ++++ plugins/getUrl.js | 44 ++++ plugins/getWeather.js | 56 +++++ 9 files changed, 449 insertions(+), 345 deletions(-) create mode 100644 appTest.js create mode 100644 config.kulmapaikka.js create mode 100644 plugins/getCharacter.js create mode 100644 plugins/getDice.js create mode 100644 plugins/getUrl.js create mode 100644 plugins/getWeather.js diff --git a/.hgignore b/.hgignore index 19f6c52..e6869d7 100644 --- a/.hgignore +++ b/.hgignore @@ -10,3 +10,4 @@ deploy .tar.gz backup/ .log +config.js diff --git a/app.js b/app.js index 94d4042..669de71 100644 --- a/app.js +++ b/app.js @@ -1,76 +1,6 @@ -// IRC Bot -var config = { - irc: { - server: 'irc.elisa.fi', - nick: 'Ookami-dev', - channels: ['#kulmapaikka-dev'] - } -}; -var members = { - 'lanxu': { - user: /julankin$/, - host: /^jumi\.lut\.fi$/ - }, - 'asdfas': { - user: /asdfas$/, - host: /(.*)\.ssp\.fi$/ - }, - 'asdfas2': { - user: /Asdfas$/, - host: /(.*)\.elisa-mobile\.fi$/ - }, - 'cbd': { - user: /cbd$/, - host: /kapsi\.fi$/ - }, - 'fitzhood': { - user: /Fitzhood$/, - host: /(.*)ssp\.fi$/ - }, - 'mindflayer': { - user: /mindflaye$/, - host: /(.*)opintanner\.fi$/ - }, - 'pariah': { - user: /rautia$/, - host: /mozart\.cc\.tut\.fi$/ - }, - 'zoid': { - user: /jolaakso$/, - host: /kapsi\.fi$/ - }, - 'palin': { - user: /Palin$/, - host: /(.*)\.elisa-mobile\.fi$/ - }, - 'rootmer': { - user: /ror$/, - host: /(.*)\.inet\.fi$/ - }, - 'masaKapsi': { - user: /maruohon$/, - host: /kapsi\.fi$/ - }, - 'masaJumi': { - user: /maruohon$/, - host: /jumi\.lut\.fi$/ - }, - 'masaAura': { - user: /masa$/, - host: /(.*)\.ssp\.fi$/ - } -}; - +// General includes var irc = require('irc'); -var penaapi = require('./penaapi')(); var owmapi = require('./owmapi')(); - -var owmCityIds = { - Tampere: 634963, - Karinainen: 654059, - Lappeenranta: 648900 -}; - var iconCodeToText = { '01d': 'selkeää', '02d': 'puolipilvistä', @@ -90,305 +20,149 @@ var iconCodeToText = { '11n': 'ukkostaa', '13n': 'lumisadetta', '50n': 'sumua' - }; +// Load config +var config = require('./config'); -var throwStat = function() { - // Heittää 4 kertaa d6:n, tiputtaa heikoimman tuloksen ja laskee - // loput yhteen - - var throws = []; - var sum = 0; - for( var i = 0; i < 4; i++ ) { - var t = Math.floor(Math.random()*6)+1; - throws.push(t); - } - - throws.sort(); - throws.reverse(); - - var sum = 0; - for(var i = 0; i < 3; i++) { - sum += throws[i]; - } - - return sum; -}; - -var getDnDCharacter = function() { - var statPoints = 'DnD-statsit:'; - var total = 0; - for( var i = 0; i < 6; i++) { - var newStat = throwStat(); - statPoints += ' '; // erotetaan sanat toisistaan - statPoints += newStat; - total += Number(newStat); - } - statPoints += ' ('+total+')'; - return statPoints; -}; - -var getTemperatureString = function() { - var Promise = require('promise'); - var promise = new Promise(function(resolve, reject) { - - Promise.all([ - owmapi.getTemperatures(owmCityIds), - penaapi.getTemperatures() - ]).then(function(results) { - var resultString = ''; - // OWM - results[0].list.forEach(function(data) { - var city = data.name; - var temp = (data.main.temp-273.15).toFixed(1); - var code = data.weather[0].icon; - - resultString += '' + city + ' ('+temp+' °C, '+iconCodeToText[code]+'), '; - }); - - if(results[1].length > 0) { - var temp = Number(results[1][0].temp).toFixed(1); - resultString += 'Aura (' + temp + ' °C)'; - } - - resolve(resultString); - - }); - }); - return promise; -}; -var getDiceString = function(numThrows, sides) { - - var total = 0; - var totalThrows = []; - - numThrows = Number(numThrows); - sides = Number(sides); - - if(numThrows === 0 || sides === 0) { - return 'Tyhjää ei voi heittää'; - } - - if(numThrows > 100) { - return 'Ei jaksa...'; - } - - for(var a = 0; a < numThrows; a++) { - var t = Math.floor(Math.random()*sides)+1; - totalThrows.push(t); - total += t; - } - - var resultString = ''; - totalThrows.forEach(function(value) { - resultString += value + ', '; - }); - - resultString = resultString.substring(0, resultString.length - 2); - resultString += ' (yhteensä: ' + total + '. '+ (total/numThrows).toFixed(2) + ' per heitto)'; - - return resultString; -}; -var text = 'Hei! https://youtu.be/TLW6eTV8F_I hienoo'; -var text = 'Hei! https://www.youtube.com/watch?v=AMlf-KXVOsQ hienoo'; -var text = 'Hei! https://www.youtu.be/TLW6eTV8F_I https://www.youtube.com/watch?v=AMlf-KXVOsQ hienoo'; -var regExp = /http(s)?:\/\/(www\.)?((youtu\.be\/([a-zA-Z0-9_-]*))|(youtube\.com\/watch\?v=([a-zA-Z0-9_-]*)))/; - -var res = text.match(regExp); - -console.log(res[5]); -console.log(res[7]); - -/* -var getYoutubeTitle = function(query) { - var google = require('googleapis'); - var apikey = 'AIzaSyBCLnmbmjjHvfScHNj8PBqINjoyLTAXEjg'; - - var youtube = google.youtube('v3'); - var params = { - part: 'snippet, statistics', - q: 'https://www.youtube.com/watch?v=XNwKqvCZ4kU', - type: 'video', - key: apikey - }; - - var result = youtube.search.list(params, function(err, resp) { - if (err) { - console.log('An error occured', err); - return; - } - - console.log(resp.items[0].snippet.title); - console.log(resp.items[0].snippet.channelTitle); - - - console.log(resp); - }); - - console.log(result); - //var resultString = 'Title: '+; -}; -*/ - -//console.log('YouTube!', getYoutubeTitle()); - - -/* - getTemperatureString().then(function(result) { - console.log(result); - }); - */ - -/* - var res = null; - var message= '.heita 4d6'; - if (res = message.match(/^\.heita ([0-9]+)d([0-9]+)$/i)) { - console.log(getDiceString(res[1], res[2])); - } - */ -/* - var message = '.saa Tampere'; var res = null; - if (res = message.match(/^\.saa ([^0-9 ]+)$/i)) { - console.log('kaupunki', res[1]); - owmapi.getTemperature(res[1]).then(function(result) { - console.log(result); - - if(result.cod === '404') { - console.log('Eioo'); - } else { - var city = result.name; - var country = result.sys.country; - var temp = (result.main.temp-273.15).toFixed(1); - var sunriseDate = new Date(result.sys.sunrise*1000); - var sunsetDate = new Date(result.sys.sunset*1000); - - var sunrise = sunriseDate.getHours() + '.' + sunriseDate.getMinutes(); - var sunset = sunsetDate.getHours() + '.' + sunsetDate.getMinutes(); - - var humidity = result.main.humidity; - var pressure = result.main.pressure; - - console.log(city, temp, country, sunrise, sunset, humidity, pressure); - } - }, function(error) { - console.log('fas',error); - }); - } - -*/ +// Load plugins +var getTemperatureString = require('./plugins/getWeather')(); +var getDnDCharacter = require('./plugins/getCharacter')(); +var getDiceString = require('./plugins/getDice')(); +var getUrlString = require('./plugins/getUrl')(); +// Start client var client = new irc.Client(config.irc.server, config.irc.nick, { debug: true, channels: config.irc.channels, }); -client.addListener('message', function (from, to, message) { + +var handleMessage = function(from, to, message) { console.log(from + ' => ' + to + ': ' + message); - if (to.match(/^[#&]/)) { - // channel message - if (message.match(/^\.sää$/i) || message.match(/^\.saa$/i)) { - getTemperatureString().then(function(str) { - client.say(to, 'Sää: ' + str); - }); - } - var res = null; - if (res = message.match(/^\.s(ää|aa) ([^0-9]+)$/i)) { - //console.log('kaupunki', res[1]); - owmapi.getTemperature(res[2]).then(function(result) { - //console.log(result); - if(result.cod === '404') { - //console.log('Eioo: ' + res[1]); - client.say(to, 'Eioo: ' + res[2]); - } else { - var city = result.name; - var country = result.sys.country; - var temp = (result.main.temp-273.15).toFixed(1); - var code = result.weather[0].icon; - var sunriseDate = new Date(result.sys.sunrise*1000); - var sunsetDate = new Date(result.sys.sunset*1000); + //if (to.match(/^[#&]/)) { + // channel message + if (message.match(/^\.sää$/i) || message.match(/^\.saa$/i)) { + getTemperatureString(config.owmCityIds).then(function(str) { + client.say(to, 'Sää: ' + str); + }); + } - var sunrise = sunriseDate.getHours() + '.' + sunriseDate.getMinutes(); - var sunset = sunsetDate.getHours() + '.' + sunsetDate.getMinutes(); + var res = null; - var humidity = result.main.humidity; - var pressure = result.main.pressure; + // Weather + if (res = message.match(/^\.s(ää|aa) ([^0-9]+)$/i)) { + //console.log('kaupunki', res[1]); + owmapi.getTemperature(res[2]).then(function(result) { + //console.log(result); + if(result.cod === '404') { + //console.log('Eioo: ' + res[1]); + client.say(to, 'Eioo: ' + res[2]); + } else { + var city = result.name; + var country = result.sys.country; + var temp = (result.main.temp-273.15).toFixed(1); + var code = result.weather[0].icon; + var sunriseDate = new Date(result.sys.sunrise*1000); + var sunsetDate = new Date(result.sys.sunset*1000); - var windspeed = result.wind.speed; + var sunrise = sunriseDate.getHours() + '.' + sunriseDate.getMinutes(); + var sunset = sunsetDate.getHours() + '.' + sunsetDate.getMinutes(); - //console.log(city, temp, code); - client.say(to, 'Sää: '+city+', '+country+' ('+temp+' °C, '+ iconCodeToText[code] +', ilmankosteus: '+humidity+' %, ilmanpaine: '+pressure+' hPa, tuulen nopeus: '+windspeed+' m/s)'); - } - }, function(error) { - console.log('ERROR ',error); - client.say(to, 'Oho! Tapahtui virhe. Yritä myöhemmin uudelleen...'); - }); - } + var humidity = result.main.humidity; + var pressure = result.main.pressure; - if (res = message.match(/^\.heit(a|ä) ([0-9]+)d([0-9]+)$/i)) { - var th = getDiceString(res[2], res[3]); - client.say(to, 'Heitettiin: '+th); - } - if (res = message.match(/^\.luohahmo$/i)) { - var character = getDnDCharacter(); - client.say(to, ''+character); - } - if (message.match(/^\.heit(a|ä) voltti homo$/i)) { - client.say(to, 'steam://run/1250'); - } - if (message.match(/^\.op$/i)) { - client.send('NAMES', to); - } + var windspeed = result.wind.speed; - if (res = message.match(/http(s)?:\/\/(www\.)?((youtu\.be\/([a-zA-Z0-9_-]*))|(youtube\.com\/watch\?v=([a-zA-Z0-9_-]*)))/)) { - - var googletin = require('./googleapi.js')(); - console.log(res); - var id = res[7]; - if(typeof id === 'undefined') { - id = res[5]; + client.say(to, 'Sää: '+city+', '+country+' ('+temp+' °C, '+ iconCodeToText[code] +', ilmankosteus: '+humidity+' %, ilmanpaine: '+pressure+' hPa, tuulen nopeus: '+windspeed+' m/s)'); } - if(typeof id !== 'undefined') { - - + }, function(error) { + console.log('ERROR ',error); + client.say(to, 'Oho! Tapahtui virhe. Yritä myöhemmin uudelleen...'); + }); + } + + // Create Character + if (res = message.match(/^\.luohahmo$/i)) { + var character = getDnDCharacter(); + client.say(to, ''+character); + } + + // Throw dice + if (res = message.match(/^\.heit(a|ä) ([0-9]+)d([0-9]+)$/i)) { + var th = getDiceString(res[2], res[3]); + client.say(to, 'Heitettiin: '+th); + } + if (message.match(/^\.heit(a|ä) voltti homo$/i)) { + client.say(to, 'steam://run/1250'); + } + + // Op + if (message.match(/^\.op$/i)) { + client.send('NAMES', to); + } + + // Url specific handling + if (res = message.match(/http(s)?:\/\/(www\.)?((youtu\.be\/([a-zA-Z0-9_-]*))|(youtube\.com\/watch\?v=([a-zA-Z0-9_-]*)))/)) { + + var googletin = require('./googleapi.js')(); + console.log(res); + var id = res[7]; + if(typeof id === 'undefined') { + id = res[5]; + } + if(typeof id !== 'undefined') { googletin.getYoutubeVideoById(id).then(function(result) { var resultString = 'Youtube: '; resultString += result.title; resultString += ', esittäjänä ' + result.channelTitle; - var rotten = (Number(result.statistics.likeCount)/(Number(result.statistics.likeCount)+Number(result.statistics.dislikeCount))).toFixed(2); - - //resultString += ' ('+result.duration+')'; resultString += ' ('+result.duration+', '+ result.statistics.viewCount +' katselukertaa, '+rotten*100+'% tykätty, '+result.url+' )'; - //console.log(resultString); client.say(to, ''+resultString); }, function(err) { console.log('error', err); client.say(to, 'Youtube: jokin meni pieleen...'); }); - } } - - if (res = message.match(/^\.youtube (.+)$/i)) { + } else if (res = message.match(/^\.youtube (.+)$/i)) { - var googletin = require('./googleapi.js')(); - console.log(res); - googletin.getYoutubeVideo(res[1]).then(function(result) { - var resultString = 'Youtube: '; - resultString += result.title; - resultString += ', esittäjänä ' + result.channelTitle; + var googletin = require('./googleapi.js')(); + console.log(res); + googletin.getYoutubeVideo(res[1]).then(function(result) { + var resultString = 'Youtube: '; + resultString += result.title; + resultString += ', esittäjänä ' + result.channelTitle; - var rotten = (Number(result.statistics.likeCount)/(Number(result.statistics.likeCount)+Number(result.statistics.dislikeCount))).toFixed(2); + var rotten = (Number(result.statistics.likeCount)/(Number(result.statistics.likeCount)+Number(result.statistics.dislikeCount))).toFixed(2); - //resultString += ' ('+result.duration+')'; - resultString += ' ('+result.duration+', '+ result.statistics.viewCount +' katselukertaa, '+rotten*100+'% tykätty, '+result.url+' )'; - //console.log(resultString); - client.say(to, ''+resultString); - }, function(err) { - console.log('error'); - client.say(to, 'Youtube: jokin meni pieleen...'); - }); - } + //resultString += ' ('+result.duration+')'; + resultString += ' ('+result.duration+', '+ result.statistics.viewCount +' katselukertaa, '+rotten*100+'% tykätty, '+result.url+' )'; + //console.log(resultString); + client.say(to, ''+resultString); + }, function(err) { + console.log('error'); + client.say(to, 'Youtube: jokin meni pieleen...'); + }); + } else if (res = message.match(/http(s)?:\/\/([^ ]*)/i)) { + var url = res[0]; + getUrlString(url).then(function(str) { + client.say(to, 'Otsikko: ' + str); + }); + } else { + // Do nothing? :D + } +}; + + +client.addListener('message', function (from, to, message) { + if(String(from) !== String(config.irc.nick)) { + handleMessage(from, to, message); + } +}); + +client.addListener('pm', function (from, message) { + if(String(from) !== String(config.irc.nick)) { + handleMessage(from, from, message); } }); @@ -396,6 +170,7 @@ client.addListener('join', function(channel, who) { client.whois(who, function(result) { console.log(result); + var members = config.members; for(var memberNick in members) { var member = members[memberNick]; @@ -406,9 +181,6 @@ client.addListener('join', function(channel, who) { } }); - setTimeout(function() { - // client.say(channel, 'Moi ' + who + '!'); - }, 4000); }); client.addListener('error', function(message) { @@ -416,20 +188,18 @@ client.addListener('error', function(message) { }); client.addListener('names', function(channel, nicks) { - console.log('names', channel, nicks); if(typeof nicks[config.irc.nick] !== 'undefined' && nicks[config.irc.nick] === '@') { // go through nicks for(var nick in nicks) { if(nicks[nick] !== '@') { client.whois(nick, function(result) { + var members = config.members; for(var memberNick in members) { var member = members[memberNick]; if(result.host.match(member.host) && result.user.match(member.user)) { - console.log('testing', channel, result.nick); client.send('MODE', channel, '+o', result.nick); } - } }); } diff --git a/appTest.js b/appTest.js new file mode 100644 index 0000000..e260d99 --- /dev/null +++ b/appTest.js @@ -0,0 +1,88 @@ + +var text = 'Hei! https://youtu.be/TLW6eTV8F_I hienoo'; +var text = 'Hei! https://www.youtube.com/watch?v=AMlf-KXVOsQ hienoo'; +var text = 'Hei! https://www.youtu.be/TLW6eTV8F_I https://www.youtube.com/watch?v=AMlf-KXVOsQ hienoo'; +var regExp = /http(s)?:\/\/(www\.)?((youtu\.be\/([a-zA-Z0-9_-]*))|(youtube\.com\/watch\?v=([a-zA-Z0-9_-]*)))/; + +var res = text.match(regExp); + +console.log(res[5]); +console.log(res[7]); + +/* +var getYoutubeTitle = function(query) { + var google = require('googleapis'); + var apikey = 'AIzaSyBCLnmbmjjHvfScHNj8PBqINjoyLTAXEjg'; + + var youtube = google.youtube('v3'); + var params = { + part: 'snippet, statistics', + q: 'https://www.youtube.com/watch?v=XNwKqvCZ4kU', + type: 'video', + key: apikey + }; + + var result = youtube.search.list(params, function(err, resp) { + if (err) { + console.log('An error occured', err); + return; + } + + console.log(resp.items[0].snippet.title); + console.log(resp.items[0].snippet.channelTitle); + + + console.log(resp); + }); + + console.log(result); + //var resultString = 'Title: '+; +}; +*/ + +//console.log('YouTube!', getYoutubeTitle()); + + +/* + getTemperatureString().then(function(result) { + console.log(result); + }); + */ + +/* + var res = null; + var message= '.heita 4d6'; + if (res = message.match(/^\.heita ([0-9]+)d([0-9]+)$/i)) { + console.log(getDiceString(res[1], res[2])); + } + */ +/* + var message = '.saa Tampere'; var res = null; + if (res = message.match(/^\.saa ([^0-9 ]+)$/i)) { + console.log('kaupunki', res[1]); + owmapi.getTemperature(res[1]).then(function(result) { + console.log(result); + + if(result.cod === '404') { + console.log('Eioo'); + } else { + var city = result.name; + var country = result.sys.country; + var temp = (result.main.temp-273.15).toFixed(1); + var sunriseDate = new Date(result.sys.sunrise*1000); + var sunsetDate = new Date(result.sys.sunset*1000); + + var sunrise = sunriseDate.getHours() + '.' + sunriseDate.getMinutes(); + var sunset = sunsetDate.getHours() + '.' + sunsetDate.getMinutes(); + + var humidity = result.main.humidity; + var pressure = result.main.pressure; + + console.log(city, temp, country, sunrise, sunset, humidity, pressure); + } + }, function(error) { + console.log('fas',error); + }); + } + +*/ \ No newline at end of file diff --git a/config.kulmapaikka.js b/config.kulmapaikka.js new file mode 100644 index 0000000..bbcfab2 --- /dev/null +++ b/config.kulmapaikka.js @@ -0,0 +1,67 @@ +var config = { + irc: { + server: 'irc.elisa.fi', + nick: 'Ookami-dev', + channels: ['#kulmapaikka-dev'] + }, + members: { + 'lanxu': { + user: /julankin$/, + host: /^jumi\.lut\.fi$/ + }, + 'asdfas': { + user: /asdfas$/, + host: /(.*)\.ssp\.fi$/ + }, + 'asdfas2': { + user: /Asdfas$/, + host: /(.*)\.elisa-mobile\.fi$/ + }, + 'cbd': { + user: /cbd$/, + host: /kapsi\.fi$/ + }, + 'fitzhood': { + user: /Fitzhood$/, + host: /(.*)ssp\.fi$/ + }, + 'mindflayer': { + user: /mindflaye$/, + host: /(.*)opintanner\.fi$/ + }, + 'pariah': { + user: /rautia$/, + host: /mozart\.cc\.tut\.fi$/ + }, + 'zoid': { + user: /jolaakso$/, + host: /kapsi\.fi$/ + }, + 'palin': { + user: /Palin$/, + host: /(.*)\.elisa-mobile\.fi$/ + }, + 'rootmer': { + user: /ror$/, + host: /(.*)\.inet\.fi$/ + }, + 'masaKapsi': { + user: /maruohon$/, + host: /kapsi\.fi$/ + }, + 'masaJumi': { + user: /maruohon$/, + host: /jumi\.lut\.fi$/ + }, + 'masaAura': { + user: /masa$/, + host: /(.*)\.ssp\.fi$/ + }, + }, + owmCityIds: { + Tampere: 634963, + Karinainen: 654059, + Lappeenranta: 648900, + Helsinki: 658225 + } +}; \ No newline at end of file diff --git a/owmapi.js b/owmapi.js index 2ce41e5..948abdb 100644 --- a/owmapi.js +++ b/owmapi.js @@ -1,6 +1,7 @@ var request = require('request'); var Promise = require('promise'); + var requestPromise = function(url, urlArgs) { var promise = new Promise(function(resolve, reject) { request({ @@ -19,8 +20,9 @@ var requestPromise = function(url, urlArgs) { }; + /** - * Pena API module. + * weather API module. * @module kulmapaikka/owmapi */ module.exports = function(config) { diff --git a/plugins/getCharacter.js b/plugins/getCharacter.js new file mode 100644 index 0000000..55176c0 --- /dev/null +++ b/plugins/getCharacter.js @@ -0,0 +1,40 @@ +/** + * Based on Cb's get character code + */ +module.exports = function(config) { + var throwStat = function() { + // Heittää 4 kertaa d6:n, tiputtaa heikoimman tuloksen ja laskee + // loput yhteen + + var throws = []; + var sum = 0; + for( var i = 0; i < 4; i++ ) { + var t = Math.floor(Math.random()*6)+1; + throws.push(t); + } + + throws.sort(); + throws.reverse(); + + var sum = 0; + for(var i = 0; i < 3; i++) { + sum += throws[i]; + } + + return sum; + }; + + var getDnDCharacter = function() { + var statPoints = 'DnD-statsit:'; + var total = 0; + for( var i = 0; i < 6; i++) { + var newStat = throwStat(); + statPoints += ' '; // erotetaan sanat toisistaan + statPoints += newStat; + total += Number(newStat); + } + statPoints += ' ('+total+')'; + return statPoints; + }; + return getDnDCharacter; +}; \ No newline at end of file diff --git a/plugins/getDice.js b/plugins/getDice.js new file mode 100644 index 0000000..700663f --- /dev/null +++ b/plugins/getDice.js @@ -0,0 +1,36 @@ +module.exports = function(config) { + var getDiceString = function(numThrows, sides) { + + var total = 0; + var totalThrows = []; + + numThrows = Number(numThrows); + sides = Number(sides); + + if(numThrows === 0 || sides === 0) { + return 'Tyhjää ei voi heittää'; + } + + if(numThrows > 100) { + return 'Ei jaksa...'; + } + + for(var a = 0; a < numThrows; a++) { + var t = Math.floor(Math.random()*sides)+1; + totalThrows.push(t); + total += t; + } + + var resultString = ''; + totalThrows.forEach(function(value) { + resultString += value + ', '; + }); + + resultString = resultString.substring(0, resultString.length - 2); + resultString += ' (yhteensä: ' + total + '. '+ (total/numThrows).toFixed(2) + ' per heitto)'; + + return resultString; + }; + + return getDiceString; +}; \ No newline at end of file diff --git a/plugins/getUrl.js b/plugins/getUrl.js new file mode 100644 index 0000000..a535bd9 --- /dev/null +++ b/plugins/getUrl.js @@ -0,0 +1,44 @@ +var Promise = require('promise'); +var request = require('request'); + +var requestPromise = function (url, urlArgs) { + var promise = new Promise(function(resolve, reject) { + request({ + url: url, + qs: urlArgs, + json: false + }, function(error, response, body) { + if(!error && response.statusCode == 200) { + resolve(body); + } else { + reject(error); + } + }); + }); + return promise; +}; + +module.exports = function(config) { + // http://stackoverflow.com/questions/13087888/getting-the-page-title-from-a-scraped-webpage + var getTitle = function(url) { + var urlOpts = {host: url, path: '/', port: '80'}; + + var re = /(<\s*title[^>]*>(.+?)<\s*\/\s*title)>/gi; + var urlArgs = {}; + + var promise = new Promise(function(resolve, reject) { + var urlPromise = requestPromise(url, urlArgs); + urlPromise.then(function(data) { + var match = re.exec(data); + if (match && match[2]) { + resolve(match[2]); + } else { + reject(); + } + }); + }); + return promise; + }; + + return getTitle; +}; \ No newline at end of file diff --git a/plugins/getWeather.js b/plugins/getWeather.js new file mode 100644 index 0000000..d01e1fc --- /dev/null +++ b/plugins/getWeather.js @@ -0,0 +1,56 @@ +var penaapi = require('./../penaapi')(); +var owmapi = require('./../owmapi')(); +var Promise = require('promise'); + +var iconCodeToText = { + '01d': 'selkeää', + '02d': 'puolipilvistä', + '03d': 'pilvistä', + '04d': 'pilvipeite rakoilee', + '09d': 'sadekuuroja', + '10d': 'vesisadetta', + '11d': 'ukkostaa', + '13d': 'lumisadetta', + '50d': 'sumua', + '01n': 'selkeää', + '02n': 'puolipilvistä', + '03n': 'pilvistä', + '04n': 'pilvipeite rakoilee', + '09n': 'sadekuuroja', + '10n': 'vesisadetta', + '11n': 'ukkostaa', + '13n': 'lumisadetta', + '50n': 'sumua' +}; +module.exports = function(config) { + + var getTemperatureString = function(owmCityIds) { + var promise = new Promise(function(resolve, reject) { + + Promise.all([ + owmapi.getTemperatures(owmCityIds), + penaapi.getTemperatures() + ]).then(function(results) { + var resultString = ''; + // OWM + results[0].list.forEach(function(data) { + var city = data.name; + var temp = (data.main.temp-273.15).toFixed(1); + var code = data.weather[0].icon; + + resultString += '' + city + ' ('+temp+' °C, '+iconCodeToText[code]+'), '; + }); + + if(results[1].length > 0) { + var temp = Number(results[1][0].temp).toFixed(1); + resultString += 'Aura (' + temp + ' °C)'; + } + + resolve(resultString); + + }); + }); + return promise; + }; + return getTemperatureString; +}; \ No newline at end of file