1. import urllib, requests, json, hmac, hashlib, base64, time
    2. def notice(text):
    3. """
    4. 钉钉发送通知
    5. :param text: 要发送的内容
    6. :return:
    7. """
    8. timestamp = str(round(time.time() * 1000))
    9. secret = '' # 申请的钉钉机器人的密钥
    10. http = '' # webhook的地址
    11. secret_enc = secret.encode('utf-8')
    12. string_to_sign = '{}\n{}'.format(timestamp, secret)
    13. string_to_sign_enc = string_to_sign.encode('utf-8')
    14. hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    15. sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    16. # 导入依赖库
    17. headers = {'Content-Type': 'application/json'} # 定义数据类型
    18. # 截至到&timestamp之前
    19. webhook = f'{http}&timestamp={timestamp}&sign={sign}'
    20. # 定义要发送的数据
    21. data = {
    22. # 定义内容
    23. "msgtype": "markdown",
    24. "markdown": {
    25. "title": "这是定义的标题",
    26. "text": "> 发送的内容\n%s" % text
    27. }
    28. }
    29. requests.post(webhook, data=json.dumps(data), headers=headers) # 发送post请求
    30. notice('')