Commits

firefly  committed 41f44d2

Add Wolfram|Alpha module.

  • Participants
  • Parent commits 75c36e0

Comments (0)

Files changed (1)

File modules/05-wolframalpha.js

+var xpath  = require('xpath')
+  , xmldom = require('xmldom')
+
+bot.triggers.command.add('wa', {
+  help: "Queries Wolfram|Alpha for an answer.",
+  exec: function (data) {
+    if (data.line == "") {
+      return this.reply("Too short query.")
+    }
+
+    var appid = bot.storage.data.appid.wolframalpha
+
+    var query = encodeURIComponent(data.line).replace(/%20/g, '+')
+      , self  = this
+
+    backend.net.get('api.wolframalpha.com/v2/query',
+                   { input: query,
+                     appid: appid },
+      function (err, xml, done) {
+        if (!done) return
+        if (err)   return self.error(err)
+
+        require('fs').writeFile('/tmp/wa-api-output', xml)
+
+        var doc       = (new xmldom.DOMParser()).parseFromString(xml)
+          , plaintext = xpath.select('//pod[@id!="Input"]//plaintext/text()', doc)[0]
+
+        console.log("Plaintext:", String(plaintext))
+
+        if (plaintext) {
+          self.reply(prettify(String(plaintext)))
+        } else {
+          self.send(data.target, "Couldn't grab plaintext result!")
+        }
+      })
+  }
+})
+
+function prettify(str) {
+  var subscript   = { "+":"₊", "-":"₋", "=":"₌", "(":"₍", ")":"₎",
+                      "x":"ₓ", "i":"ᵢ" }
+    , superscript = { "+":"⁺", "-":"⁻", "=":"⁼", "(":"⁽", ")":"⁾",
+                      "n":"ⁿ" }
+    , wordSubstitution = { "sum": "∑", "product": "∏" }
+
+  for (var i=0; i<10; i++) {
+    subscript[i]   = "₀₁₂₃₄₅₆₇₈₉"[i]
+    superscript[i] = "⁰¹²³⁴⁵⁶⁷⁸⁹"[i]
+  }
+
+  console.warn("prettifying...")
+
+  return str.replace(/([_^])(?:(\d+|[A-Za-z])|\(([^\)]+)\))/g, function (input, op, text1, text2) {
+    var text = text1 || text2
+      , map  = op == "^"? superscript : subscript
+
+    console.warn("prettify:", op, text1, text2, input)
+
+    if (text.split("").every(lookup.bind(null, map))) {
+      return text.replace(/./g, lookup.bind(null, map))
+    } else {
+      return input
+    }
+  }).replace(/[A-Za-z]+/g, function (word) {
+    return wordSubstitution[word] || word
+  })
+
+  function lookup(obj, key, def) {
+    return key in obj? obj[key] : def
+  }
+}