11#! /usr/bin/env python
22# -*- coding: utf-8 -*-
33
4+ #from __future__ import unicode_literals
45import urllib ,urllib2
56import json
67import sys
1213
1314'''
1415##########################################################
15- # 微信企业号推送消息 #
16+ # 微信企业号推送消息 #
1617# #
17- 18- # 作者博客: https://anjia.ml/ #
18+ 19+ # 作者博客: https://anjia.ml/ #
1920# Github: https://github.com/anjia0532/weixin-qiye-alert #
2021# #
2122##########################################################
2223'''
2324class WeChatAlerter (Alerter ):
2425
25- #企业号id,secret,应用id必填
26+ #企业号id,secret,应用id必填
27+
2628 required_options = frozenset (['corp_id' ,'secret' ,'agent_id' ])
2729
2830 def __init__ (self , * args ):
2931 super (WeChatAlerter , self ).__init__ (* args )
30- self .corp_id = self .rule .get ('corp_id' , '' ) #企业号id
31- self .secret = self .rule .get ('secret' , '' ) #secret
32- self .agent_id = self .rule .get ('agent_id' , '' ) #应用id
32+ self .corp_id = self .rule .get ('corp_id' , '' ) #企业号id
33+ self .secret = self .rule .get ('secret' , '' ) #secret
34+ self .agent_id = self .rule .get ('agent_id' , '' ) #应用id
3335
34- self .party_id = self .rule .get ('party_id' ) #部门id
35- self .user_d = self .rule .get ('user_d' , '' ) #用户id,多人用 | 分割,全部用 @all
36- self .tag_id = self .rule .get ('tag_id' , '' ) #标签id
36+ self .party_id = self .rule .get ('party_id' ) #部门id
37+ self .user_d = self .rule .get ('user_d' , '' ) #用户id,多人用 | 分割,全部用 @all
38+ self .tag_id = self .rule .get ('tag_id' , '' ) #标签id
3739 self .access_token = '' #微信身份令牌
3840 #self.expires_in=datetime.datetime.now() - datetime.timedelta(seconds=60)
39-
40- self .headers = {'content-type' : 'application/json' }
4141
4242 def create_default_title (self , matches ):
4343 subject = 'ElastAlert: %s' % (self .rule ['name' ])
4444 return subject
4545
4646 def alert (self , matches ):
47-
4847 # https://github.com/Yelp/elastalert/blob/master/elastalert/alerts.py#L236-L243
4948 body = self .create_alert_body (matches )
5049
51- # 获取微信企业号的accessToken
5250 # http://qydev.weixin.qq.com/wiki/index.php?title=AccessToken
5351 self .get_token ()
5452
55- self .send_data (body )
56-
53+ #print self.access_token
54+ #print self.expires_in
55+
56+ self .senddata (body )
5757 elastalert_logger .info ("发送消息给 %s" % (self .corp_id ))
5858
5959 def get_token (self ):
6060
61- #构建获取token的url
61+ #if self.expires_in >= datetime.datetime.now() and not self.access_token:
62+ # return self.access_token
63+
64+ #构建获取token的url
6265 get_token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + self .corp_id + '&corpsecret=' + self .secret
6366
6467 try :
65- response = requests . get (get_token_url , headers = self . headers )
66- response . raise_for_status ()
67- except RequestException as e :
68- raise EAException ( "推送微信消息--获取accessToken时失败: %s" % e )
68+ token_file = urllib2 . urlopen (get_token_url )
69+ except urllib2 . HTTPError as e :
70+ print e . code
71+ print e . read (). decode ( "utf8" )
6972 sys .exit ()
7073
71- token_json = json .loads (response .text )
74+ token_data = token_file .read ().decode ('utf-8' )
75+ token_json = json .loads (token_data )
7276 token_json .keys ()
7377
7478 #获取access_token和expires_in
@@ -77,37 +81,36 @@ def get_token(self):
7781
7882 return self .access_token
7983
80-
81- def send_data (self , content ):
84+ def senddata (self , content ):
8285
83- # 微信企业号文本消息有字符长度限制,文档上说限制1000字符,但是我实际测试,可以上传2090个字符
84- # 超长的进行截断处理
86+ # 微信企业号有字符长度限制,超长自动截断
87+
8588 if len (content ) > 2000 :
8689 content = content [:1997 ] + "..."
87-
90+
8891 send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self .access_token
8992
93+ headers = {'content-type' : 'application/json' }
94+
9095 payload = {
9196 'totag' : self .tag_id ,
9297 'msgtype' : "text" ,
9398 "agentid" : self .agent_id ,
9499 "text" :{
95- "content" : content .encode ('UTF-8' )
100+ "content" : content .encode ('UTF-8' ) #避免中文字符发送失败
96101 },
97102 "safe" :"0"
98103 }
99104
100-
101- print len (content )
102-
103105 # set https proxy, if it was provided
104106 # proxies = {'https': self.pagerduty_proxy} if self.pagerduty_proxy else None
105107 try :
106108 response = requests .post (send_url , data = json .dumps (payload , ensure_ascii = False ), headers = headers )
107109 response .raise_for_status ()
108110 except RequestException as e :
109- raise EAException ("推送微信消息失败: %s" % e )
110- elastalert_logger .info ("推送微信报警" )
111+ raise EAException ("推送消息异常: %s" % e )
112+
113+ elastalert_logger .info ("推送消息" )
111114
112115 print response .text
113116
0 commit comments