currency_convert.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Currency convert (DuckDuckGo)
  3. """
  4. import json
  5. from searx.result_types import EngineResults
  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) -> EngineResults:
  25. res = EngineResults()
  26. # remove first and last lines to get only json
  27. json_resp = resp.text[resp.text.find('\n') + 1 : resp.text.rfind('\n') - 2]
  28. try:
  29. conversion_rate = float(json.loads(json_resp)["to"][0]["mid"])
  30. except IndexError:
  31. return res
  32. answer = '{0} {1} = {2} {3}, 1 {1} ({5}) = {4} {3} ({6})'.format(
  33. resp.search_params['amount'],
  34. resp.search_params['from'],
  35. resp.search_params['amount'] * conversion_rate,
  36. resp.search_params['to'],
  37. conversion_rate,
  38. resp.search_params['from_name'],
  39. resp.search_params['to_name'],
  40. )
  41. url = f"https://duckduckgo.com/?q={resp.search_params['from']}+to+{resp.search_params['to']}"
  42. res.add(res.types.Answer(answer=answer, url=url))
  43. return res