notify.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import onepush.core
  5. import yaml
  6. from onepush import get_notifier
  7. from onepush.core import Provider
  8. from onepush.exceptions import OnePushException
  9. from onepush.providers.custom import Custom
  10. from requests import Response
  11. from module.logger import logger
  12. onepush.core.log = logger
  13. def handle_notify(_config: str, **kwargs) -> bool:
  14. try:
  15. config = {}
  16. for item in yaml.safe_load_all(_config):
  17. config.update(item)
  18. except Exception:
  19. logger.error("Fail to load onepush config, skip sending")
  20. return False
  21. try:
  22. provider_name: str = config.pop("provider", None)
  23. if provider_name is None:
  24. logger.info("No provider specified, skip sending")
  25. return False
  26. notifier: Provider = get_notifier(provider_name)
  27. required: list[str] = notifier.params["required"]
  28. config.update(kwargs)
  29. # pre check
  30. for key in required:
  31. if key not in config:
  32. logger.warning(
  33. f"Notifier {notifier.name} require param '{key}' but not provided"
  34. )
  35. if isinstance(notifier, Custom):
  36. if "method" not in config or config["method"] == "post":
  37. config["datatype"] = "json"
  38. if not ("data" in config or isinstance(config["data"], dict)):
  39. config["data"] = {}
  40. if "title" in kwargs:
  41. config["data"]["title"] = kwargs["title"]
  42. if "content" in kwargs:
  43. config["data"]["content"] = kwargs["content"]
  44. if provider_name.lower() == "gocqhttp":
  45. access_token = config.get("access_token")
  46. if access_token:
  47. config["token"] = access_token
  48. resp = notifier.notify(**config)
  49. if isinstance(resp, Response):
  50. if resp.status_code != 200:
  51. logger.warning("Push notify failed!")
  52. logger.warning(f"HTTP Code:{resp.status_code}")
  53. return False
  54. else:
  55. if provider_name.lower() == "gocqhttp":
  56. return_data: dict = resp.json()
  57. if return_data["status"] == "failed":
  58. logger.warning("Push notify failed!")
  59. logger.warning(
  60. f"Return message:{return_data['wording']}")
  61. return False
  62. except OnePushException:
  63. logger.exception("Push notify failed")
  64. return False
  65. except Exception as e:
  66. logger.exception(e)
  67. return False
  68. logger.info("Push notify success")
  69. return True