钉钉api开发
参考:https://blog.csdn.net/tachycardie/article/details/97249198
import requests
import dingtalk.api
import datetime
from datetime import datetime as dt
一、#先调用API获取到token
def getaccseetoken():
request = dingtalk.api.OapiGettokenRequest("https://oapi.dingtalk.com/gettoken")
request.corpid = "AppKey" #AppKey要更换为实际查到的值
request.corpsecret = "AppSecret" #AppSecret要更换为实际查到的值
f = request.getResponse()
access_token = f['access_token']
return access_token
print(getaccseetoken())
二、#获取userid
def get_userid(access_token):
request = dingtalk.api.OapiAttendanceListscheduleRequest('https://oapi.dingtalk.com/topapi/attendance/listschedule')
request.workDate = str(dt.strftime(dt.now(), '%Y-%m-%d %H:%M:%S'))
f = request.getResponse(access_token)
for fx in f:
print(fx)
userid = list(map(lambda x: x["userid"], f['result']['schedules']))
userid = list(set(userid))
return userid
print(get_userid(getaccseetoken()))
#print(get_userid(getaccseetoken()))
#print(len(get_userid(getaccseetoken())))
三、#根据API获取到打卡详情(钉钉有人数限制,此处已做处理)
def get_attendence_listrecord(userid, access_token, day):
request = dingtalk.api.OapiAttendanceListRecordRequest('https://oapi.dingtalk.com/attendance/list')
request.workDateFrom = str(dt.now() - day * datetime.timedelta(days=1))
request.workDateTo = str(dt.now())
request.userIdList = userid
request.offset = 0
request.limit = 50
f = request.getResponse(access_token)
h = []
h.append(f)
while ('hasMore', True) in f.items():
request.offset = request.offset+request.limit
f = request.getResponse(access_token)
h.append(f)
return h
response = get_attendence_listrecord(['manager5540'], '8d1207d535e23e428bda3532110bc06d', day=0)
print(response[0]['recordresult'][0]['userCheckTime'])
print(dt.fromtimestamp(int(response[0]['recordresult'][0]['userCheckTime']) / 1000))
四、#之后你就可以拿数据存入数据库了(注意处理返回system的数据)
def get_value(userid_in, access):
l = []
if len(userid_in)>50:
users = []
start = 0
end = 49
while end<len(userid_in):
users.append(userid_in[start:end])
start +=49
end = start + 50
users.append(userid_in[start:end])
for userid_in_in in users:
reponse = get_attendence_listrecord(userid_in_in, access, day=0)
if reponse[0]['errmsg'] != 'ok':
global access_token
access_token = getaccseetoken()
reponse = get_attendence_listrecord(userid_in_in, access_token, day=0)
for respose in reponse[0]['recordresult']:
if respose['sourceType'] != 'SYSTEM':
value = (respose['userId'], respose['checkType'], dt.fromtimestamp(int(respose['userCheckTime']) / 1000),
respose['locationResult'])
l.append(value)
return l
db = pymysql.connect('数据库地址', '用户名', '密码', '库名', charset="utf8")
cursor = db.cursor()
query = """insert into 表名 (字段名, 字段名,字段名,字段名
) values (%s,%s,%s,%s)"""
valu = get_value(userid, access_token)
def insert():
value = get_value(userid, access_token)
for record in value:
cursor.execute(query, record)
db.commit()