kulmapaikka-ircbot/plugins/instantanswer.js

77 lines
1.8 KiB
JavaScript
Raw Normal View History

var Promise = require('promise')
var requestPromise = require('./helpers/requestPromise.js')
var BasePlugin = require('./base.js')
2018-04-29 17:37:07 +03:00
class InstantAswer extends BasePlugin {
constructor (config) {
super(config)
this.name = 'InstantAswer'
2018-04-29 17:37:07 +03:00
}
test (input) {
if (input.match(/^\.wtf (.+)$/i)) {
return true
2018-04-29 17:37:07 +03:00
}
return false
2018-04-29 17:37:07 +03:00
}
getDDG (query) {
2018-04-29 17:37:07 +03:00
var urlArgs = {
q: query,
kp: -1,
skip_disambig: '0',
format: 'json'
}
2018-04-29 17:37:07 +03:00
let url = 'https://api.duckduckgo.com/'
var promise = requestPromise(url, urlArgs, {
'Accept': 'application/json'
})
2018-04-29 17:37:07 +03:00
return promise
2018-04-29 17:37:07 +03:00
}
getAnswer (query) {
let that = this
var promise = new Promise(function (resolve, reject) {
2018-04-29 17:37:07 +03:00
that.getDDG(query).then((response) => {
var str = ''
if (response.AbstractText !== '') {
var text = ''
if (response.AbstractText.length > 350) {
text = response.AbstractText.substring(0, 350 - response.AbstractURL.length) + '...'
2018-04-29 17:37:07 +03:00
} else {
text = response.AbstractText
2018-04-29 17:37:07 +03:00
}
str = 'Vastaus: ' + text + '" | ' + response.AbstractURL
resolve(str)
} else if (response.RelatedTopics.length > 0) {
str = 'Vastaus: "' + response.RelatedTopics[0].Text + '" | ' + response.RelatedTopics[0].FirstURL
resolve(str)
2018-04-29 17:37:07 +03:00
} else {
reject(new Error())
2018-04-29 17:37:07 +03:00
}
}, reject)
})
return promise
2018-04-29 17:37:07 +03:00
}
result (input) {
let that = this
var resultPromise = new Promise(function (resolve, reject) {
var res = input.match(/^\.wtf (.+)$/i)
if (res !== null) {
2018-04-29 17:37:07 +03:00
let query = res[1]
that.getAnswer(query).then(str => {
resolve(str)
2018-04-29 17:37:07 +03:00
})
} else {
reject(new Error())
2018-04-29 17:37:07 +03:00
}
})
return resultPromise
2018-04-29 17:37:07 +03:00
}
}
module.exports = InstantAswer