/plugins/answer.lua

https://github.com/wrxck/mattata · Lua · 57 lines · 49 code · 4 blank · 4 comment · 25 complexity · de6fc0c44e66e4a7a239f9901db4e3d3 MD5 · raw file

  1. --[[
  2. Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com>
  3. This code is licensed under the MIT. See LICENSE for details.
  4. ]]
  5. local answer = {}
  6. local mattata = require('mattata')
  7. local https = require('ssl.https')
  8. local url = require('socket.url')
  9. local json = require('dkjson')
  10. local redis = require('libs.redis')
  11. function answer:init()
  12. answer.commands = mattata.commands(self.info.username):command('answer').table
  13. answer.help = '/answer <query> - Provides a quick answer to the given query. Results provided by DuckDuckGo.'
  14. answer.url = 'https://api.duckduckgo.com/?format=json&pretty=0&q='
  15. end
  16. function answer:on_message(message, _, language)
  17. local input = mattata.input(message.text)
  18. if not input then
  19. return false
  20. elseif input:match('%d* ?[%+*%-/]') then
  21. message.text = '/calc ' .. input
  22. return mattata.on_message(self, message)
  23. end
  24. input = input:gsub('[%?!,]', '')
  25. local jstr, res = https.request(answer.url .. url.escape(input))
  26. if res ~= 200 then
  27. return mattata.send_reply(message, language.errors.connection)
  28. end
  29. local jdat = json.decode(jstr)
  30. if not jdat.meta and jdat.Heading == '' and not jdat.RelatedTopics[1] then
  31. redis:hset('ai:' .. message.chat.id .. ':' .. message.message_id, 'text', input)
  32. redis:hset('ai:' .. message.chat.id .. ':' .. message.message_id, 'language', language)
  33. return true
  34. end
  35. local output = '<b>%s</b>\n<em>%s</em>\n%s'
  36. local heading = jdat.Heading
  37. local body = jdat.AbstractText ~= '' and jdat.AbstractText or jdat.RelatedTopics[1].Text or 'Couldn\'t find a description, try sending /wiki ' .. jdat.Heading
  38. local via = jdat.AbstractSource ~= '' and jdat.AbstractSource or jdat.RelatedTopics[1].FirstURL
  39. local image = jdat.Image ~= '' and jdat.Image or jdat.RelatedTopics[1] and jdat.RelatedTopics[1].Icon.URL
  40. if via:lower() == 'wikipedia' then
  41. via = '<a href="https://en.wikipedia.org">Wikipedia</a>'
  42. end
  43. via = 'Via ' .. via .. '.'
  44. if body:find(' /wiki ') then -- If we're re-directing them to the Wikipedia command, we don't want to give them a via message.
  45. return mattata.send_reply(message, 'I couldn\'t find an answer for that, try /wiki ' .. heading .. '.')
  46. end
  47. output = string.format(output, mattata.escape_html(heading), mattata.escape_html(body), via)
  48. if image and image ~= '' then
  49. return mattata.send_photo(message.chat.id, image, output, 'html', false, message.message_id)
  50. end
  51. return mattata.send_reply(message, output, 'html', true)
  52. end
  53. return answer