首先附上 钉钉的开放开发文档链接:
在钉钉的开发过程,基本是用到了企业(当前所在的组织架构)的开发权限限制,需要开通。
首先要你需要在企业的钉钉开发平台创建一个应用
然后
真找不到,看钉钉文档
https://open.dingtalk.com/document/orgapp-server/obtain-orgapp-token
其次获取企业的access_token
def getAccess_token():
_appkey = '你自己的appkey'
_appsecret = '你自己的appsecret'
url = 'https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s' % (_appkey, _appsecret)
headers = {
'Content-Type': "application/x-www-form-urlencoded"
}
data = {'appkey': _appkey,
'appsecret': _appsecret}
r = requests.request('GET', url, data=data, headers=headers)
access_token = r.json()["access_token"]
print(access_token)
return access_token
钉钉群里消息可以直接在钉钉群创建一个群机器人,通过这个机器人发送消息。不必通过的用access_token方式调用.
一般群里只有群主才能设置群管理员
附上钉钉文档链接
https://open.dingtalk.com/document/orgapp-server/obtain-orgapp-token
def sendmess():
url = '机器人webhook'
headers = {'content-type': 'application/json',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'}
post_data = {
"msgtype": "text",
"text": {
"content": "通知: 测试信息."
},
"at": {
"atUserIds": ["10093530"],
}
}
r = requests.post(url, headers=headers, data=json.dumps(post_data))
print(r.content)
需要先上传文件,获取文件的 media_id
def getMedia_id():
access_token = getAccess_token()
# 获取要推送文件的路径
# path = os.getcwd()
# file = os.path.join(path, '文件名')
file = r'文件路径'
url = 'https://oapi.dingtalk.com/media/upload?access_token=%s&type=file' % access_token
files = {'media': open(file, 'rb')}
data = {'access_token': access_token,
'type': 'file'}
response = requests.post(url, files=files, data=data)
json = response.json()
print(json)
return json["media_id"]
根据media_id去推送消息,还需要获取钉钉群的chatid.
def SendFile():
access_token = getAccess_token()
media_id = getMedia_id()
chatid = 钉钉群的chatid
url = 'https://oapi.dingtalk.com/chat/send?access_token=' + access_token
header = {
'Content-Type': 'application/json'
}
data = {'access_token': access_token,
'chatid': chatid,
'msg': {
'msgtype': 'file',
'file': {'media_id': media_id}
}}
r = requests.request('POST', url, data=json.dumps(data), headers=header)
print(r.json())
chatid获取的方式是可以在开发者后台去获取
还有一种方式是 直接用代码创建一个会话群,可以返回一个chatid
def get_chatid():
access_token = ''
url = 'https://oapi.dingtalk.com/chat/create?access_token=%s' % access_token
data = {'name': '群名称',
'owner': '群主userid',
'useridlist': ['成员列表userid']} #注意这边必须要加入群主的userid
r = requests.post(url, data=json.dumps(data))
mess = r.json()
print(mess)