var Promise = require('promise') var requestPromise = require('./helpers/requestPromise.js') var BasePlugin = require('./base.js') class InstantAswer extends BasePlugin { constructor (config) { super(config) this.name = 'InstantAswer' } help () { // | Command | Description return '.wtf Etsii vastauksen annetulle termille' } test (input) { if (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(new Error()) } }, reject) }) return promise } result (input) { let that = this var resultPromise = new Promise(function (resolve, reject) { var res = input.match(/^\.wtf (.+)$/i) if (res !== null) { let query = res[1] that.getAnswer(query).then(str => { resolve(str) }) } else { reject(new Error()) } }) return resultPromise } } module.exports = InstantAswer