钉钉接口,发送消息到群机器人 - xd21303/Notebook GitHub Wiki

import base64

my_secret = '***'
my_url = 'https://oapi.dingtalk.com/robot/send?access_token=***'

photo_path = 'fig1.png'
with open(photo_path, 'rb') as f:
    bs64 = base64.b64encode(f.read())  # 读取文件,转换为base64编码(二进制)
    f.close()
    bs64 = bs64.decode()  # 重新解码为字符串
    print(len(bs64))  # 打印长度
# 图片大小有限制

my_data = {
    "msgtype": "markdown",
    "markdown": {"title": "测试发送本地图片",
                 "text": "![myphoto](data:image/png;base64,"+bs64+")"  # 固定格式:data:image/png;base64, bs64内容;image/后面填你的图片后缀,base64,后面填编码好的bs64字符串
                 },
    "at": {
        "atMobiles": [],
        "isAtAll": False}  # 是否@所有人
}

class DingDingWebHook(object):
    def __init__(self, secret=None, url=None):
        """
        :param secret: 安全设置的加签秘钥
        :param url: 机器人没有加签的WebHook_url
        """
        if secret is not None:
            secret = secret
        else:
            secret = '*********'  # 加签秘钥
        if url is not None:
            url = url
        else:
            url = "https://oapi.dingtalk.com/robot/send?access_token=*********"  # 无加密的url

        timestamp = 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))  # 最终签名

        self.webhook_url = url + '&timestamp={}&sign={}'.format(timestamp, sign)  # 最终url,url+时间戳+签名

    def send_meassage(self, data):
        """
        发送消息至机器人对应的群
        :param data: 发送的内容
        :return:
        """
        header = {
            "Content-Type": "application/json",
            "Charset": "UTF-8"
        }
        send_data = json.dumps(data)  # 将字典类型数据转化为json格式
        send_data = send_data.encode("utf-8")  # 编码为UTF-8格式
        request = urllib.request.Request(url=self.webhook_url, data=send_data, headers=header)  # 发送请求

        opener = urllib.request.urlopen(request)  # 将请求发回的数据构建成为文件格式
        print(opener.read())  # 打印返回的结果

dingding = DingDingWebHook(secret=my_secret, url=my_url)
dingding.send_meassage({
    "msgtype": "markdown",
    "markdown": {"title": "测试发送本地图片",
                 "text": "测试"                  },
    "at": {
        "atMobiles": [],
        "isAtAll": False}  # 是否@所有人
})