ddg.lua (928B)
1 local http = require "socket.http" 2 local json = require "json" 3 4 function urlencode(str) 5 if (str) then 6 str = string.gsub(str, "\n", "\r\n") 7 str = string.gsub(str, "([^%w ])", function (c) return string.format ("%%%02X", string.byte(c)) end) 8 str = string.gsub(str, " ", "+") 9 end 10 return str 11 end 12 13 local urlq = urlencode(args) 14 local url = "http://api.duckduckgo.com/?q=" .. urlq .. "&format=json" 15 16 local js = http.request(url) 17 18 local t = json.decode(js) 19 20 tlist = { 21 "Answer", 22 "Definition", 23 "AbstractText" 24 } 25 26 local ret = "" 27 for i,v in ipairs(tlist) do 28 if (ret == "") then 29 ret = t[v] 30 end 31 end 32 33 if (ret == "") then 34 local rett = {} 35 for i,reltopic in ipairs(t["RelatedTopics"]) do 36 if (reltopic["Topics"]) then 37 for j,topic in ipairs(reltopic["Topics"]) do 38 rett[#rett+1] = tostring(topic["Text"]) 39 end 40 else 41 rett[#rett+1] = tostring(reltopic["Text"]) 42 end 43 end 44 ret = table.concat(rett,"\n") 45 end 46 47 return ret