<Python启发式自动化>之钉钉推送

1,135 阅读4分钟

<Python启发式自动化>之钉钉推送

如果你希望通过钉钉接收信息通知(注意不是钉钉邮件,所有邮件操作已经在上一小节讲过)

在钉钉上设置一个群机器人,钉钉个人权限所致。

如果为企业权限请详细参考 developers.dingtalk.com/document

  • 添加一个自定义机器人并指定群组
  • 得到一个 Webhook 地址
  • 出于安全考虑,添加签名,即 secret

根据 developers.dingtalk.com/document/ap… 使用 Python 实现一个机器人推送功能

文本推送

# -*- coding: utf-8 -*-
import requests
import json
import time
import hmac
import hashlib
import base64
import urllib.parse


def dingMessage():
    timestamp = str(round(time.time() * 1000))
    secret = 'SEC21022...cf06a65a761c86eb4027b'
    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))
    print(timestamp)
    print(sign)

    # 请求的URL,WebHook地址
    webhook = f"https://oapi.dingtalk.com/robot/send?access_token=33576dfcb4...7bc0ec08354cc181a&timestamp={timestamp}&sign={sign}"
    # 构建请求头部
    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }
    # 构建请求数据
    tex = "呼叫0号呼叫0号"
    message = {
        "msgtype": "text",
        "text": {
            "content": f" @137....97091 {tex}"
        },

        # todo 是否@所有人
        "at": {
            "atMobiles": [
                "137...7091"
            ],
            "isAtAll": False
        }

    }
    # 对请求的数据进行json封装
    message_json = json.dumps(message)
    # 发送请求
    info = requests.post(url=webhook, data=message_json, headers=header)
    # 打印返回的结果
    print(info.text)


if __name__ == "__main__":
    dingMessage()

做了什么

  • secret 机器人加签
  • webhook 机器人API地址,参数组成: timestamp(时间戳) sign(sha256加密后base64编码生成的签名)
  • tex 文本信息
  • message 主体对象,选择@相关的人(这里根据手机号码)

markdown推送

# -*- coding: utf-8 -*-
import json

import requests


def dingmessage():
    import time
    import hmac
    import hashlib
    import base64
    import urllib.parse

    timestamp = str(round(time.time() * 1000))
    secret = 'SEC21022b79....9cf06a65a761c86eb4027b'
    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))
    print(timestamp)
    print(sign)

    # 请求的URL,WebHook地址
    webhook = f"https://oapi.dingtalk.com/robot/send?access_token=33576dfc....4800d577bc0ec08354cc181a&timestamp={timestamp}&sign={sign}"
    # 构建请求头部
    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }
    message = {
        "msgtype": "markdown",
        # "text": {
        #     "content": f" @137...97091 {tex}"
        # },

        "markdown": {
            "title": "杭州天气",
            "text": "#### 杭州天气 @155...773 \n> 900度,西北风1级,空气良8009,相对温度673%\n> [![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png)](https://developers.dingtalk.com/document/app/send-normal-messages)\n> ###### 10点20分发布 [天气](https://www.dingtalk.com) \n"
        },

        # todo 是否@所有人
        "at": {
            "atMobiles": [
                "15....773"
            ],
            "isAtAll": False
        }

    }
    # 对请求的数据进行json封装
    message_json = json.dumps(message)
    # 发送请求
    info = requests.post(url=webhook, data=message_json, headers=header)
    # 打印返回的结果
    print(info.text)


if __name__ == "__main__":
    dingmessage()

网页链接

# -*- coding: utf-8 -*-
import json

import requests


