81 lines
1.9 KiB
JavaScript
81 lines
1.9 KiB
JavaScript
var Promise = require('promise');
|
||
var requestPromise = require('./helpers/requestPromise.js');
|
||
var BasePlugin = require('./base.js');
|
||
var logger = require('winston');
|
||
|
||
class InstantAswer extends BasePlugin {
|
||
constructor(config) {
|
||
super(config);
|
||
this.name = 'InstantAswer';
|
||
}
|
||
test(input) {
|
||
var res = null;
|
||
if (res = input.match(/^\.wtf (.+)$/i)) {
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
getDDG(query) {
|
||
var urlArgs = {
|
||
q: query,
|
||
kp: -1,
|
||
skip_disambig: '0',
|
||
format: 'json'
|
||
};
|
||
|
||
let url = 'https://api.duckduckgo.com/';
|
||
var promise = requestPromise(url, urlArgs, {
|
||
'Accept': 'application/json',
|
||
});
|
||
|
||
return promise;
|
||
}
|
||
|
||
getAnswer(query) {
|
||
let that = this;
|
||
var promise = new Promise(function(resolve, reject) {
|
||
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) + '...';
|
||
} else {
|
||
text = response.AbstractText;
|
||
}
|
||
|
||
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);
|
||
} else {
|
||
reject();
|
||
}
|
||
}, reject);
|
||
});
|
||
return promise;
|
||
}
|
||
|
||
result(input) {
|
||
let that = this;
|
||
var resultPromise = new Promise(function(resultResolve, resultReject) {
|
||
var res = null;
|
||
if (res = input.match(/^\.wtf (.+)$/i)) {
|
||
let query = res[1]
|
||
that.getAnswer(query).then(str => {
|
||
resultResolve(str);
|
||
})
|
||
} else {
|
||
resultReject();
|
||
}
|
||
});
|
||
return resultPromise;
|
||
|
||
}
|
||
}
|
||
|
||
module.exports = InstantAswer;
|