PageRenderTime 814ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/plugins/duckduckgo.py

http://github.com/Reisen/bruh
Python | 75 lines | 44 code | 15 blank | 16 comment | 8 complexity | cd8021234af2588d0ba40147e2382497 MD5 | raw file
  1. """
  2. This module wraps the DDG Instant Answer API. A godamn badass API. At some
  3. point this might be the default entry point for the .calc command instead
  4. of the google calculator.
  5. """
  6. from urllib.parse import quote_plus, unquote_plus, urlencode
  7. from urllib.request import urlopen, Request
  8. from plugins import mod
  9. import json
  10. hook = mod.hook
  11. def handle_exclusive(query):
  12. return query['Answer']
  13. def handle_article(query):
  14. return query['AbstractText']
  15. def handle_disambiguation(query):
  16. # DDG Figured out a probable result for us.
  17. if query['AbstractText']:
  18. return query['AbstractText']
  19. # Or maybe a probable definition.
  20. if query['Definition']:
  21. return '{} (Source: {})'.format(
  22. query['Definition'],
  23. query['DefinitionSource'] if query['DefinitionSource'] else query['AbstractSource']
  24. )
  25. # Or maybe DDG figured out NOTHING, in which case lets just hope the first
  26. # related topic is sensible.
  27. return query['RelatedTopics'][0]['Text']
  28. @hook.command(['ddg'])
  29. def duckduckgo(irc, nick, chan, msg, args):
  30. """
  31. DuckDuckGo Instant API.
  32. .ddg <expression>
  33. """
  34. if not msg:
  35. return "Syntax: .ddg <expression>"
  36. # Build the request. DuckDuckGo requires an app name parameter for request
  37. # attribution, so don't remove this.
  38. request = Request(
  39. 'https://api.duckduckgo.com/?{}'.format(urlencode({
  40. 'q': msg,
  41. 'format': 'json',
  42. 'pretty': 1,
  43. 'no_redirect': 1,
  44. 'no_html': 1
  45. })),
  46. headers = {
  47. }
  48. )
  49. try:
  50. query = json.loads(urlopen(request, timeout = 7).read().decode('UTF-8'))
  51. # Dispatch to a function that understands the format type returned.
  52. output = {
  53. 'E': lambda: handle_exclusive(query),
  54. 'A': lambda: handle_article(query),
  55. 'D': lambda: handle_disambiguation(query)
  56. }[query['Type']]()
  57. if output:
  58. return output
  59. except Exception as e:
  60. return "No decent results found for those terms."