用python實現的釘釘機器人發消息

1 # coding:utf-8 2 3 import json 4 5 import urllib.request 6 7 # 1、構建url 8 9 url = "機器人的tooken地址" 10 # url為機器人的webhook 11 12 # 2、構建一下請求頭部 13 14 header = { 15 16 "Content-Type": "application/json", 17 18 "Charset": "UTF-8" 19 20 } 21 22 # 3、構建請求數據 23 24 data = { 25 "msgtype": "text", 26 "text": { 27 "content": "【你要發送的消息內容】 " 28 }, 29 "at": { 30 "isAtAll": True #@全體成員(在此可設置@特定某人) 31 } 32 } 33 34 #4、對請求的數據進行json封裝 35 sendData = json.dumps(data)#將字典類型數據轉化為json格式 36 sendData = sendData.encode("utf-8") # python3的Request要求data為byte類型 37 #5、發送請求 38 request = urllib.request.Request(url=url, data=sendData, headers=header) 39 40 #6、將請求發回的數據構建成為文件格式 41 42 opener = urllib.request.urlopen(request) 43 #7、打印返回的結果 44 print(opener.read()) 45