dingtalk.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import json
  2. import time
  3. import hmac
  4. import hashlib
  5. import base64
  6. import requests
  7. import urllib.parse
  8. import logging
  9. from settings import ding_talk
  10. import re
  11. import socket
  12. def intranet_ip():
  13. try:
  14. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  15. s.connect(('8.8.8.8', 80))
  16. ip = s.getsockname()[0]
  17. finally:
  18. s.close()
  19. return str(ip)
  20. def web_ip():
  21. response = requests.get('http://ip.tool.chinaz.com/')
  22. ips = re.findall('\d+\.\d+\.\d+\.\d+', response.text)
  23. if len(ips) > 0:
  24. return ips[0]
  25. else:
  26. return None
  27. def sign_dingtalk():
  28. timestamp = round(time.time() * 1000)
  29. secret = ding_talk['secret_sign']
  30. secret_enc = bytes(secret, 'utf-8')
  31. string_to_sign = '{}\n{}'.format(timestamp, secret)
  32. string_to_sign_enc = bytes(string_to_sign, 'utf-8')
  33. hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
  34. sign = urllib.parse.quote(base64.b64encode(hmac_code))
  35. return timestamp, sign
  36. def send_message(content, atsombody=None, is_self=True, is_carryip=False):
  37. '''
  38. :param content:发送文本
  39. :param atsombody: [
  40. "156xxxx8827",
  41. "151XXX2316"
  42. ]
  43. :param is_self:
  44. :return:
  45. '''
  46. try:
  47. base_url = 'https://oapi.dingtalk.com/robot/send?access_token=dc19e91491341b81f29d7fc347071647031e3d33d8df73f15e4529ad01520e22'
  48. timestamp, sign = sign_dingtalk()
  49. url = base_url + "&timestamp={timestamp}&sign={sign}".format(timestamp=timestamp, sign=sign)
  50. if is_carryip:
  51. ip_intranet = intranet_ip()
  52. ip_public = web_ip()
  53. ip_content = '内网ip {} ,公网ip {}'.format(ip_intranet, ip_public)
  54. content = content + '\n' + ip_content
  55. data = {
  56. "msgtype": "text",
  57. "text": {
  58. "content": content[:10000]
  59. },
  60. "at": {
  61. "atMobiles": [atsombody],
  62. "isAtAll": False
  63. }
  64. }
  65. headers = {'content-type': 'application/json'} # 请求头
  66. time.sleep(1)
  67. response = requests.post(url=url, headers=headers, data=json.dumps(data))
  68. if response.json()['errcode'] == 0:
  69. logging.info('钉钉信息:{} 发送成功'.format(content))
  70. else:
  71. time.sleep(10)
  72. logging.warning('钉钉信息出现问题:{}'.format(str(response.text)))
  73. except Exception as e:
  74. logging.error('钉钉发消息发生问题 error:{} ')
  75. time.sleep(10)