dingding 发消息(send msg)

使用dingding的webhook机器人群发消息

开头

由于木有更高权限,所以我不能获取全员id等信息,所以目前部分场景使用机器人群发,还是感觉popo好,哈哈 官方文档部分(好难找)https://developers.dingtalk.com/document/app/message-types-and-data-format

一个py脚本,注意使用的时候msg用json.dumps包一下,吐槽一下dingding太low

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# added for jenkins call dingding with params msg and envs by hzluqixue at 2021/1/23 v1

import requests
import argparse
import json

# accept params:
# -t | --token: dingding robot token
# -m | --msg: dingding msg


class DinTalk(object):

    token = ''
    secret = ''
    msg = ''

    def __init__(self, token):
        self.token = token


    def buildMsgJson(self, msg, kind):
        ret = {'status':1, 'message':'','data':''}
        try:
            if kind not in ['text','link','markdown','actionCard']:
                ret['message'] = 'the msg not support. support text,link,markdown,actionCard'
                return ret
            msg = json.loads(json.dumps(eval(msg)))
            if kind == 'text':
                ms_json = {
                    "msgtype": "text",
                    "text": {
                        "content": msg['content']
                    }
                }
            else:
                ms_json = {
                    "msgtype": kind,
                     kind: msg
                 }
            ret['status'] = 0
            ret['message'] = 'get msg json ok'
            ret['data'] = json.dumps(ms_json)
        except Exception as e:
            ret['message'] = "msg json load failed "+str(e)
        finally:
            return ret

    def sendMsg(self, kind='msg', msg='test'):
        ret = {'status':1, 'message':'init', 'data': None}
        try:
            ms_json_ret = self.buildMsgJson(msg=msg, kind=kind)
            if ms_json_ret['status'] == '1':
                ret['message'] = ms_json_ret['message']
                return ret
            headers = {'Content-Type': 'application/json'}
            url = 'https://oapi.dingtalk.com/robot/send?access_token=' + self.token
            data = ms_json_ret['data']
            req = requests.post(url=url, headers=headers, data=data)
            if str(req.status_code) == '200':
                ret['status'] = 0
                ret['message'] = 'send msg successfully for dingding'
            else:
                ret['status'] = 1
                ret['message'] = 'send msg failed error: '+str(req.text)
        except Exception as e:
            ret['status'] = 1
            ret['message'] = 'send msg caught exception: '+str(e)
        finally:
            return ret

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='jenkins dingding')
    parser.add_argument('--token', '-t', nargs=1, default="xxx", required=True, help="please use your dingding robot token with --token TOKEN or -t TOKEN")
    # msg be a json like str
    # text: "{'content':'your message'}"
    # link: "{'text':'link message', 'title': 'link title', 'picUrl':'picure url','messageUrl':'the message link'}"
    # markdown: "{'title':'message title','text':'markdown text'}"
    # actionCard: "{'title':'test title','text:'## lqx test \n\n info','hideAvatar':'0','btnOrientation':'0','btns':[{'title':'ok','actionURL':'https://xxx'},{'title':'not','actionURL':'http://xxx'}]}"
    parser.add_argument('--msg', '-m', nargs=1, default="test", required=True,  help="""please use the msg you want send by dingding with --msg or -m with info ,msg be a json like str
# text:
"{'content':'your message'}"
# link:
"{'text':'link message', 'title': 'link title', 'picUrl':'picure url','messageUrl':'the message link'}"
#markdown:\n
"{'title':'message title','text':'markdown text'}"
    """
)

    parser.add_argument('--kind', '-k', nargs=1, default='text', required=False, help="please use the message type in text, link, markdown, actionCard")
    args = parser.parse_args()
    ding = DinTalk(token=args.token[0])
    ret = ding.sendMsg(msg=args.msg[0], kind=args.kind[0])
    print(ret['message'])

关于markdown

我试了下,html标签没有解释出来 表格无法解释,不知道是不是我的操作问题 开头搞一张图片,整个通知会好看很多,不信你试试!

总结

  1. dingding发消息有的时候还不如邮件如果大家用邮件
  2. 群发消息不要太多,避免消息轰炸,狼来了的情况
  3. dingding的markdown支持并不好,建议参考官文的例子吧

如果有更高的权限可以实现单发https://developers.dingtalk.com/document/app