学习python使用自定义钉钉机器人的示例代码


本文摘自php中文网,作者coldplay.xixi,侵删。

1.添加自定义机器人

相关学习推荐:python视频教程

2.编写python代码请求钉钉机器人所给的webhook

钉钉自定义机器人官方文档

安全方式使用加签的方式:

第一步,把timestamp+"\n"+密钥当做签名字符串,使用HmacSHA256算法计算签名,然后进行Base64 encode,最后再把签名参数再进行urlEncode,得到最终的签名(需要使用UTF-8字符集)。

参数

说明

timestamp

当前时间戳,单位是毫秒,与请求调用时间误差不能超过1小时

secret

密钥,机器人安全设置页面,加签一栏下面显示的SEC开头的字符串

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

import requests

  

  

#python 3.8

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和第一步得到的签名值拼接到URL中。

参数

说明

timestamp

第一步使用到的时间戳

sign

第一步得到的签名值


第三步,发送请求

1

2

3

4

5

6

7

8

9

10

11

12

13

url='生成的Webhook&timestamp={}&sign={}'.format(timestamp, sign)

  

  

print (url)

headers={

 'Content-Type':'application/json'

}

json={"msgtype": "text",

 "text": {

  "content": "888"

 } }

resp=requests.post(url=url,headers=headers,json=json)

print (resp.text)

结果:

整体代码:

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

29

30

31

32

33

34

import requests

  

  

#python 3.8

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)

  

  

url='生成的Webhook&timestamp={}&sign={}'.format(timestamp, sign)

  

  

print (url)

headers={

 'Content-Type':'application/json'

}

json={"msgtype": "text",

 "text": {

  "content": "测试"

 } }

resp=requests.post(url=url,headers=headers,json=json)

print (resp.text)

相关学习推荐:编程视频

以上就是学习python使用自定义钉钉机器人的示例代码的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python excel使用xlutils类库实现追加写功能的方法

Python中变量和数据类型介绍

Python共发布过哪些版本

Python的线程join怎么用

Python print()打印怎么不换行

Python数据类型的区别

Python怎么导入模块

Python中flask应用(表单处理)

Python开发的gui漂亮吗

深入理解Python对json的解析_Python

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...