Send DingTalk personal work notification through python

1. DingTalk official open document

https://open.dingtalk.com/document/isvapp/before-you-start

Before development, you need to read the relevant content of the official open documents to avoid some strange problems, such as the change of the domain name of the new and old versions of the interface, different request methods, call frequency restrictions, whether to open the corresponding interface permissions, whitelist, etc.

2. Preparation before development

  • First, the account used for development needs to have DingTalk administrator privileges
  • Self-built application in DingTalk background
    insert image description here
  • Get app AGENT_ID, APP_KEY, APP_SECRET

insert image description here- Open application "Contact Management" module full permissions

3. Implementation ideas

  1. Through the DingTalk open interface, obtain the mapping relationship between the user names of all employees in the enterprise and the employee userId
  2. Establish the relationship between the employee user name and the interface for sending work notification messages
  3. Use the employee’s name as the login account on the third-party platform to be connected, dynamically obtain the employee ID through the DingTalk open interface, and realize sending work notifications

4. Code implementation

DingTalk V1 interface, obtain user id through mobile phone number

# -*- coding: utf-8 -*-
# @Time    : 2020/11/22 12:32
# @Author  : chinablue
# @File    : dingtalk_helper.py

import requests
import objectpath

# 在钉钉上创建应用后获取
AGENT_ID = 123456
APP_KEY = "123456"
APP_SECRET = "123456"

dd_domain = "https://oapi.dingtalk.com"


class DingtalkHelper():

    def __init__(self):
        self.access_token = self.get_token()

    # 获取token
    def get_token(self):
        url = f"{
      
      dd_domain}/gettoken"
        data = {
    
    
            "appkey": APP_KEY,
            "appsecret": APP_SECRET,
        }
        res_json = requests.get(url=url, params=data).json()
        return objectpath.Tree(res_json).execute("$.access_token")

    # 获取部门列表
    def get_depList(self):
        url = f"{
      
      dd_domain}/department/list"
        data = {
    
    
            "access_token": self.access_token,
        }
        res_json = requests.get(url=url, params=data).json()
        departmentIds_list = list(objectpath.Tree(res_json).execute("$..*[@.name is not null].id"))

        return departmentIds_list

    # 获取部门用户userid列表
    def get_memberList(self, depId: str):
        url = f"{
      
      dd_domain}/user/getDeptMember"
        data = {
    
    
            "access_token": self.access_token,
            "deptId": depId,
        }
        res_json = requests.get(url=url, params=data).json()

        return res_json

    # 获取用户详情
    def get_userInfo(self, userId):
        url = f"{
      
      dd_domain}/user/get"
        data = {
    
    
            "access_token": self.access_token,
            "userid": userId,
        }
        res_json = requests.get(url=url, params=data).json()

        userIds_list = list(objectpath.Tree(res_json).execute("$..*[@.userid is not null].(mobile, userid)"))
        userInfo = userIds_list[0]

        return {
    
    userInfo.get("mobile"): userInfo.get("userid")}

    # 向企业个人发送钉钉通知
    def send_ddMsg(self, userId, build_url, build_result, project_num, build_person, build_time):
        url = f"{
      
      dd_domain}/topapi/message/corpconversation/asyncsend_v2?access_token={
      
      self.access_token}"
        msg = {
    
    
            "msgtype": "oa",
            "oa": {
    
    
                "pc_message_url": build_url,
                "head": {
    
    
                    "bgcolor": "FFBBBBBB",
                    "text": build_result
                },
                "body": {
    
    
                    "title": f"({
      
      build_result})Jenkins Pipeline",
                    "form": [
                        {
    
    
                            "key": "项目编号:",
                            "value": f"  {
      
      project_num}"
                        },
                        {
    
    
                            "key": "构建账号:",
                            "value": f"  {
      
      build_person}"
                        },
                        {
    
    
                            "key": "构建时间:",
                            "value": f"  {
      
      build_time}"
                        },
                        {
    
    
                            "key": "构建结果:",
                            "value": f"  {
      
      build_result}"
                        },
                    ],
                    "content": "",
                    "image": "@lADOADmaWMzazQKA",
                }
            }
        }
        data = {
    
    
            "agent_id": AGENT_ID,
            "userid_list": userId,
            "msg": str(msg),
        }
        # 发送消息
        requests.post(url=url, params=data)

    ### 获取公司内所有人员的userId
    def getAll_userIds(self):
        deptIds_list = self.get_depList()

        userIds_list = list()

        for deptId in deptIds_list:
            res_json = self.get_memberList(deptId)
            userIds = objectpath.Tree(res_json).execute("$.userIds")
            userIds_list.extend(userIds)

        return userIds_list

    ### 获取公司内所有人员的mobile和userId的映射关系表
    def getAll_usersInfo(self):
        userIds_list = self.getAll_userIds()

        usersInfo_dict = dict()

        for userId in userIds_list:
            userInfo = self.get_userInfo(userId)
            usersInfo_dict.update(userInfo)

        return usersInfo_dict

DingTalk V1+V2, convert the name into pinyin through the python three-party library, and use the user name to obtain the DingTalk id

AGENT_ID = ######
APP_KEY = ######
APP_SECRET = ######
dd_domain = "https://oapi.dingtalk.com"


class DingTalkConfig:
    def __init__(self):
        self.access_token = self.get_token()

    def get_token(self):
        try:
            url = f"{
      
      dd_domain}/gettoken"
            data = {
    
    
                "appkey": APP_KEY,
                "appsecret": APP_SECRET,
            }
            res_json = Requests.get(url=url, params=data)
            return objectpath.Tree(res_json).execute("$.access_token")
        except Exception as e:
            logger.error(f"获取token失败, {
      
      e}")

    def get_depList(self):
        url = f"{
      
      dd_domain}/department/list"
        data = {
    
    
            "access_token": self.access_token,
        }
        res_json = Requests.get(url=url, params=data)
        departmentids_list = list(objectpath.Tree(res_json).execute("$..*[@.name is not null].id"))
        return departmentids_list
        
    def getAll_userIds(self):
        deptIds_list = self.get_depList()
        userIds_list = list()
        for deptId in deptIds_list:
            res_json = self.get_userList(deptId)
            res = res_json['result']['list']
            userIds_list.extend(res)
        return userIds_list
        
    def dduserList(self):
        userlist = self.getAll_userIds()
        ll = []
        for user in userlist:
            pp = pinyin.get(user['name'], format='strip')
            user.update({
    
    'name': pp})
            ll.append(user)
        logger.info(f'userlist={
      
      ll}')
        return ll
        
    def get_ddid(self, name):
        try:
            for user in self.dduserList():
                if user['name'] == name:
                    return user['userid']
        except Exception as e:
            logger.error(f'获取钉钉用户ID错误,{
      
      e}')

5. Example screenshot

insert image description here

Guess you like

Origin blog.csdn.net/weixin_43587784/article/details/130802313