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

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

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

1.添加自定义机器人

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

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

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

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

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

参数

说明

timestamp

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

secret

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

import requests  #python 3.8import timeimport hmacimport hashlibimport base64import 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

第一步得到的签名值


第三步,发送请求

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)

结果:

整体代码

import requests  #python 3.8import timeimport hmacimport hashlibimport base64import 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使用自定义钉钉机器人的示例代码所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1184201.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-03
下一篇2022-06-03

发表评论

登录后才能评论

评论列表(0条)

    保存