@@ -45,16 +45,19 @@ def create_default_title(self, matches):
4545
4646 def alert (self , matches ):
4747
48+ if not self .party_id and not self .user_id and not self .tag_id :
49+ elastalert_logger .warn ("All touser & toparty & totag invalid" )
50+
4851 # 参考elastalert的写法
4952 # https://github.com/Yelp/elastalert/blob/master/elastalert/alerts.py#L236-L243
50-
5153 body = self .create_alert_body (matches )
5254
5355 # 微信企业号获取Token文档
5456 # http://qydev.weixin.qq.com/wiki/index.php?title=AccessToken
5557 self .get_token ()
5658
5759 self .senddata (body )
60+
5861 elastalert_logger .info ("send message to %s" % (self .corp_id ))
5962
6063 def get_token (self ):
@@ -69,16 +72,15 @@ def get_token(self):
6972 try :
7073 token_file = urllib2 .urlopen (get_token_url )
7174 except urllib2 .HTTPError as e :
72- print e .code
73- print e .read ().decode ("utf8" )
75+ raise EAException ("get access_token failed , http code : %s, http response content:%s" % e .code ,e .read ().decode ("utf8" ))
7476 sys .exit ()
7577
7678 token_data = token_file .read ().decode ('utf-8' )
7779 token_json = json .loads (token_data )
7880 token_json .keys ()
7981
8082 if token_json ['access_token' ] is None :
81- print token_data
83+ elastalert_logger . warn ( "get access_token failed , the response is : %s" % token_data )
8284 sys .exit ()
8385
8486 #获取access_token和expires_in
@@ -93,16 +95,17 @@ def senddata(self, content):
9395
9496 if len (content ) > 2000 :
9597 content = content [:1997 ] + "..."
98+
9699 # 微信发送消息文档
97100 # http://qydev.weixin.qq.com/wiki/index.php?title=%E6%B6%88%E6%81%AF%E7%B1%BB%E5%9E%8B%E5%8F%8A%E6%95%B0%E6%8D%AE%E6%A0%BC%E5%BC%8F
98101 send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self .access_token
99102
100103 headers = {'content-type' : 'application/json' }
101104
102105 payload = {
103- "touser" : self .user_id , #用户账户,建议使用tag
104- "toparty" : self .party_id , #部门id,建议使用tag
105- "totag" : self .tag_id , #tag可以很灵活的控制发送群体细粒度。比较理想的推送应该是,在heartbeat或者其他elastic工具自定义字段,添加标签id。这边根据自定义的标签id,进行推送
106+ "touser" : self .user_id and self . user_id or '' , #用户账户,建议使用tag
107+ "toparty" : self .party_id and self . party_id or '' , #部门id,建议使用tag
108+ "totag" : self .tag_id and self . tag_id or '' , #tag可以很灵活的控制发送群体细粒度。比较理想的推送应该是,在heartbeat或者其他elastic工具自定义字段,添加标签id。这边根据自定义的标签id,进行推送
106109 'msgtype' : "text" ,
107110 "agentid" : self .agent_id ,
108111 "text" :{
@@ -118,11 +121,9 @@ def senddata(self, content):
118121 response = requests .post (send_url , data = json .dumps (payload , ensure_ascii = False ), headers = headers )
119122 response .raise_for_status ()
120123 except RequestException as e :
121- raise EAException ("推送消息异常 : %s" % e )
124+ raise EAException ("send message has error : %s" % e )
122125
123- elastalert_logger .info ("推送消息" )
124-
125- print response .text
126+ elastalert_logger .info ("send msg and response: %s" % response .text )
126127
127128
128129 def get_info (self ):
0 commit comments