背景
想將 Python 爬下來的內容通知到釘釘
釘釘群聊機器人概述
- 所謂群聊機器人,指可以在群內使用的機器人,目前主要為 webhook 機器人和企業自建機器人兩大類,另外通過場景群模板的方式,也可以預先配置好機器人並通過啟用模板的方式安裝到群內
- 如圖所示,群主和群管理員,可以通過群助手的設置頁,啟用webhook機器人和企業自建機器人,或者在插件更多頁面,通過啟用群模板的方案,來啟用群機器人
群機器人適用於以下場景:
- 項目協同交
- 互式服務
添加機器人到釘釘群
https://developers.dingtalk.com/document/robots/use-group-robots
自定義機器人安全設置
目前機器人一定要有安全設置,如果用 Python 腳本的話,推薦用加簽方式
https://developers.dingtalk.com/document/robots/customize-robot-security-settings
一個小栗子
抓取網上 iphone13 的供貨情況然后通過釘釘機器人通知我
import requests # 獲取手機供貨信息 def get_phone(): res = requests.get( "https://www.apple.com.cn/shop/fulfillment-messages?pl=true&parts.0=MLTE3CH/A&location=%E5%B9%BF%E4%B8%9C%20%E5%B9%BF%E5%B7%9E%20%E5%A4%A9%E6%B2%B3%E5%8C%BA", verify=False) res = res.json()["body"]["content"]["pickupMessage"]["stores"] for num, item in enumerate(res): phone = item["partsAvailability"]["MLTE3CH/A"] storeSelectionEnabled = phone["storeSelectionEnabled"] storePickupQuote = phone["storePickupQuote"] pickupSearchQuote = phone["pickupSearchQuote"] if storeSelectionEnabled: res = { "可取貨": storeSelectionEnabled, "取貨狀態": storePickupQuote, "供應狀態": pickupSearchQuote } yield res # python 3.8 import time import hmac import hashlib import base64 import urllib.parse # 加簽 timestamp = str(round(time.time() * 1000)) secret = '此處填寫 webhook token' 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)) def dingmessage(): # 請求的URL,WebHook地址 webhook = f"https://oapi.dingtalk.com/robot/send?access_token={token}×tamp={timestamp}&sign={sign}" # 構建請求頭部 header = {"Content-Type": "application/json", "Charset": "UTF-8"} # 循環生成器並發送消息 for phone in get_phone(): message = { "msgtype": "text", "text": {"content": phone}, "at": { # @ 所有人 "isAtAll": True } } message_json = json.dumps(message) info = requests.post(url=webhook, data=message_json, headers=header, verify=False) # 打印返回的結果 print(info.text) if __name__ == "__main__": dingmessage()