Office tool: use Python to send messages to DingTalk

As the most popular office software at present, DingTalk spends most of his time dealing with him at work. Today, I will share with you how to use Python to send messages to DingTalk, and finally automatically send sales reports to designated groups every day.

New swarm robot

First open the group settings and click Smart Group Assistant.
[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-Foj5cKWB-1655343303879)(https://files.mdnice.com/user/19180/0c5981b9-51dc-46e7 -af7e-3ea2fcb1042a.png)]

Choose to add a custom bot

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-zRzGWVBg-1655343303882)(https://files.mdnice.com/user/19180/63090ee0-cd8f-46b0 -a022-ca58c1d59e68.png)]

Then add information according to the prompts. It is recommended to select the first two items of security settings. The key for signing here needs to be saved for later use.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-GPzozI5R-1655343303883)(https://files.mdnice.com/user/19180/13b24511-e995-4ed6 -93d7-a520accdcf6d.png)]

After the click is completed, an Webhookaddress will be generated. Do not publish this address and key casually. Placing it on an external website will pose a security risk.

get signature value

We have obtained the key sum at this time Webhook, first parse the key to get the timestamp (timestamp) and signature value (sign), the code is as follows.

import time
import hmac
import hashlib
import base64
import urllib.parse

timestamp = str(round(time.time() * 1000))
secret = '填入你的密钥'
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(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()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
print(timestamp)
print(sign)

timestamp and sign are two key parameters, and they are Webhookspliced ​​together.

https://oapi.dingtalk.com/robot/send?access_token=XXXXXX&timestamp=XXX&sign=XXX

The value of the access_token parameter has been included in the robot when it was created Webhook. Here, you only need to pass in the values ​​of timestamp and sign to get the complete one Webhook.

DingTalk message type

There are many types of DingTalk messages, and you can choose the type of message to send according to your needs.

Official document: https://open.dingtalk.com/document/robots/custom-robot-access

I use the Markdown format, which currently only supports basic Markdown syntax. At first I thought it was modest, but after a personal test, I found that it does not support it, and only a small part of HTML syntax is supported.

标题
# 一级标题
## 二级标题
### 三级标题
#### 四级标题
##### 五级标题
###### 六级标题

引用
> A man who stands for nothing will fall for anything.

文字加粗、斜体
**bold**
*italic*

链接
[this is a link](http://name.com)

图片
![](http://name.com/pic.jpg)

无序列表
- item1
- item2

有序列表
1. item1
2. item2

Python send request

The overall code is not complicated, the code is as follows.

import time
import hmac
import hashlib
import base64
import urllib.parse
import datetime
import json

timestamp = str(round(time.time() * 1000))
secret = '填入你的密钥'
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(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()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
print(timestamp)
print(sign)

url = f'https://oapi.dingtalk.com/robot/send?access_token=xxxx&timestamp={
      
      timestamp}&sign={
      
      sign}'


def send_request(url, datas):
    header = {
    
    
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }
    sendData = json.dumps(datas)
    sendDatas = sendData.encode("utf-8")
    request = urllib.request.Request(url=url, data=sendDatas, headers=header)
    opener = urllib.request.urlopen(request)
    # 输出响应结果
    print(opener.read())


def get_string():
    '''
    自己想要发送的内容,注意消息格式,如果选择markdown,字符串中应为包含Markdown格式的内容
    例:
    "<font color=#00ffff>昨日销售额:XXX</font> \n <font color=#00ffff>昨日销量:XXX</font>"
    '''
    return "- 测试1 - 测试2"


def main():
    # isAtAll:是否@所有人,建议非必要别选,不然测试的时候很尴尬
    dict = {
    
    
        "msgtype": "markdown",
        "markdown": {
    
    "title": "销售日报",
                     "text": ""
                     },
        "at": {
    
    
            "isAtAll": False
        }
    }

    #把文案内容写入请求格式中
    dict["markdown"]["text"] = get_string()
    send_request(url, dict)

main()

If you are still unclear, you can directly send a private message or refer to the official document.

https://open.dingtalk.com/document/robots/robot-overview

Guess you like

Origin blog.csdn.net/qq_43965708/article/details/125309826