robot.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on 2022-06-15
  4. ---------
  5. @summary: 企业微信机器人
  6. ---------
  7. @author: Dzr
  8. """
  9. import requests
  10. import setting
  11. def post_data(platform, limit, usage, msg, allow_reset=False):
  12. """
  13. :param platform:平台名称
  14. :param limit:限制次数
  15. :param usage:使用次数
  16. :param msg: 通知内容
  17. :param allow_reset: 解除限制
  18. :return:
  19. """
  20. label = "<font color=\"warning\">{}</font>".format(msg)
  21. platform = ">平台名称: <font color=\"comment\">{}</font>".format(platform)
  22. c0 = ">调用上限: <font color=\"comment\">{}次</font>".format(limit)
  23. c1 = ">调用次数: <font color=\"comment\">{}次</font>".format(usage)
  24. msg = "{}\n {}\n > {}\n > {}\n".format(label, platform, c0, c1)
  25. if allow_reset:
  26. c2 = f"[解除限制]({setting.PLATFORM_API}/v1/images/reset)"
  27. msg = "{}[{}]\n > {}\n > {}\n {}".format(label, c2, platform, c0, c1)
  28. content = msg
  29. markdown = {"msgtype": "markdown", "markdown": {"content": content}}
  30. body = {"markdown": markdown}
  31. if setting.WECHAT_WARNING_PHONES:
  32. text = {
  33. "msgtype": "text",
  34. "text": {
  35. "content": " 请相关同事注意",
  36. "mentioned_mobile_list": setting.WECHAT_WARNING_PHONES
  37. }
  38. }
  39. body['text'] = text
  40. return body
  41. def robot_webhook(data):
  42. headers = {"Content-Type": "application/json"}
  43. params = {"key": setting.WECHAT_WARNING_ROBOT_KEY}
  44. url = setting.WECHAT_WARNING_URL
  45. response = requests.post(url, headers=headers, params=params, json=data)
  46. return response.json()
  47. def send_msg(platform, limit, usage, msg, **kwargs):
  48. contents = post_data(platform, limit, usage, msg, **kwargs)
  49. for _, content in contents.items():
  50. response = robot_webhook(content)
  51. print('企业微信机器人 >>> ', response)