1. Add a custom robot
Related learning recommendations: python video tutorial
2. Writing The python code requests the webhook provided by DingTalk Robot
DingTalk Custom Robot Official Document
Use the signature method in a safe way:
The first step is to use the timestamp "\n" key as the signature string, use the HmacSHA256 algorithm to calculate the signature, and then perform Base64 encode. Finally, urlEncode the signature parameters to get the final signature (you need to use UTF -8 character set).
Parameter Description |
timestamp |
The current timestamp, in milliseconds, cannot exceed 1 hour from the request call time |
secret |
Key, robot security settings page, the string starting with SEC displayed under the signature column |
import requests #python 3.8 import time import hmac import hashlib import base64 import urllib.parse timestamp = str(round(time.time() * 1000)) 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) Copy after login | The second step is to splice the timestamp and the signature value obtained in the first step into the URL.
timestamp | The timestamp used in the first step |
##sign | The signature value obtained in the first step |
The third step, send the request | url='生成的Webhook×tamp={}&sign={}'.format(timestamp, sign) print (url) headers={ 'Content-Type':'application/json' } json={"msgtype": "text", "text": { "content": "888" } } resp=requests.post(url=url,headers=headers,json=json) print (resp.text) Copy after login Result: |
import requests #python 3.8 import time import hmac import hashlib import base64 import urllib.parse timestamp = str(round(time.time() * 1000)) 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) url='生成的Webhook×tamp={}&sign={}'.format(timestamp, sign) print (url) headers={ 'Content-Type':'application/json' } json={"msgtype": "text", "text": { "content": "测试" } } resp=requests.post(url=url,headers=headers,json=json) print (resp.text)
Programming video
The above is the detailed content of Learn python to use the sample code of custom DingTalk robot. For more information, please follow other related articles on the PHP Chinese website!