想将 Python 爬下来的内容通知到钉钉
群机器人适用于以下场景:
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()