diff --git a/scripts/wolfram.coffee b/scripts/wolfram.coffee index b02d9d0..611839a 100644 --- a/scripts/wolfram.coffee +++ b/scripts/wolfram.coffee @@ -1,31 +1,55 @@ # Description: # accede a wolfram alpha # -# Dependencies: -# "wolfram":"0.3.1" -# # Configuration: # WOLFRAM_API_KEY - self explanatory # # Commands -# hubot wolfram/wfa/quanto fa/compute ... - pone la domanda a Wolfram Alpha +# hubot wolfram/wfa/quanto fa/calcola/compute ... - pone la domanda a Wolfram Alpha # # Author: # Enrico Fasoli (fazo96) # -Wolfram = require 'wolfram' +cheerio = require 'cheerio' module.exports = (robot) -> - robot.respond /(?:quanto fa|compute|wfa|wolfram) (.+)/i, (res) -> - unless process.env.WOLFRAM_API_KEY + robot.wquery = (input, key, callback) -> + q = encodeURIComponent input + url = 'http://api.wolframalpha.com/v2/query?input=' + q + '&appid=' + key + robot.http(url).get() (err, res, body) -> + if err then return callback err, {} + + $ = cheerio.load body, xmlMode: true + if $('queryresult').attr('error') == 'true' + return callback $('error').find('msg').text(), {} + + pods = ($('pod').map (_, pod) -> + title: $(pod).attr 'title' + primary: $(pod).attr('primary')? + subpods: ($('subpod', $ pod).map (_, subpod) -> + title: $(subpod).attr 'title' + value: $('plaintext', $ subpod).text() + image: $('img', $ subpod).attr 'src' + ).get() + ).get() + + if pods.length + callback null, pods + else + callback 'la risposta da wolfram non è valida', [] + + robot.respond /(?:calcola|quanto fa|compute|wfa|wolfram) (.+)/i, (res) -> + wait = ['chiedo a wolfy', 'dammi un attimo', 'sto pensando', + 'fammi fare due conti', 'chiedo a wolfram'] + key = process.env.WOLFRAM_API_KEY + if not key return res.send 'non ho le chiavi per Wolfram Alpha :(' - wolfram = Wolfram.createClient process.env.WOLFRAM_API_KEY - res.send 'Contattando Wolfram Alpha...' - wolfram.query res.match[1], (err, result) -> - if err then return res.send err - unless result?.slice? - return res.send 'invalid response from Wolfram Alpha' + + res.send (res.random wait) + '...' + robot.wquery res.match[1], key, (err, result) -> + if err then return res.send "c'è qualche problema: " + err + parseSubPod = (subpod) -> subpod.value or subpod.image parsePod = (pod) -> '\n=== ' + pod.title + '\n' + pod.subpods.map(parseSubPod).join('\n')