最简单的一种方法 — 步骤:
选择一个钉钉群,进入设置里边,生成机器人,会有一个url,直接复制此url到代码里 sendmsg 也行
# -*- coding: utf-8 -*-
'''
文件说明:
钉钉机器人自动发消息通知
'''
import request
class DingTalk():
def __init__(self):
pass
def getAccess_token(self):
url = 'https://oapi.dingtalk.com/gettoken?appkey=********&appsecret=*******'
appkey = '*********' # 管理员账号登录开发者平台,应用开发-创建应用-查看详情-appkey
appsecret = '********' # 应用里的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"]
return access_token
def getMedia_id(self):
# access_token = self.getAccess_token() # 拿到接口凭证
access_token = 'ABCD2'
soapath = os.getcwd()
filepath = soapath + '/soa_logs.txt'
url = 'https://oapi.dingtalk.com/media/upload?access_token=' + access_token + '&type=file'
files = {'media': open(filepath, 'rb')}
data = {'access_token': access_token,
'type': 'file'}
response = requests.post(url, files=files, data=data)
json = response.json()
return json["media_id"]
def sendfile(self):
access_token = self.getAccess_token()
media_id = self.getMedia_id()
chatid = '******* '# 通过jsapi工具获取的群聊id
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())
def sendmsg(self, content):
keyword = '钉钉消息'
# 采购群链接
url = 'https://oapi.dingtalk.com/robot/send?access_token=ABCD2'
header = {
'Content-Type': 'application/json',
"Charset": "UTF-8"
}
data = {
"msgtype": "text",
"text": {
"content": content
},
"at": {
"isAtAll": False # @全体成员(在此可设置@特定某人)
}
}
r = requests.request('POST', url, data=json.dumps(data), headers=header)
# print(r.json()) # {'errcode': 0, 'errmsg': 'ok'}
if __name__ == "__main__":
pass