currency_convert.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Currency convert (DuckDuckGo)
  4. """
  5. import json
  6. # about
  7. about = {
  8. "website": 'https://duckduckgo.com/',
  9. "wikidata_id": 'Q12805',
  10. "official_api_documentation": 'https://duckduckgo.com/api',
  11. "use_official_api": False,
  12. "require_api_key": False,
  13. "results": 'JSONP',
  14. "description": "Service from DuckDuckGo.",
  15. }
  16. engine_type = 'online_currency'
  17. categories = []
  18. base_url = 'https://duckduckgo.com/js/spice/currency/1/{0}/{1}'
  19. weight = 100
  20. https_support = True
  21. def request(_query, params):
  22. params['url'] = base_url.format(params['from'], params['to'])
  23. return params
  24. def response(resp):
  25. # remove first and last lines to get only json
  26. json_resp = resp.text[resp.text.find('\n') + 1 : resp.text.rfind('\n') - 2]
  27. try:
  28. conversion_rate = float(json.loads(json_resp)["to"][0]["mid"])
  29. except IndexError:
  30. return []
  31. answer = '{0} {1} = {2} {3}, 1 {1} ({5}) = {4} {3} ({6})'.format(
  32. resp.search_params['amount'],
  33. resp.search_params['from'],
  34. resp.search_params['amount'] * conversion_rate,
  35. resp.search_params['to'],
  36. conversion_rate,
  37. resp.search_params['from_name'],
  38. resp.search_params['to_name'],
  39. )
  40. url = f"https://duckduckgo.com/?q={resp.search_params['from']}+to+{resp.search_params['to']}"
  41. return [{"answer": answer, "url": url}]