钉钉webhook推送群消息

195 阅读1分钟
import time
import requests
import hmac
import json
import hashlib
import base64
import urllib.parse

# 加签
timestamp = str(round(time.time() * 1000))
# 此处填写 webhook token
secret = 'SE*********************************************************61'
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
# 此处填写 access_token
token = "b349***********************************17b049"


def dingmessage():
    # 请求的URL,WebHook地址
    webhook = f"https://oapi.dingtalk.com/robot/send?access_token={token}&timestamp={timestamp}&sign={sign}"
    # 构建请求头部
    header = {"Content-Type": "application/json", "Charset": "UTF-8"}
    # 发送消息
    message = {
        "msgtype": "text",
        "text": {"content": "测试测试"},
        "at": {
            # @ 所有人
            "atMobiles": [
                "135****336"
            ],
            # "isAtAll": false
        }
    }
    message_json = json.dumps(message)
    info = requests.post(url=webhook, data=message_json, headers=header, verify=False)  # 打印返回的结果
    print(info.text)


if __name__ == "__main__":
    dingmessage()