1- # encoding: utf-8
1+ #! /usr/bin/env python
2+ # -*- coding: utf-8 -*-
3+
4+ #from __future__ import unicode_literals
25import urllib ,urllib2
36import json
47import sys
58import datetime
69from elastalert .alerts import Alerter , BasicMatchString
7-
10+ from requests . exceptions import RequestException
811from elastalert .util import elastalert_logger
12+ import requests
913
1014'''
1115##########################################################
@@ -28,6 +32,7 @@ def __init__(self, *args):
2832 self .corp_id = self .rule .get ('corp_id' , '' ) #企业号id
2933 self .secret = self .rule .get ('secret' , '' ) #secret
3034 self .agent_id = self .rule .get ('agent_id' , '' ) #应用id
35+
3136 self .party_id = self .rule .get ('party_id' ) #部门id
3237 self .user_d = self .rule .get ('user_d' , '' ) #用户id,多人用 | 分割,全部用 @all
3338 self .tag_id = self .rule .get ('tag_id' , '' ) #标签id
@@ -45,7 +50,7 @@ def alert(self, matches):
4550 # http://qydev.weixin.qq.com/wiki/index.php?title=AccessToken
4651 self .get_token ()
4752
48- print self .access_token
53+ # print self.access_token
4954 #print self.expires_in
5055
5156 self .senddata (body )
@@ -77,26 +82,40 @@ def get_token(self):
7782 return self .access_token
7883
7984 def senddata (self , content ):
85+
86+ if len (content ) > 2000 :
87+ content = content [:1997 ] + "..."
88+
8089 send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self .access_token
81- send_values = {
82- "totag" :self .tag_id ,
83- "touser" :self .user_d ,
84- "toparty" : self .party_id ,
85- "msgtype" :"text" ,
86- "agentid" :self .agent_id ,
90+
91+
92+ # post to pagerduty
93+ headers = {'content-type' : 'application/json' }
94+ payload = {
95+ 'totag' : self .tag_id ,
96+ 'msgtype' : "text" ,
97+ "agentid" : self .agent_id ,
8798 "text" :{
88- "content" :content
99+ "content" : content . encode ( 'UTF-8' )
89100 },
90101 "safe" :"0"
91- }
92-
93- send_data = json .dumps (send_values , ensure_ascii = False )
102+ }
94103
95- send_request = urllib2 . Request ( send_url , send_data )
104+ print len ( content . encode ( 'UTF-8' ) )
96105
97- response = json .loads (urllib2 .urlopen (send_request ).read ())
98-
99- print str (response )
106+ # set https proxy, if it was provided
107+ # proxies = {'https': self.pagerduty_proxy} if self.pagerduty_proxy else None
108+ try :
109+ response = requests .post (send_url , data = json .dumps (payload , ensure_ascii = False ), headers = headers )
110+ # response.raise_for_status()
111+ except RequestException as e :
112+ raise EAException ("Error posting to pagerduty: %s" % e )
113+ elastalert_logger .info ("Trigger sent to PagerDuty" )
114+
115+ print "-----"
116+ print response .text
117+ print "-----"
118+
100119
101120 def get_info (self ):
102121 return {'type' : 'WeChatAlerter' }
0 commit comments