notify.py 6.3 KB
Newer Older
U
UlricQin 已提交
1
#!/usr/bin/env python
Q
qinyening 已提交
2 3 4
# -*- coding: UTF-8 -*-
import sys
import json
U
UlricQin 已提交
5
import urllib2
Q
qinyening 已提交
6 7 8
import smtplib
from email.mime.text import MIMEText

U
UlricQin 已提交
9
notify_channel_funcs = {
7
710leo 已提交
10 11 12 13
  "email":"email",
  "sms":"sms",
  "voice":"voice",
  "dingtalk":"dingtalk",
U
Ulric Qin 已提交
14 15
  "wecom":"wecom",
  "feishu":"feishu"
7
710leo 已提交
16 17
}

U
UlricQin 已提交
18 19 20 21 22
mail_host = "smtp.163.com"
mail_port = 994
mail_user = "ulricqin"
mail_pass = "password"
mail_from = "ulricqin@163.com"
23

U
UlricQin 已提交
24 25 26 27
class Sender(object):
    @classmethod
    def send_email(cls, payload):
        users = payload.get('event').get("notify_users_obj")
28

U
UlricQin 已提交
29 30 31 32
        emails = {}
        for u in users:
            if u.get("email"):
                emails[u.get("email")] = 1
33 34 35

        if not emails:
            return
U
UlricQin 已提交
36

U
UlricQin 已提交
37 38
        recipients = emails.keys()
        mail_body = payload.get('tpls').get("mailbody.tpl", "mailbody.tpl not found")
7
710leo 已提交
39
        message = MIMEText(mail_body, 'html', 'utf-8')
40 41
        message['From'] = mail_from
        message['To'] = ", ".join(recipients)
U
UlricQin 已提交
42
        message["Subject"] = payload.get('tpls').get("subject.tpl", "subject.tpl not found")
43

U
UlricQin 已提交
44 45 46 47 48 49 50
        try:
            smtp = smtplib.SMTP_SSL(mail_host, mail_port)
            smtp.login(mail_user, mail_pass)
            smtp.sendmail(mail_from, recipients, message.as_string())
            smtp.close()
        except smtplib.SMTPException, error:
            print(error)
51 52

    @classmethod
U
UlricQin 已提交
53 54 55 56
    def send_wecom(cls, payload):
        users = payload.get('event').get("notify_users_obj")

        tokens = {}
李伟强 已提交
57 58 59

        for u in users:
            contacts = u.get("contacts")
U
UlricQin 已提交
60 61 62 63 64 65 66 67 68 69 70 71
            if contacts.get("wecom_robot_token", ""):
                tokens[contacts.get("wecom_robot_token", "")] = 1

        opener = urllib2.build_opener(urllib2.HTTPHandler())
        method = "POST"

        for t in tokens:
            url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={}".format(t)
            body = {
                "msgtype": "markdown",
                "markdown": {
                    "content": payload.get('tpls').get("wecom.tpl", "wecom.tpl not found")
李伟强 已提交
72 73
                }
            }
U
UlricQin 已提交
74 75 76 77 78 79 80 81
            request = urllib2.Request(url, data=json.dumps(body))
            request.add_header("Content-Type",'application/json;charset=utf-8')
            request.get_method = lambda: method
            try:
                connection = opener.open(request)
                print(connection.read())
            except urllib2.HTTPError, error:
                print(error)
82 83

    @classmethod
U
UlricQin 已提交
84 85
    def send_dingtalk(cls, payload):
        users = payload.get('event').get("notify_users_obj")
ning1875's avatar
ning1875 已提交
86

U
UlricQin 已提交
87 88
        tokens = {}
        phones = {}
ning1875's avatar
ning1875 已提交
89 90

        for u in users:
U
UlricQin 已提交
91 92
            if u.get("phone"):
                phones[u.get("phone")] = 1
ning1875's avatar
ning1875 已提交
93

U
UlricQin 已提交
94 95 96
            contacts = u.get("contacts")
            if contacts.get("dingtalk_robot_token", ""):
                tokens[contacts.get("dingtalk_robot_token", "")] = 1
ning1875's avatar
ning1875 已提交
97

