PageRenderTime 94ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/modules/duckduckgo.py

https://bitbucket.org/pbui/bobbit
Python | 58 lines | 47 code | 8 blank | 3 comment | 2 complexity | f38a1137065c7216a1024db21d0c8177 MD5 | raw file
  1. from __common__ import shorten_url, format_responses
  2. import requests
  3. # Constants
  4. MODULE_NAME = 'DuckDuckGo Instance Answer Search'
  5. MODULE_ENABLE = True
  6. MODULE_TYPE = 'command'
  7. DUCKDUCKGO_URL = u'http://api.duckduckgo.com'
  8. DUCKDUCKGO_RE = r'^!(ddg|duckduckgo)\s+'
  9. # DuckDuckGo Instance Answer function
  10. # https://duckduckgo.com/api
  11. def duckduckgo(bot, nick, query, channel):
  12. query = query[len(query.split()[0]) + 1:].strip()
  13. params = {'q': query, 'format': 'json', 'no_html': 1, 'no_redirect': 1}
  14. results = requests.get(DUCKDUCKGO_URL, params=params, timeout=bot.conn.requests_timeout)
  15. response = u'No results'
  16. try:
  17. result = results.json()
  18. if query.startswith('!'):
  19. title = query[len(query.split()[0]) + 1:].strip()
  20. content = ''
  21. url = result['Redirect']
  22. else:
  23. title = result['Heading']
  24. content = result['AbstractText']
  25. url = result['AbstractURL']
  26. if not title:
  27. raise KeyError
  28. if not content:
  29. response = u'{title} @ {url}'.format(**locals())
  30. else:
  31. response = u'{title} - {content} @ {url}'.format(**locals())
  32. shorturl = shorten_url(url)
  33. if url != shorturl:
  34. response = u'{response} || {shorturl}'.format(**locals())
  35. except (KeyError, IndexError):
  36. response = u'No results'
  37. return format_responses([response], nick, channel)
  38. # Registration hook
  39. def register_patterns(bot):
  40. return (
  41. (DUCKDUCKGO_RE, lambda nick, message, channel: duckduckgo(bot, nick, message, channel)),
  42. )
  43. # vim: set sts=4 sw=4 ts=8 expandtab ft=python: