python 编写的钉钉机器人自动发消息
用python实现的钉钉机器人发消息
# coding:utf-8
import json
import urllib.request
# 1、构建url
url = "机器人的tooken地址"
# url为机器人的webhook
# 2、构建一下请求头部
header = {
"Content-Type": "application/json",
"Charset": "UTF-8"
}
# 3、构建请求数据
data = {
"msgtype": "text",
"text": {
"content": "【你要发送的消息内容】 "
},
"at": {
"isAtAll": True #@全体成员(在此可设置@特定某人)
}
}
#4、对请求的数据进行json封装
sendData = json.dumps(data)#将字典类型数据转化为json格式
sendData = sendData.encode("utf-8") # python3的Request要求data为byte类型
#5、发送请求
request = urllib.request.Request(url=url, data=sendData, headers=header)
#6、将请求发回的数据构建成为文件格式
opener = urllib.request.urlopen(request)
#7、打印返回的结果
print(opener.read())