当前位置:   article > 正文

利用钉钉机器人,实现python向钉钉发送消息_钉钉机器人发送签名、加签、ip段都有的情况下怎么编写

钉钉机器人发送签名、加签、ip段都有的情况下怎么编写

(1)添加群机器人
我添加的是自定义机器人,安全设置选择的是“加签”。
(2)在python中调用
①url的获取
参考钉钉的开发文档 https://open.dingtalk.com/document/robots/customize-robot-security-settings。加签方式需要把timestamp+“\n”+密钥当做签名字符串,使用HmacSHA256算法计算签名,然后进行Base64 encode,最后再把签名参数再进行urlEncode,得到最终的签名(需要使用UTF-8字符集)。该文档提供了python签名计算的代码,直接粘贴即可。最终拼接到调用的url中:https://oapi.dingtalk.com/robot/send?access_token=XXXXXX×tamp=XXX&sign=XXX

参数说明
https://oapi.dingtalk.com/robot/send?access_token=XXXXXX钉钉定义的Webhook
timestamppython中获得的时间戳
signpython中获得的签名值

②调用函数。以下代码为通用函数,需结合安全方式做调整。

import requests  
import json  
  
def send_dingtalk_message(webhook_url, message):  
    data = {  
        "msgtype": "text",  
        "text": {  
            "content": message  
        }  
    }  
    headers = {  
        "Content-Type": "application/json;charset=utf-8"  
    }  
    response = requests.post(webhook_url, data=json.dumps(data), headers=headers)  
    return response.json()  
  
webhook_url = "您的Webhook地址"  
message = "您要发送的消息"  
response = send_dingtalk_message(webhook_url, message)  
print(response)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

③消息格式
如上段代码,可发送普通消息。如需发送markdown格式的消息,则需要调整代码。

import requests  
import json  
  
def send_dingtalk_message(webhook_url, title, message):  
    data = {  
        "msgtype": "markdown",  
        "markdown": {  
            "title": "Markdown消息",  
            "text": message  
        }  
    }  
    headers = {  
        "Content-Type": "application/json;charset=utf-8"  
    }  
    response = requests.post(webhook_url, data=json.dumps(data), headers=headers)  
    return response.json()  
  
title= "题目"    
webhook_url = "您的Webhook地址"  
message = "**加粗**和*斜体*的文本"  
response = send_dingtalk_message(webhook_url, message)  
print(response)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

其中markdown格式的消息,钉钉支持如下格式:

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

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

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

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

图片(建议不要超过20张)
![](http://name.com/pic.jpg)

无序列表
- item1
- item2

有序列表
1. item1
2. item2
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

效果如下:
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/518854
推荐阅读
相关标签
  

闽ICP备14008679号