def dingmessage():
    import time
    import hmac
    import hashlib
    import base64
    import urllib.parse

    timestamp = str(round(time.time() * 1000))
    secret = 'SEC21022b792577....8639cf06a65a761c86eb4027b'
    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))
    print(timestamp)
    print(sign)
    # 请求的URL,WebHook地址
    webhook = f"https://oapi.dingtalk.com/robot/send?access_token=33576dfcb4....800d577bc0ec08354cc181a&timestamp={timestamp}&sign={sign}"

    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }

    message = {
        "msgtype": "link",
        "link": {
            "text": "这个即将发布的新版本,创始人xx称它为红树林。而在此之前,每当面临重大升级,产品经理们都会取一个应景的代号,这一次,为什么是红树林",
            "title": "时代的火车向前开",
            "picUrl": "",
            "messageUrl": "https://www.dingtalk.com/s?__biz=MzA4NjMwMTA2Ng==&mid=2650316842&idx=1&sn=60da3ea2b29f1dcc43a7c8e4a7c97a16&scene=2&srcid=09189AnRJEdIiWVaKltFzNTw&from=timeline&isappinstalled=0&key=&ascene=2&uin=&devicetype=android-23&version=26031933&nettype=WIFI"
        },

        # todo 是否@所有人
        "at": {
            "atMobiles": [
                "15....8773"
            ],
            "isAtAll": False
        }

    }
    message_json = json.dumps(message)
    info = requests.post(url=webhook, data=message_json, headers=header)
    print(info.text)


if __name__ == "__main__":
    dingmessage()

卡片推送

整体跳转ActionCard类型

# -*- coding: utf-8 -*-
import json

import requests


def dingmessage():
    import time
    import hmac
    import hashlib
    import base64
    import urllib.parse

    timestamp = str(round(time.time() * 1000))
    secret = 'SEC21022b7925....064668639cf06a65a761c86eb4027b'
    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))
    print(timestamp)
    print(sign)
    # 请求的URL,WebHook地址
    webhook = f"https://oapi.dingtalk.com/robot/send?access_token=33576dfcb.....4800d577bc0ec08354cc181a&timestamp={timestamp}&sign={sign}"

    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }

    message = {
        "msgtype": "actionCard",
        "actionCard": {
            "text": "![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png) \n\n #### 乔布斯 20 年前想打造的苹果咖啡厅 \n\n Apple Store 的设计正从原来满满的科技感走向生活化,而其生活化的走向其实可以追溯到 20 年前苹果一个建立咖啡馆的计划",
            "title": "时代的火车向前开",
            "btnOrientation": "0", 
            "singleTitle" : "阅读全文",
            "singleURL" : "https://www.dingtalk.com/"
        },

        # todo 是否@所有人
        "at": {
            "atMobiles": [
                "155....8773"
            ],
            "isAtAll": False
        }

    }
    message_json = json.dumps(message)
    info = requests.post(url=webhook, data=message_json, headers=header)
    print(info.text)


if __name__ == "__main__":
    dingmessage()

独立跳转ActionCard类型

# -*- coding: utf-8 -*-
import json

import requests


def dingmessage():
    import time
    import hmac
    import hashlib
    import base64
    import urllib.parse

    timestamp = str(round(time.time() * 1000))
    secret = 'SEC21022b792.....39cf06a65a761c86eb4027b'
    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))
    print(timestamp)
    print(sign)
    # 请求的URL,WebHook地址
    webhook = f"https://oapi.dingtalk.com/robot/send?access_token=33576dfcb4.....0ec08354cc181a&timestamp={timestamp}&sign={sign}"

    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }

    message = {
        "msgtype": "actionCard",
        "actionCard": {
            "text": "![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png) \n\n #### 乔布斯 20 年前想打造的苹果咖啡厅 \n\n Apple Store 的设计正从原来满满的科技感走向生活化,而其生活化的走向其实可以追溯到 20 年前苹果一个建立咖啡馆的计划",
            "title": "时代的火车向前开",
            "hideAvatar": "0",
            "btnOrientation": "1",
            "btns": [
                {
                    "title": "内容不错",
                    "actionURL": "https://www.dingtalk.com/"
                },
                {
                    "title": "不感兴趣",
                    "actionURL": "https://www.dingtalk.com/"
                }
            ]
        },

        # todo 是否@所有人
        "at": {
            "atMobiles": [
                "155....8773"
            ],
            "isAtAll": False
        }

    }
    message_json = json.dumps(message)
    info = requests.post(url=webhook, data=message_json, headers=header)
    print(info.text)


if __name__ == "__main__":
    dingmessage()

以上就是钉钉群机器人通知的几种类型。

总而言之钉钉机器人推送是一种非常不错的选择,足以应对日常工作中的各类场景 (定时提醒阈值告警事件通知 等等)