背景
想将 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()