sdk/qywx-sdk/test.py

159 lines
5.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from typing import List, Dict
import requests
#获取token
def get_access_token(corpid: str, corpsecret: str) -> str:
"""
获取企业微信 access_token
:param corpid: 企业ID在企业微信管理后台可找到
:param corpsecret: 应用的凭证密钥
:return: access_token 字符串
:raises Exception: 如果请求失败或返回错误码
"""
url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
params = {
"corpid": corpid,
"corpsecret": corpsecret
}
response = requests.get(url, params=params, timeout=5)
data = response.json()
if data.get("errcode") != 0:
raise Exception(f"获取 access_token 失败: {data}")
return data["access_token"]
#获取企业所有员工
def get_userid_list(access_token: str, limit: int = 10000) -> list:
"""
获取企业成员的 userid 与部门ID列表支持分页
:param access_token: 企业微信 access_token
:param limit: 每次请求返回的成员数上限最大10000
:return: 成员列表,每个成员是字典,包含 'userid''department'
"""
url = "https://qyapi.weixin.qq.com/cgi-bin/user/list_id"
members = []
cursor = ""
while True:
payload = {
"cursor": cursor,
"limit": limit
}
response = requests.post(url, params={"access_token": access_token}, json=payload, timeout=5)
data = response.json()
if data.get("errcode") != 0:
raise Exception(f"获取成员列表失败: {data}")
members.extend(data.get("userid_list", [])) # userid_list是成员ID列表
cursor = data.get("next_cursor")
if not cursor:
break
return members
#获取企业员工所有打卡记录
def get_checkin_data(access_token: str, starttime: int, endtime: int, useridlist: List[str], opencheckindatatype: int = 3) -> List[Dict]:
"""
获取企业成员指定时间段内的打卡记录
:param access_token: 企业微信 access_token
:param starttime: 开始时间(时间戳,秒级)
:param endtime: 结束时间(时间戳,秒级)
:param useridlist: 员工 userid 列表
:param opencheckindatatype: 打卡数据类型,默认 3包含全部打卡记录
:return: 打卡记录列表,每条为字典
"""
url = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckindata"
payload = {
"opencheckindatatype": opencheckindatatype,
"starttime": starttime,
"endtime": endtime,
"useridlist": useridlist
}
response = requests.post(url, params={"access_token": access_token}, json=payload, timeout=10)
data = response.json()
if data.get("errcode") != 0:
raise Exception(f"获取打卡记录失败: {data}")
return data.get("checkindata", [])
#获取微盘所有文件列表
def get_file_list_recursive(access_token, spaceid, fatherid=None, sort_type=1):
"""
递归获取指定空间下所有文件
"""
all_files = []
start = 0
limit = 100 # 每次请求最大文件数,可调整
while True:
url = f"https://qyapi.weixin.qq.com/cgi-bin/wedrive/file_list?access_token={access_token}"
payload = {
"spaceid": spaceid,
"fatherid": fatherid if fatherid else spaceid,
"sort_type": sort_type,
"start": start,
"limit": limit
}
resp = requests.post(url, json=payload)
resp.raise_for_status()
data = resp.json()
if data.get("errcode") != 0:
raise Exception(f"获取文件列表失败: {data}")
files = data.get("items", [])
all_files.extend(files)
# 处理分页
next_start = data.get("next_start", 0)
if next_start == 0:
break
start = next_start
# 递归获取子文件夹中的文件
all_recursive_files = []
for f in all_files:
all_recursive_files.append(f)
if f.get("type") == 1: # type==1 表示文件夹
sub_files = get_file_list_recursive(access_token, spaceid, f["fileid"], sort_type)
all_recursive_files.extend(sub_files)
return all_recursive_files
# 示例调用
if __name__ == "__main__":
corpid = "wwed4ac0dd4e1d398d" # 替换为你的企业ID
corpsecret = "9Mnp2TvsnGkzZkSf9XgLzJdBOo-Mm3Ef0qq3uXCnh_U" # 替换为你的应用密钥
usersecret="mPx7rBDDMQ9QByP3DWxNyEvbkUGhSJB-8a20PIREteo"
user_token=get_access_token(corpid, usersecret)
access_token = get_access_token(corpid, corpsecret)
print("✅ AccessToken:", access_token)
print("✅ UserToken:", user_token)
userids = get_userid_list(user_token)
print(f"✅ 成员数量: {len(userids)}")
print(userids)
starttime = 1492617600 # 示例开始时间
endtime = 1492790400 # 示例结束时间
records = get_checkin_data(access_token, starttime, endtime, userids)
print(f"✅ 打卡记录数量: {len(records)}")
for r in records:
print(r)
# SPACEID="123"
# files = get_file_list_recursive(token, SPACEID)
# print(f"总文件数: {len(files)}")
# for f in files:
# print(f"{f.get('name')} ({'文件夹' if f.get('type') == 1 else '文件'})")