U
UlricQin 已提交
98 99
        opener = urllib2.build_opener(urllib2.HTTPHandler())
        method = "POST"
ning1875's avatar
ning1875 已提交
100

U
UlricQin 已提交
101 102 103
        for t in tokens:
            url = "https://oapi.dingtalk.com/robot/send?access_token={}".format(t)
            body = {
ning1875's avatar
ning1875 已提交
104 105
                "msgtype": "text",
                "text": {
U
UlricQin 已提交
106
                    "content": payload.get('tpls').get("dingtalk.tpl", "dingtalk.tpl not found")
ning1875's avatar
ning1875 已提交
107 108
                },
                "at": {
U
UlricQin 已提交
109
                    "atMobiles": phones.keys(),
ning1875's avatar
ning1875 已提交
110 111
                    "isAtAll": False
                }
112
            }
U
UlricQin 已提交
113 114 115 116 117 118 119 120
            request = urllib2.Request(url, data=json.dumps(body))
            request.add_header("Content-Type",'application/json;charset=utf-8')
            request.get_method = lambda: method
            try:
                connection = opener.open(request)
                print(connection.read())
            except urllib2.HTTPError, error:
                print(error)
Q
qinyening 已提交
121

U
Ulric Qin 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    @classmethod
    def send_feishu(cls, payload):
        users = payload.get('event').get("notify_users_obj")

        tokens = {}
        phones = {}

        for u in users:
            if u.get("phone"):
                phones[u.get("phone")] = 1

            contacts = u.get("contacts")
            if contacts.get("feishu_robot_token", ""):
                tokens[contacts.get("feishu_robot_token", "")] = 1

        opener = urllib2.build_opener(urllib2.HTTPHandler())
        method = "POST"

        for t in tokens:
            url = "https://open.feishu.cn/open-apis/bot/v2/hook/{}".format(t)
            body = {
                "msg_type": "text",
                "content": {
                    "text": payload.get('tpls').get("feishu.tpl", "feishu.tpl not found")
                },
                "at": {
                    "atMobiles": phones.keys(),
                    "isAtAll": False
                }
            }
            request = urllib2.Request(url, data=json.dumps(body))
            request.add_header("Content-Type",'application/json;charset=utf-8')
            request.get_method = lambda: method
            try:
                connection = opener.open(request)
                print(connection.read())
            except urllib2.HTTPError, error:
                print(error)

U
UlricQin 已提交
161 162 163 164 165 166 167 168 169
    @classmethod
    def send_sms(cls, payload):
        users = payload.get('event').get("notify_users_obj")
        phones = {}
        for u in users:
            if u.get("phone"):
                phones[u.get("phone")] = 1
        if phones:
            print("send_sms not implemented, phones: {}".format(phones.keys()))
170

U
UlricQin 已提交
171 172 173 174 175 176 177 178 179
    @classmethod
    def send_voice(cls, payload):
        users = payload.get('event').get("notify_users_obj")
        phones = {}
        for u in users:
            if u.get("phone"):
                phones[u.get("phone")] = 1
        if phones:
            print("send_voice not implemented, phones: {}".format(phones.keys()))
Q
qinyening 已提交
180

U
UlricQin 已提交
181 182 183 184 185 186 187 188 189 190 191
def main():
    payload = json.load(sys.stdin)
    with open(".payload", 'w') as f:
        f.write(json.dumps(payload, indent=4))
    for ch in payload.get('event').get('notify_channels'):
        send_func_name = "send_{}".format(notify_channel_funcs.get(ch.strip()))
        if not hasattr(Sender, send_func_name):
            print("function: {} not found", send_func_name)
            continue
        send_func = getattr(Sender, send_func_name)
        send_func(payload)
Q
qinyening 已提交
192

U
UlricQin 已提交
193 194
def hello():
    print("hello nightingale")
Q
qinyening 已提交
195 196 197 198

if __name__ == "__main__":
    if len(sys.argv) == 1:
        main()
U
UlricQin 已提交
199 200
    elif sys.argv[1] == "hello":
        hello()
Q
qinyening 已提交
201
    else:
U
UlricQin 已提交
202
        print("I am confused")