Python - 接入钉钉机器人
2023-03-15 22:00:13 时间
背景
想将 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 = '{}
{}'.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()
相关文章
- Python中的函数与方法 以及Bound Method和Unbound Method
- 一文贯通python文件读取
- Python 中的异步编程:Asyncio
- 7个你现在就该学习Python的理由
- 提高Python运行效率的六个窍门
- Python数据科学:神经网络
- 一篇文章看懂大数据分析就业前景及职能定位
- R和Python中的文本挖掘:8个入门小贴士
- 告诉你为什么Python有点慢,但我却无所谓?
- 专注学习DevOps编程语言Top 5推荐
- Python发送邮件脚本
- Python多进程并行编程实践: mpi4py 的使用
- Python语言在未来的发展前景
- Python vs Ruby: 谁是最好的 web 开发语言?
- Python对Ruby:谁在Web开发领域更胜一筹?
- Python一行代码完成并行任务
- Python开发者2017应该关注的七个类库
- python爬虫入门基本知识
- 在终端中优雅地编写Python
- Python机器学习实战:信用卡欺诈检测