import time
import hmac
import hashlib
import base64
import urllib.parse
import urllib.request
import http.client
import json
import ssl
>timestamp = str(round(time.time() * 1000))
secret = '在钉钉群聊设置的secret'
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))
print(timestamp)
print(sign)
>#sendMsg={"msgtype": "link","link": {"text":"这个即将发布的新版本,创始人xx称它为红树林。而在此之前,每当面临重大升级,产品经理们都会取一个应景的代号,这一次,为什么是红树林","title": "时代的火车向前开","picUrl": "","messageUrl": "https://www.dingtalk.com/s?__biz=MzA4NjMwMTA2Ng==&mid=2650316842&idx=1&sn=60da3ea2b29f1dcc43a7c8e4a7c97a16&scene=2&srcid=09189AnRJEdIiWVaKltFzNTw&from=timeline&isappinstalled=0&key=&ascene=2&uin=&devicetype=android-23&version=26031933&nettype=WIFI"}}
>data = {
"msgtype": "link",
"link": {
"text":"大家好,新版本已经发布",
"title":"新版本",
"picUrl":"图片地址",
"messageUrl":"app链接"
}
}
sendData = json.dumps(data)#将字典类型数据转化为json格式
data_url_encode=sendData.encode('utf-8')
url='https://oapi.dingtalk.com/robot/send?access_token=637069babbd586a90e463908d390a854a75a3535a17997f0de3936f569702775×tamp={}&sign={}' .format(timestamp, sign)
header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36','Content-type': 'application/json','Charset': 'UTF-8'}
conn = http.client.HTTPSConnection('oapi.dingtalk.com')
conn.request(method="POST", url=url, headers=header, body=data_url_encode)
response = conn.getresponse()
print('发送结果')
print(response.getcode())
html=response.read()
print(html)
参考文档:
钉钉自定义机器人(https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq)