Python uses DingTalk robot to send messages and share with multiple people

Continue with the water article. Today I mainly complain about DingTalk’s interface documents

I met a need a few days ago:

  1. Check daily unfinished tasks from jira interface
  2. Use the DingTalk robot to send the task to the DingTalk work group, and mark who the task is and the title of the task
  3. When sending, the person corresponding to Aite
  4. Create to-do tasks for everyone
  5. Triggered at 18:00 every day
    insert image description here

I just heard about this requirement, and it feels like a small case, so it should not be troublesome. But during the actual operation, I was cheated. Record the problems encountered today. (For things related to work, I won’t attach all the source code, just take part of the source code to illustrate the problem)

Why do you say pit? In fact, the main reason is that DingTalk's official API is vague, with complicated concepts, and important details are not clearly explained. You have to go through them one by one to see if TA supports it or not.

Here are the steps:

1. Write the public method of jira query. slightly

2. Write the public method for the DingTalk robot to send messages

(DingTalk supports message bodies in multiple formats. Here we only describe how to send markdown. The other principles are the same, just copy according to the interface document)

# -*- coding: utf-8 -*-

import base64
import hashlib
import hmac
import json
import os
import time
from urllib.parse import quote_plus
import requests
import dingding_get_id


class Messenger:
    def __init__(self, token=os.getenv("DD_ACCESS_TOKEN"), secret=os.getenv("DD_SECRET")):
        self.timestamp = str(round(time.time() * 1000))
        self.URL = "https://oapi.dingtalk.com/robot/send"
        self.headers = {
    
    'Content-Type': 'application/json'}
        secret = secret
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(self.timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        self.sign = quote_plus(base64.b64encode(hmac_code))
        self.params = {
    
    'access_token': token, "sign": self.sign}

    def send_markdown(self, title: object, text: object, atUserIds):
        """
        发送markdown
        """
        data = {
    
    
            "msgtype": "markdown",
            "markdown": {
    
    
                "title": title,
                "text": text
            },
            "at": {
    
    
                "atMobiles": [
                ],
                "atUserIds": [
                    *atUserIds
                ],
                "isAtAll": False
            }
        }
        self.params["timestamp"] = self.timestamp
        r = requests.post(
            url=self.URL,
            data=json.dumps(data),
            params=self.params,
            headers=self.headers
        )
        print("data:", data)
        print("-----------------")
        print(r.json())

3. The steps and methods of Aite DingTalk users

Official document: Implementation of @human access guide for internal bot group chat

insert image description here

Here I feel that the writing is quite unclear.
1. The type is array, which means array in java. But there is no such type for python, but a list list can be used instead. For a novice like me, it is not easy to understand. Fortunately, I have learned some java basics before, otherwise I might not understand it.
2.
In the atMobiles parameter, write: in the message content text;
in the atUserids parameter, write: in the message content.
Text and content are two words, and it is easy for people to understand that they are two different things, but in actual use, they refer to the words content of the message.
3. It needs to be used in combination with atMobiles/atUserids parameters to have the @ effect. I read it three times before I understood what it meant: in the two parameters in the picture below, the message content must write @+mobile phone number (or id), and then in the corresponding atMobiles/atUserids, also write the corresponding mobile phone number (or id) to display the @ effect.

insert image description here

Regarding the function of @, I have two questions:
3.1. What should I do if there are many people who need Aite? (Looking at the type of atMobiles and atUserids are java arrays (lists in Python), I feel that multiple people can be passed in to realize multi-person Aite, but the interface documentation does not mention it.) 3.2. The mobile phone number and id must be written together
. Is it effective? Is it okay to only write the id but not the mobile phone number?

These two problems are not written in his interface documentation, so he has to experiment by himself.

The final result of the experiment is:
The answer to 3.1 is: multiple values ​​can be passed in, and multi-person Aite
3.2 does not need to be written with the mobile phone number and id, only one is enough. For example, if you choose a mobile phone number as the Aite mode, then write the mobile phone number in the message content and pass the atMobiles parameter; otherwise, write the id in the message content and pass the atUserids parameter.

Call the sending DingTalk robot and click:

msg = ''
for user_info in user_info_list:
	atuserid = user_info['userid']
	msg = f"+ 经办人:@{
      
      atuserid}"
	
dingding.send_markdown(title='所有未关闭的需求', 
							text=msg,
                           	atUserIds=(j for j in user_id_list)
                           )

The combination of these two sentences is a knowledge point, I will talk about it when I have time
insert image description here

The interface document of Aite is the most uncomfortable to read, even if I am stupid.

4. Steps and methods for creating DingTalk to-do tasks

Official document: Create a DingTalk to-do task

Here I want to complain about the fact that the old version of the sdk is too difficult to use (rbs), there is no other complaint. Just follow the steps.

5. Creation of scheduled tasks

5.1, you can use Jenkins continuous integration
5.2, you can also use what I wrote before: APScheduler timing framework
to execute python timing tasks on Linux servers (APScheduler timing framework)

The End

The official APIs of these major manufacturers, personal feeling friendliness: Baidu>WeChat>DingTalk

Guess you like

Origin blog.csdn.net/xkukeer/article/details/125680519