/src/programy/services/duckduckgo.py

https://github.com/keiffster/program-y · Python · 86 lines · 62 code · 18 blank · 6 comment · 15 complexity · a9f608c84e4209953fa5f303304c639c MD5 · raw file

  1. """
  2. Copyright (c) 2016-2020 Keith Sterling http://www.keithsterling.com
  3. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  4. documentation files (the "Software"), to deal in the Software without restriction, including without limitation
  5. the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
  6. and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  7. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
  8. Software.
  9. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
  10. THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  11. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  12. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  13. """
  14. import json
  15. from programy.utils.logging.ylogger import YLogger
  16. from programy.services.service import Service
  17. from programy.services.requestsapi import RequestsAPI
  18. class DuckDuckGoAPI:
  19. def __init__(self, request_api=None):
  20. if request_api is None:
  21. self._requests_api = RequestsAPI()
  22. else:
  23. self._requests_api = request_api
  24. # Provide a summary of a single article
  25. def ask_question(self, url, question, num_responses=1):
  26. # http://api.duckduckgo.com/?q=DuckDuckGo&format=json
  27. payload = {'q': question, 'format': 'json'}
  28. response = self._requests_api.get(url, params=payload)
  29. if response is None:
  30. raise Exception("No response from DuckDuckGo service")
  31. if response.status_code != 200:
  32. raise Exception("Error response from DuckDuckGo service [%d]" % response.status_code)
  33. json_data = json.loads(response.text)
  34. if 'RelatedTopics' not in json_data:
  35. raise Exception("Invalid response from DuckDuckGo service, 'RelatedTopcis' missing from payload")
  36. topics = json_data['RelatedTopics']
  37. if len(topics) == 0:
  38. raise Exception("Invalid response from DuckDuckGo service, no topics in payload")
  39. if len(topics) < num_responses:
  40. num_responses = len(topics)
  41. responses = []
  42. for i in range(num_responses):
  43. if 'Text' in topics[i]:
  44. sentences = topics[i]['Text'].split(".")
  45. responses.append(sentences[0])
  46. return ". ".join(responses)
  47. class DuckDuckGoService(Service):
  48. def __init__(self, config=None, api=None):
  49. Service.__init__(self, config)
  50. if api is None:
  51. self._api = DuckDuckGoAPI()
  52. else:
  53. self._api = api
  54. self._url = None
  55. if config.url is None:
  56. raise Exception("Undefined url parameter")
  57. else:
  58. self._url = config.url
  59. def ask_question(self, client_context, question: str):
  60. try:
  61. return self._api.ask_question(self._url, question)
  62. except Exception as e:
  63. YLogger.error(client_context, "General error querying DuckDuckGo for question [%s] - [%s]", question,
  64. str(e))
  65. return ""