kulmapaikka-ircbot/plugins/pvm.js

101 lines
2.7 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
}
2019-11-20 20:28:11 +02:00
help () {
// | Command | Description
return '.pvm Kertoo päivän, nimipäivän ja muita tietoja'
}
2018-10-27 14:50:31 +03:00
test (input) {
var res = input.match(/^\.pvm$/i)
if (res) {
return true
}
return false
}
today () {
var today = new Date()
2021-11-30 00:38:28 +02:00
return (new Intl.DateTimeFormat('fi-FI', {day: 'numeric', month: 'numeric', timeZone: 'Europe/Helsinki'}).format(today))
2018-10-27 14:50:31 +03:00
}
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)
2021-11-30 00:38:28 +02:00
let sunrise = new Intl.DateTimeFormat('fi-FI', {hour: 'numeric', minute: 'numeric', timeZone: 'Europe/Helsinki'}).format(sunriseDate)
let sunset = new Intl.DateTimeFormat('fi-FI', {hour: 'numeric', minute: 'numeric', timeZone: 'Europe/Helsinki'}).format(sunsetDate)
2018-10-27 14:50:31 +03:00
const $ = cheerio.load(data[0])
let names = []
$('.text p').children('a').each(function (i, elem) {
2018-10-27 14:50:31 +03:00
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