加签方式

加签方式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import requests
import time
import hmac
import hashlib
import base64
import urllib.parse

# 钉钉机器人 webhook
webhook = 'https://oapi.dingtalk.com/robot/send?access_token=cea075108ea3eee904ea591b7a72a2cc9431877fdb141c50d09b22e89d97ff02'
# 加签密钥
secret = 'SECe04971aa5d5b8afb27ac6f7ad5b7cfc114ef34bdee69597e524b244206b35b5b'


def get_sign(secret):
    # 获取当前时间戳
    timestamp = str(int(time.time() * 1000))
    # 生成签名
    string_to_sign = f"{timestamp}\n{secret}"
    sign = hmac.new(secret.encode(), string_to_sign.encode(), hashlib.sha256).digest()
    sign = base64.b64encode(sign).decode()
    # 将链接的签名进行url编码
    sign = urllib.parse.quote(sign)
    return timestamp, sign


def send_dingtalk_message(content):
    timestamp, sign = get_sign(secret)
    # 构建请求头
    headers = {
        'Content-Type': 'application/json;charset=utf-8',
    }

    # 构建请求负载
    payload = {
        "msgtype": "text",
        "text": {
            "content": content
        },
        "at": {
            "is_at_all": False
        }
    }

    # 发送请求
    response = requests.post(f"{webhook}&timestamp={timestamp}&sign={sign}", json=payload, headers=headers)

    # 输出响应
    print(response.json())


# 调用函数发送消息
send_dingtalk_message("这是一条测试消息,来自Python脚本!")