/ibid/plugins/ddg.py

https://github.com/ibid/ibid · Python · 59 lines · 44 code · 12 blank · 3 comment · 8 complexity · 27c9b1bb994b3ced3016328a8974377c MD5 · raw file

  1. # Copyright (c) 2016, Kyle Robbertze
  2. # Released under terms of the MIT/X/Expat Licence. See COPYING for details.
  3. from httplib import BadStatusLine
  4. from ibid.plugins import Processor, match
  5. from ibid.utils import json_webservice
  6. features = {'duckduckgo': {
  7. 'description': u'Retrieves results from DuckDuckGo',
  8. 'categories': ('lookup', 'web', 'calculate', ),
  9. }}
  10. class DDGAPISearch(Processor):
  11. usage = u"""ddg[.<tld>] [for] <term>"""
  12. features = ('duckduckgo',)
  13. def _ddg_api_search(self, query, resultsize="large", country=None):
  14. params = {
  15. 'q': query,
  16. 't': 'ibid',
  17. 'format': 'json',
  18. }
  19. if country is not None:
  20. params['gl'] = country
  21. return json_webservice('https://api.duckduckgo.com', params)
  22. @match(r'^ddg(?:\.com?)?(?:\.([a-z]{2}))?\s+(?:for\s+)?(.+?)$')
  23. def search(self, event, country, query):
  24. try:
  25. items = self._ddg_api_search(query, country=country)
  26. except BadStatusLine:
  27. event.addresponse(
  28. u'DuckDuckGo appears to be broken (or more likely, '
  29. u'my connection to it)')
  30. return
  31. results = []
  32. for item in items['Results']:
  33. title = item['Text']
  34. url = item['FirstURL']
  35. results.append(u'"%s" %s' % (title, url))
  36. for item in items['RelatedTopics'][:5]:
  37. if 'Text' in item:
  38. title = item['Text']
  39. url = item['FirstURL']
  40. results.append(u'"%s" %s' % (title, url))
  41. if results:
  42. event.addresponse(u' :: '.join(results))
  43. event.addresponse(u'(Results from DuckDuckGo)')
  44. else:
  45. event.addresponse(
  46. u'Uhh... DuckDuckGo has no Instant Answer on that')
  47. # vi: set et sta sw=4 ts=4: