currency_convert.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  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. }
  15. engine_type = 'online_currency'
  16. categories = []
  17. url = 'https://duckduckgo.com/js/spice/currency/1/{0}/{1}'
  18. weight = 100
  19. https_support = True
  20. def request(query, params):
  21. params['url'] = url.format(params['from'], params['to'])
  22. return params
  23. def response(resp):
  24. """remove first and last lines to get only json"""
  25. json_resp = resp.text[resp.text.find('\n') + 1:resp.text.rfind('\n') - 2]
  26. results = []
  27. try:
  28. conversion_rate = float(json.loads(json_resp)['conversion']['converted-amount'])
  29. except:
  30. return results
  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 = 'https://duckduckgo.com/js/spice/currency/1/{0}/{1}'.format(
  41. resp.search_params['from'].upper(), resp.search_params['to'])
  42. results.append({'answer': answer, 'url': url})
  43. return results