钉钉获取公司所有员工的方法及代码

java 文章 2020-12-31 14:52 2084 0 全屏看文

AI助手支持GPT4.0

钉钉也没提供直接的方法。钉钉官方给出的办法就是先遍迭代所有部门,再枚举出所有的用户。

网上也没现成的代码所以自己写了一个

首先准备好两个方法:

  1. 获取公司所有部门和子部门

  2. 获取部门下所有的员工


获取部门方法和部门用户方法如下:

/**
 * 根据父节点遍历所有的子节点
 * @from sanshu.cn
 * @param deptId 部门编号
 * @return
 * @throws ApiException
 */
public OapiDepartmentListResponse getDeptList(String id,boolean  fetchChild) throws ApiException{
	DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
	OapiDepartmentListRequest request = new OapiDepartmentListRequest();
	request.setId(id);
	request.setHttpMethod("GET");
	request.setFetchChild(fetchChild);
	OapiDepartmentListResponse response = client.execute(request, accessTokenUtil.getToken());
	System.out.println(response.getBody());
	return response;
	
}

/**
 * 根据获取用户编号
 * @from sanshu.cn
 * @param deptId 部门编号
 * @return
 * @throws ApiException
 */
public List<String> getUsersIdByDeptId(String deptId) throws ApiException {
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getDeptMember");
		OapiUserGetDeptMemberRequest req = new OapiUserGetDeptMemberRequest();
		req.setHttpMethod("GET");
		req.setDeptId(deptId);
		OapiUserGetDeptMemberResponse rsp = client.execute(req,accessTokenUtil.getToken());
		System.out.println(rsp.getBody());
		return rsp.getUserIds();
}


最后是把上面两个方法串起来的代码:

@Test
public void getAllUser() throws ApiException {
	//String rootDept = "362217315";
	String rootDept = "225228641";
	OapiDepartmentListResponse resp = dingDeptService.getDeptList(rootDept,true);
	if(!resp.isSuccess()) {
		System.err.println(resp.getMessage());
	}else {
		resp.getDepartment().forEach(d->{
			System.out.println(d.getId()+"->"+d.getName());
			try {
				List<String> usersId = dingUserService.getUsersIdByDeptId(d.getId().toString());
				usersId.forEach(u->{
					System.out.println("---"+u);
				});
			} catch (ApiException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		});
	}
}

最终运行结果:

image.png


-EOF-

AI助手支持GPT4.0