Skip to content

Commit

Permalink
添加自定义报警功能
Browse files Browse the repository at this point in the history
  • Loading branch information
chao ma committed Sep 19, 2017
1 parent 0f1fd94 commit 42cdf35
Show file tree
Hide file tree
Showing 8 changed files with 183 additions and 195 deletions.
8 changes: 6 additions & 2 deletions controller/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const (
DEFAULT_WORKER_COUNT = 5
DEFAULT_ACTION_TIMEOUT = 60
DEFAULT_SEND_NOTIFICATIONS_DIR = "./scripts/notifications/"
DEFAULT_SEND_ATIONS_DIR = "./scripts/actions/"
DEFAULT_SEND_MAIL_SCRIPT = "send_mail.py"
DEFAULT_SEND_SMS_SCRIPT = "send_sms.py"
DEFAULT_SEND_WECHAT_SCRIPT = "send_wechat.py"
Expand Down Expand Up @@ -75,7 +76,9 @@ type Config struct {

SEND_CALL_SCRIPT string //打电话的脚本

SEND_NOTIFICATIONS_DIR string //自定义脚本的目录
SEND_NOTIFICATIONS_DIR string //原有默认发送通知脚本目录

SEND_ATIONS_DIR string //自定义脚本的目录

SEND_INTERVAL int //发送消息间隔时间单位毫秒

Expand All @@ -97,7 +100,7 @@ func InitGlobalConfig() error {
MYSQL_PASSWORD: cfg.MustValue(goconfig.DEFAULT_SECTION, "mysql_password", DEFAULT_MYSQL_PASSWORD),
MYSQL_MAX_CONN: cfg.MustInt(goconfig.DEFAULT_SECTION, "mysql_max_conn", DEFAULT_MAX_CONN),
MYSQL_MAX_IDLE_CONN: cfg.MustInt(goconfig.DEFAULT_SECTION, "mysql_max_idle_conn", DEFAULT_MAX_IDLE_CONN),
LOG_FILE: cfg.MustValue(goconfig.DEFAULT_SECTION, "log_file", "./logs/controller.log", DEFAULT_LOG_FILE),
LOG_FILE: cfg.MustValue(goconfig.DEFAULT_SECTION, "log_file", DEFAULT_LOG_FILE),
LOG_EXPIRE_DAYS: cfg.MustInt(goconfig.DEFAULT_SECTION, "log_expire_days", DEFAULT_LOG_EXPIRE_DAYS),
LOG_LEVEL: cfg.MustInt(goconfig.DEFAULT_SECTION, "log_level", DEFAULT_LOG_LEVEL),
MAX_PACKET_SIZE: cfg.MustInt(goconfig.DEFAULT_SECTION, "max_packet_size", DEFAULT_MAX_PACKET_SIZE),
Expand All @@ -113,6 +116,7 @@ func InitGlobalConfig() error {
SEND_WECHAT_SCRIPT: cfg.MustValue(goconfig.DEFAULT_SECTION, "send_wechat_script", DEFAULT_SEND_WECHAT_SCRIPT),
SEND_CALL_SCRIPT: cfg.MustValue(goconfig.DEFAULT_SECTION, "send_call_script", DEFAULT_SEND_CALL_SCRIPT),
SEND_NOTIFICATIONS_DIR: cfg.MustValue(goconfig.DEFAULT_SECTION, "send_notifications_dir", DEFAULT_SEND_NOTIFICATIONS_DIR),
SEND_ATIONS_DIR: cfg.MustValue(goconfig.DEFAULT_SECTION, "send_ations_dir", DEFAULT_SEND_ATIONS_DIR),
SEND_INTERVAL: cfg.MustInt(goconfig.DEFAULT_SECTION, "send_interval", DEFAULT_SEND_INTERVAL),
SEND_SWITCH: cfg.MustBool(goconfig.DEFAULT_SECTION, "send_switch", DEFAULT_SEND_SWITCH),
SEND_MAX: cfg.MustInt(goconfig.DEFAULT_SECTION, "send_max", DEFAULT_SEND_MAX),
Expand Down
5 changes: 4 additions & 1 deletion controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ func (this *Controller) sendToQueue(strategy_event_id int64, subject, content st
params = append(params, user.Phone)
this.callQueue.PutNoWait(&QueueTask{strategy_event_id, file_path, params, action, user})
case SEND_ACTION:
file_path := filepath.Join(GlobalConfig.SEND_NOTIFICATIONS_DIR, action.FilePath)
file_path := filepath.Join(GlobalConfig.SEND_ATIONS_DIR, action.FilePath)
user_info, err := json.Marshal(user)
if err != nil {
lg.Error(err.Error())
Expand Down Expand Up @@ -552,6 +552,9 @@ func generateEvent(strategy_event *StrategyEvent, strategy_result *StrategyResul
merged_strategy_event.ID = strategy_event.ID
merged_strategy_event.Count = strategy_event.Count
merged_strategy_event.Status = strategy_event.Status
merged_strategy_event.ProcessUser = strategy_event.ProcessUser
merged_strategy_event.ProcessComments = strategy_event.ProcessComments
merged_strategy_event.ProcessTime = strategy_event.ProcessTime
}

return
Expand Down
168 changes: 128 additions & 40 deletions controller/scripts/notifications/send_call.py
Original file line number Diff line number Diff line change
@@ -1,51 +1,139 @@
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#! /usr/bin/env python2
# encoding:utf-8

import httplib
import json
import random
import time
import hashlib
import argparse
import urllib2
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

SERVICE_TOKEN = ""


def send(subject, content, receiver):
api = "http://www.linkedsee.com/alarm/channel"
data = dict()
data["receiver"] = receiver
data["type"] = "phone"
data["title"] = subject
data["content"] = content
try:
data = json.dumps(data, ensure_ascii=False).encode("utf-8")
req = urllib2.Request(api, data)
req.add_header("Servicetoken", SERVICE_TOKEN)
res = urllib2.urlopen(req)
result = json.loads(res.read(), encoding="utf-8")
if "status" in result and not result["status"]:
return False, json.dumps(result, ensure_ascii=False).encode("utf-8")
except Exception as e:
return False, e

return True, json.dumps(result, ensure_ascii=False).encode("utf-8")

'''语音通知发送'''
class VoicePromptSender:
appid = 0
appkey = ""
url = "/v5/tlsvoicesvr/sendvoiceprompt"
template = "电话报警:"
def __init__(self, appid, appkey):
self.appid = appid
self.appkey = appkey
self.util = SmsSenderUtil()

""" 语音验证码发送
Returns:
请求包体
{
"tel": {
"nationcode": "86", //国家码
"mobile": "13788888888" //手机号码
},
"prompttype": 2, //语音类型,目前固定为2
"promptfile": "语音内容文本", //通知内容,utf8编码,支持中文英文、数字及组合,需要和语音内容模版相匹配
"playtimes": 2, //播放次数,可选,最多3次,默认2次
"sig": "30db206bfd3fea7ef0db929998642c8ea54cc7042a779c5a0d9897358f6e9505", //app凭证,具体计算方式见下注
"time": 1457336869, //unix时间戳,请求发起时间,如果和系统时间相差超过10分钟则会返回失败
"ext": "" //用户的session内容,腾讯server回包中会原样返回,可选字段,不需要就填空。
}
应答包体
{
"result": 0, //0表示成功,非0表示失败
"errmsg": "OK", //result非0时的具体错误信息
"ext": "", //用户的session内容,腾讯server回包中会原样返回
"callid": "xxxx" //标识本次发送id,标识一次下发记录
}
参数说明:
nation_code: 国家码,如 86 为中国
phone_number: 不带国家码的手机号
msg: 信息内容,必须与申请的模板格式一致,否则将返回错误
ext: 服务端原样返回的参数,可填空串
"""
def send(self,nation_code, phone_number,playtimes,msg, ext):
rnd = self.util.get_random()
cur_time = self.util.get_cur_time()

data = {}
tel = {"nationcode": nation_code, "mobile": phone_number}
data["tel"] = tel
data["prompttype"] = 2
data["promptfile"] = msg
data["playtimes"] = playtimes
data["sig"] = hashlib.sha256("appkey=" + self.appkey + "&random=" + str(rnd)
+ "&time=" + str(cur_time) + "&mobile=" + phone_number).hexdigest()
data["time"] = cur_time
data["ext"] = ext

whole_url = self.url + "?sdkappid=" + str(self.appid) + "&random=" + str(rnd)
result = self.util.send_post_request("yun.tim.qq.com", whole_url, data)
obj = json.loads(result)
if obj["result"] == "0" and obj["errmsg"] == "OK":
return True, result
else:
return False, result

class SmsSenderUtil:
""" 工具类定义 """

def get_random(self):
return random.randint(100000, 999999)

def get_cur_time(self):
return long(time.time())

def calculate_sig(self, appkey, rnd, cur_time, phone_numbers):
phone_numbers_string = phone_numbers[0]
for i in range(1, len(phone_numbers)):
phone_numbers_string += "," + phone_numbers[i]
return hashlib.sha256("appkey=" + appkey + "&random=" + str(rnd) + "&time=" + str(cur_time)
+ "&mobile=" + phone_numbers_string).hexdigest()

def calculate_sig_for_templ_phone_numbers(self, appkey, rnd, cur_time, phone_numbers):
""" 计算带模板和手机号列表的 sig """
phone_numbers_string = phone_numbers[0]
for i in range(1, len(phone_numbers)):
phone_numbers_string += "," + phone_numbers[i]
return hashlib.sha256("appkey=" + appkey + "&random=" + str(rnd) + "&time="
+ str(cur_time) + "&mobile=" + phone_numbers_string).hexdigest()

def calculate_sig_for_templ(self, appkey, rnd, cur_time, phone_number):
phone_numbers = [phone_number]
return self.calculate_sig_for_templ_phone_numbers(appkey, rnd, cur_time, phone_numbers)

def phone_numbers_to_list(self, nation_code, phone_numbers):
tel = []
for phone_number in phone_numbers:
tel.append({"nationcode": nation_code, "mobile":phone_number})
return tel

def send_post_request(self, host, url, data):
con = None
try:
con = httplib.HTTPSConnection(host)
con.request('POST', url, json.dumps(data))
response = con.getresponse()
if '200' != str(response.status):
obj = {}
obj["result"] = -1
obj["errmsg"] = "connect failed:\t"+str(response.status) + " " + response.reason
result = json.dumps(obj)
else:
result = response.read()
except Exception,e:
obj = {}
obj["result"] = -2
obj["errmsg"] = "connect failed:\t" + str(e)
result = json.dumps(obj)
finally:
if con:
con.close()
return result

if __name__ == "__main__":
parser = argparse.ArgumentParser(description="script for sending alarm by linkedsee")
parser = argparse.ArgumentParser(description="script for sending alarm call")
parser.add_argument("subject", help="the subject of the alarm call")
parser.add_argument("content", help="the content of the alarm call")
parser.add_argument("receiver", help="the alarm to send by linkedsee")
parser.add_argument("receiver", help="the phone number who receive the call")
args = parser.parse_args()

retry = 3
while retry:
status, response = send(args.subject, args.content, args.receiver)
if status:
break
retry -= 1
if not status:
sys.exit("{0} {1}".format(status, response))

vps = VoicePromptSender(VoicePromptSender.appid, VoicePromptSender.appkey)
status, response = vps.send(86, args.receiver, 2, "{0}{1}".format(VoicePromptSender.template, args.content), "")
print status, response
148 changes: 0 additions & 148 deletions controller/scripts/notifications/send_tencent_sms.py

This file was deleted.

Loading

0 comments on commit 42cdf35

Please sign in to comment.