kulmapaikka-ircbot/plugins/pvm.js

99 lines
2.4 KiB
JavaScript
Raw Normal View History

2018-10-27 14:50:31 +03:00
var Promise = require('promise')
var requestPromise = require('./helpers/requestPromise.js')
var BasePlugin = require('./base.js')
var cheerio = require('cheerio')
class Pwm extends BasePlugin {
constructor (config) {
super(config)
this.name = 'Pvm'
this.apikey = config.keys.owm.apiKey // owm for sunrise
}
test (input) {
var res = input.match(/^\.pvm$/i)
if (res) {
return true
}
return false
}
today () {
var today = new Date()
var month = today.getMonth() + 1
var day = today.getDate()
var dateString = day + '.' + month + '.'
return dateString
}
getWeather (city, code) {
var language = 'fi'
var urlArgs = {
'q': city,
'lang': language,
'APPID': this.apikey
}
var url = 'http://api.openweathermap.org/data/2.5/weather'
var promise = requestPromise(url, urlArgs)
return promise
}
getNimipaiva () {
let dateString = this.today()
var urlArgs = {}
var url = 'http://nimipäivä.fi/' + dateString + '/'
var promise = requestPromise(url, urlArgs, {
'Accept': 'application/json'
}, true)
return promise
}
getAllData () {
return Promise.all([
this.getNimipaiva(),
this.getWeather('Helsinki')
])
}
result (input) {
var that = this
var resultPromise = new Promise(function (resolve, reject) {
var res = input.match(/^\.pvm$/i)
if (res) {
that.getAllData().then(function (data) {
// console.log(data)
let weather = data[1]
if (weather.cod === '404') {
reject(new Error('Eioo'))
return
}
let sunriseDate = new Date(Number(weather.sys.sunrise) * 1000)
let sunsetDate = new Date(Number(weather.sys.sunset) * 1000)
let sunrise = sunriseDate.getHours() + '.' + sunriseDate.getMinutes()
let sunset = sunsetDate.getHours() + '.' + sunsetDate.getMinutes()
const $ = cheerio.load(data[0])
let names = []
let names_ = $('.text p').children('a').each(function (i, elem) {
names.push($(this).text())
})
let text = 'Pvm: Tänään on ' + that.today() + ' ja nimipäivää viettävät ' + names.join(', ') + '. Aurinko nousee ' + sunrise + ' ja laskee ' + sunset + '.'
resolve(text)
}, function (error) {
reject(error)
})
}
})
return resultPromise
}
}
module.exports = Pwm