Python调用钉钉群机器人发送群消息

1、首先需要一个钉钉群,群才有机器人

2、群设置->智能群助手->添加机器人->自定义机器人

 

3、添加自定义机器人,配置如下:给机器人命名,选择加签。保存机器人的秘钥、Webhook,python连接机器人需要用到

秘钥:SEC开头的一段字符

Webhook:https://oapi.dingtalk.com/robot/send?access_token=......

4、至此,机器人添加成功

  5、下面是python脚本

如需发送到另一个钉钉群,只需求更改脚本里的 Webhook链接secret秘钥 即可

复制代码
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests,json

#加签
webhook='https://oapi.dingtalk.com/robot/send?access_token=......' #钉钉机器人webhook
timestamp = str(round(time.time() * 1000))
secret = 'SEC......'  #钉钉机器人秘钥
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
# print(string_to_sign)
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)
webhook=webhook+'&timestamp='+timestamp+'&sign='+sign
print(webhook)
#定义数据类型
headers={'Content-Type':'application/json'}
data={"msgtype":"text","text":{"content":'机器人将发送该备注20221129'},"isAtAll":True}
#发送post请求
res=requests.post(webhook,data=json.dumps(data),headers=headers)
print(res.text)
复制代码

6、执行python脚本即马上给钉钉群机器人发送消息,如图成功发送

 

 

下一篇继续介绍通过Windows定时任务执行Python脚本给钉钉群发送消息

posted @   dabeen  阅读(2606)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示