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

非常好用。

相关推荐
Sandman6z19 分钟前
uv python 卸载
开发语言·python·uv
三道杠卷胡1 小时前
【AI News | 20250521】每日AI进展
人工智能·python·计算机视觉·语言模型·aigc
Chocolate_men1 小时前
ftp、http下载远程文件(多线程、断点续传)
python·网络协议·http
测试19982 小时前
Selenium无法定位元素的几种解决方案详解
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
花菜会噎住3 小时前
Python 计算机网络TCP网络应用程序开发
网络·python·tcp/ip·计算机网络·客户端·服务端
louisliao_19813 小时前
钉钉开发之AI消息和卡片交互开发文档收集
人工智能·钉钉
lijian2603 小时前
钉钉手机端应用访问提示: 钉钉授权码获取遇到了 “签名校验失败“ 的错误,钉钉开发文档有坑造成的
钉钉
牛马的人生4 小时前
使用亮数据代理IP+Python爬虫批量爬取招聘信息训练面试类AI智能体(手把手教学版)
爬虫·python·tcp/ip·其他
leo_hush4 小时前
python查询elasticsearch 获取指定字段的值的list
python·elasticsearch
红衣小蛇妖4 小时前
Python基础学习-Day30
开发语言·python·学习