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')

非常好用。

相关推荐
消失的旧时光-194327 分钟前
第 4 篇:TCP 字节流中的粘包、半包与机器人协议解析
机器人·tcp·通信协议·半包·粘包
张小殊.44 分钟前
LoongForge TAOT 训练方案,解决MoE EP不均衡问题
人工智能·python·深度学习·机器学习·ai
玫幽倩1 小时前
2026黄河流域公安院校-电子物证单项赛(程序逆向分析+服务器取证)
运维·服务器·python·电子取证·逆向·程序分析·服务器取证
北斗落凡尘1 小时前
LangGraph 入门实战(4)
python·langchain
某林2121 小时前
从“仿真能跑”到“真机能走”:一套轮腿机械狗强化学习系统的工程化实践
人工智能·stm32·嵌入式硬件·架构·机器人·机械狗
liwulin05061 小时前
【PYTHON】使用Selenium + ChromeDriver以及XPATH语法
开发语言·python·selenium
copyer_xyf1 小时前
Agentic RAG 实战:PostgreSQL + LangGraph 一条链路
python·postgresql·agent
paopao_djshddhdj1 小时前
钉钉悟空:企业数字化转型的智能助手,使用与收费详解
钉钉
动力 continue1 小时前
Python 元类与异常类:类的“制造工厂”与“报错定制师”
开发语言·python·制造
147API2 小时前
Python批量生成蒸馏数据,并发、重试、幂等和断点续跑
开发语言·jvm·python