• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

博客园    首页    新随笔    联系   管理    订阅  订阅
Python调用钉钉群机器人发送群消息

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

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

 

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

秘钥:SEC开头的一段字符

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

(如果选择自定义关键词,则下面代码中不需要秘钥那一段,url=Webhook,发送的内容中包含所设置的关键词才会发送消息,不包含则不会发送)

 

 

 

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

5、下面是python脚本

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

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


def send_dingding(content):
    webhook='https://oapi.dingtalk.com/robot/send?access_token=b484274a54cb0a81fed7c9281b733c672f65cb9b2c5cf8aa1e4318233d44deb9' #钉钉机器人webhook

    timestamp = str(round(time.time() * 1000))
    secret = 'SEC4b13d351458dfd7a570974a0de01a5a63f97882f0277573eafa77cf0a9623859'  #钉钉机器人秘钥
    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))
    url=webhook+'&timestamp='+timestamp+'&sign='+sign


    headers={'Content-Type':'application/json'}
    data={
        "msgtype":"text",
        "text":{
            "content":content
        },
        "isAtAll":True}  #这是判断是否要全员艾特
    #发送post请求
    res=requests.post(url,data=json.dumps(data),headers=headers)

send_dingding('hello')

 

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

 

posted on 2023-02-17 17:36  搁浅小夕  阅读(968)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3