Python一些可能用的到的函数系列131 发送钉钉机器人消息

说明

来自顾同学的助攻

钉钉机器人可以用来发送一些重要的系统消息,例如磁盘将满等等。原本还可以有更强的功能,就是监听群里的消息,然后做出反应,不过这个好像要买企业版,贵的毫无意义。

钉钉发消息有几种模式,一种是按关键字过滤的,还有一种是按签名发送的。这次顾同学帮我梳理了按签名发送的函数。

内容

前提准备:有钉钉群组,并按签名方式创建了机器人,这时候会得到两个东西:

  • 1 webhook_url: 这个是用于发送消息的接口
  • 2 secret: 签名秘钥

以下函数在每次发送消息时生成签名,然后将消息发送到指定的(机器人所在)的群组

python 复制代码
import requests
import json
import time
import hmac
import hashlib
import base64
import urllib.parse
# 钉钉 Webhook 和加签密钥
webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=xxxx'
secret ='SECxxxx'
# 生成签名
def generate_sign(secret):
    timestamp = str(round(time.time() * 1000))
    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))
    return timestamp, sign
# 发送信息到群里面
def send_dingtalk_message(webhook, secret, message):
    try:
        timestamp, sign = generate_sign(secret)
        url = f"{webhook}&timestamp={timestamp}&sign={sign}"
        headers = {'Content-Type': 'application/json'}
        data = {
            "msgtype": "text",
            "text": {
                "content": message
            }
        }
        print(f"Sending message to URL: {url}")
        print(f"Message content: {data}")
        response = requests.post(url, headers=headers, data=json.dumps(data))
        print(f"Response: {response.status_code}, {response.text}")
        return response.status_code, response.text
    except Exception as e:
        print(f"Error sending message: {e}")
        return None, str(e)

send_dingtalk_message(webhook_url, secret, 'test')

非常好用。

相关推荐
默默coding的程序猿1 小时前
3.git的分支携带问题是什么?怎么解决?
java·git·python·svn·gitee·github·intellij-idea
新子y3 小时前
【小白笔记】PyTorch 和 Python 基础的这些问题
pytorch·笔记·python
万俟淋曦3 小时前
【论文速递】2025年第28周(Jul-06-12)(Robotics/Embodied AI/LLM)
人工智能·ai·机器人·大模型·论文·robotics·具身智能
我是李武涯3 小时前
PyTorch DataLoader 高级用法
人工智能·pytorch·python
Lynnxiaowen3 小时前
今天我们开始学习python语句和模块
linux·运维·开发语言·python·学习
ThreeAu.3 小时前
pytest 实战:用例管理、插件技巧、断言详解
python·单元测试·pytest·测试开发工程师
视觉语言导航4 小时前
CoRL-2025 | SocialNav-SUB:用于社交机器人导航场景理解的视觉语言模型基准测试
人工智能·机器人·具身智能
资源补给站4 小时前
服务器高效操作指南:Python 环境退出与 Linux 终端快捷键全解析
linux·服务器·python
一苓二肆4 小时前
代码加密技术
linux·windows·python·spring·eclipse
青春不败 177-3266-05205 小时前
AI+Python驱动的无人机生态三维建模与碳储、生物量、LULC估算技术
人工智能·python·无人机·生态学·遥感·多光谱遥感