钉钉python接口对接,同步通讯录组织架构

赵俊晤
2023-12-01

python通过钉钉接口获取钉钉企业的信息。

1. 安装钉钉sdk

pip install dingtalk-sdk

例子:https://github.com/007gzs/dingtalk-django-example
文档:https://dingtalk-sdk.readthedocs.io/zh_CN/latest/client/index.html

可以通过 pip install dingtalk-sdk进行下载安装,然后就可以使用了。
在install dingtalk-sdk之前需要pip install cryptography>=0.8.2或者pip install pycrypto>=2.6.1

2. 代码

import json
import pymysql
from dingtalk import SecretClient, AppKeyClient

##定义变量
E_AppKey = "后台AppKey"
E_AppSecret ="后台AppSecret"

##连接
client = SecretClient(E_AppKey, E_AppSecret)  #新 access_token 获取方式
print(client)





 

def getdepartments(departmentid):
    '''
    :param departmentid: 部门id,默认是1,即是获取所有的部门
    :return:departmentid下所有部门的id,namehe parentid
    '''
    result = {}
    departmentid =[]
    responses = client.department.list(departmentid, fetch_child=True)

    for response in responses:
        result['id']= response.get('id')
        result['name']= response.get('name')
        result['parentid']= response.get('parentid')
        
        if result['parentid'] == None:
            result['parentid'] = 0
        print(result)
        #插入到数据库
        sql = "replace into dept (dept_id,name,parent_id)values(%s,%s,%s)"
        parent =(result['id'],result['name'],result['parentid'])
        
        try:
            cursor.execute(sql, parent) #提交
        except Exception as e:
            cursor.rollback()  #错误回滚
	
        departmentid.append(response.get('id'))
    print(departmentid)
    return departmentid


def getDepartmemtInfo(departmentid):
    '''
    :param departmentid:部门id
    :return: 部门信息
    '''
    responses = client.department.get(departmentid)
    #print(responses)
    return responses


def getuser(departmentid):
    '''
    :param departmentid: 获取部门下的用户(不包括子部门)
    :return: 用户信息
    '''
    res = {}
    userid =[]
    responses = client.user.list(departmentid)
    #print(responses)
    a = responses.get('userlist')
    
   
    for response in a:
        #print(response.get('department'))
        res['department']= response.get('department')
        res['userid']=response.get('userid')
        res['name']=response.get('name')
        res['mobile']=response.get('mobile')
        res['active']=response.get('active')
        res['unionid']=response.get('unionid')
        print(res)

        #插入到数据库
        
        #sql = "replace into user (department,userid,name,mobile,active,unionid)values(%s,%s,%s,%s,%s,%s)"
        table_name = 'user'
        sql_select_Query = """
        INSERT `{0}`  (department, userid, name, mobile, active, unionid)
        VALUES (%s,%s,%s,%s,%s,%s)
        ON DUPLICATE KEY UPDATE
          department=VALUES(department), name=VALUES(name), mobile=VALUES(mobile), active=VALUES(active), unionid=VALUES(unionid)
        """.format(table_name)

        parent =(
            res['department'],
            res['userid'],
            res['name'],
            res['mobile'],
            res['active'],
            res['unionid'],
            )
        try:
            cursor.execute(sql_select_Query, parent) #提交
        except Exception as e:
            cursor.rollback()  #错误回滚

        userid.append(response.get('userid')) #用户id列表

        
    #print(userid)
    return userid



def getEmployeeUserInfo(userid):
    '''
    :param userid:用户钉钉的userid 
    :return: 用户的花名册(详细信息)
    '''
    res = client.employeerm.get(userid)
    print(res)
    return res


if __name__ == '__main__':
        departmentid = getdepartments(1)
        useridlist =[]

        #用户表数据循环
        for x in departmentid:
                userid = getuser(x)
                useridlist.extend(userid)
        print("==================")
        print(useridlist)
        conn.commit()
        cur.close()
        conn.close()
        #for x in useridlist:
                #userid = getEmployeeUserInfo(x)
                #print(userid)

3.DLL建表指令

CREATE TABLE `user` (
`order` varchar(255) DEFAULT NULL COMMENT '部门订单',
`leader` varchar(255) DEFAULT NULL COMMENT '是否部门负责人',
`active` varchar(255) DEFAULT NULL COMMENT '钉钉状态',
`boss` varchar(255) DEFAULT NULL,
`unionid` varchar(255) DEFAULT NULL,
`exclusive_account` varchar(255) DEFAULT NULL,
`mobile` bigint(255) NOT NULL COMMENT '手机号',
`pwd` varchar(255) NOT NULL DEFAULT '123456' COMMENT '密码',
`admin` varchar(255) DEFAULT NULL,
`remark` varchar(255) DEFAULT NULL COMMENT '备注',
`telephone` varchar(255) DEFAULT NULL COMMENT '电话',
`avatar` varchar(255) DEFAULT NULL COMMENT '花名',
`hide_mobile` varchar(255) DEFAULT NULL,
`title` varchar(255) DEFAULT NULL,
`userid` varchar(255) NOT NULL DEFAULT '123456' COMMENT '用户id',
`work_place` varchar(255) DEFAULT NULL COMMENT '工作地点',
`department` varchar(255) DEFAULT NULL COMMENT '部门id列表',
`state_code` varchar(255) DEFAULT '+86' COMMENT '+86',
`name` varchar(255) DEFAULT NULL COMMENT '名称',
`email` varchar(255) DEFAULT NULL COMMENT '邮箱',
`status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '状态,1 表示正常,0 表示禁用',
`roles` varchar(255) DEFAULT NULL COMMENT '用户角色 ID 集合,多个角色逗号分隔。',
`created` datetime DEFAULT NULL COMMENT '创建时间',
`updated` datetime DEFAULT NULL COMMENT '更新时间',
`last_login_time` datetime DEFAULT NULL COMMENT '上次登录时间',
PRIMARY KEY (`mobile`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `dept` (
`parent_id` int(20) NOT NULL DEFAULT '0' COMMENT '上级id',
`name` varchar(60) DEFAULT NULL COMMENT '部门名称',
`dept_id` int(20) NOT NULL COMMENT '部门id',
`create_dept_group` varchar(20) DEFAULT NULL COMMENT '创建部门组\n\n',
PRIMARY KEY (`dept_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE `shop` (
`shopid` varchar(255) NOT NULL COMMENT '店铺id',
`name` varchar(255) DEFAULT NULL COMMENT '店铺名称',
`account` varchar(255) DEFAULT NULL COMMENT '主账号',
`mobile` varchar(255) DEFAULT NULL COMMENT '绑定手机号',
`zfb` varchar(255) DEFAULT NULL COMMENT '支付宝名称',
`bjx` varchar(255) DEFAULT NULL COMMENT '边界线',
`department` varchar(255) DEFAULT NULL COMMENT '部门id',
`pt` varchar(255) DEFAULT NULL COMMENT '平台',
`deptname` varchar(255) DEFAULT NULL COMMENT '部门名称',
PRIMARY KEY (`shopid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


 类似资料: