+ when bot fail then send mail

This commit is contained in:
urinx
2017-05-25 16:21:48 +08:00
parent 97f347b8f8
commit 123993c3cc
9 changed files with 70 additions and 14 deletions
@@ -3,3 +3,4 @@ flask
requests requests
requests_toolbelt requests_toolbelt
pymysql pymysql
sendgrid
@@ -35,6 +35,11 @@ user = root
passwd = root passwd = root
database = wechat database = wechat
[sendgrid]
api_key = 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
from_email = wxbot@wechat.com
to_email = xxx@example.com
[loggers] [loggers]
keys = root,WeChat keys = root,WeChat
+6
View File
@@ -231,6 +231,12 @@ def save_json(filename, data, dirName, mode='w+'):
return fn return fn
def load_json(filepath):
Log.debug('load json: ' + filepath)
with open(filepath, 'r') as f:
return _decode_data(json.loads(f.read()))
def pickle_save(data, file): def pickle_save(data, file):
""" """
@brief Use pickle to save python object into file @brief Use pickle to save python object into file
+1
View File
@@ -34,6 +34,7 @@ class WeChat(WXAPI):
"[#] Skey: " + self.skey + "\n" + \ "[#] Skey: " + self.skey + "\n" + \
"[#] DeviceId: " + self.device_id + "\n" + \ "[#] DeviceId: " + self.device_id + "\n" + \
"[#] PassTicket: " + self.pass_ticket + "\n" + \ "[#] PassTicket: " + self.pass_ticket + "\n" + \
"[#] Run Time: " + self.get_run_time() + '\n' + \
"=========================" "========================="
return description return description
+5 -2
View File
@@ -767,8 +767,11 @@ class WXAPI(object):
@param text String @param text String
@return Bool: whether operation succeed @return Bool: whether operation succeed
""" """
dic = self.webwxsendmsg(text, user_id) try:
return dic['BaseResponse']['Ret'] == 0 dic = self.webwxsendmsg(text, user_id)
return dic['BaseResponse']['Ret'] == 0
except:
return False
def send_img(self, user_id, file_path): def send_img(self, user_id, file_path):
""" """
+13
View File
@@ -6,6 +6,7 @@ from wechat import WeChat
from wechat.utils import * from wechat.utils import *
from wx_handler import WeChatMsgProcessor from wx_handler import WeChatMsgProcessor
from wx_handler import Bot from wx_handler import Bot
from wx_handler import SGMail
from db import SqliteDB from db import SqliteDB
from db import MysqlDB from db import MysqlDB
from config import ConfigManager from config import ConfigManager
@@ -44,6 +45,11 @@ flask_log_handler.setFormatter(formatter)
logger.addHandler(flask_log_handler) logger.addHandler(flask_log_handler)
app.logger.addHandler(flask_log_handler) app.logger.addHandler(flask_log_handler)
# sendgrid mail
sg_apikey = cm.get('sendgrid', 'api_key')
from_email = cm.get('sendgrid', 'from_email')
to_email = cm.get('sendgrid', 'to_email')
sg = SGMail(sg_apikey, from_email, to_email)
@app.route('/') @app.route('/')
def index(): def index():
@@ -260,6 +266,13 @@ while True:
Log.error(traceback.format_exc()) Log.error(traceback.format_exc())
finally: finally:
wechat.stop() wechat.stop()
# send a mail to tell the wxbot is failing
subject = 'wxbot stop message'
log_file = open(eval(cm.get('handler_fileHandler', 'args'))[0], 'r')
mail_content = '<pre>' + str(wechat) + '\n\n-----\nLogs:\n-----\n\n' + ''.join(log_file.readlines()[-100:]) + '</pre>'
sg.send_mail(subject, mail_content, 'text/html')
log_file.close()
if wechat.exit_code == 0: if wechat.exit_code == 0:
echo(Constant.MAIN_RESTART) echo(Constant.MAIN_RESTART)
+2 -1
View File
@@ -2,4 +2,5 @@
# coding: utf-8 # coding: utf-8
from wechat_msg_processor import WeChatMsgProcessor from wechat_msg_processor import WeChatMsgProcessor
from bot import Bot from bot import Bot
from sendgrid_mail import SGMail
@@ -0,0 +1,20 @@
#!/usr/bin/env python
# coding: utf-8
#===================================================
import sendgrid
from sendgrid.helpers.mail import *
#===================================================
class SGMail(object):
def __init__(self, apikey, from_email, to_email):
self.sg = sendgrid.SendGridAPIClient(apikey=apikey)
self.from_email = Email(from_email)
self.to_email = Email(to_email)
def send_mail(self, subject, plain_content, type='text/plain'):
content = Content(type, plain_content)
mail = Mail(self.from_email, subject, self.to_email, content)
response = self.sg.client.mail.send.post(request_body=mail.get())
return response.status_code == 202
@@ -195,6 +195,8 @@ class WeChatMsgProcessor(object):
if text == 'test_revoke': # 撤回消息测试 if text == 'test_revoke': # 撤回消息测试
dic = wechat.webwxsendmsg('这条消息将被撤回', uid) dic = wechat.webwxsendmsg('这条消息将被撤回', uid)
wechat.revoke_msg(dic['MsgID'], uid, dic['LocalID']) wechat.revoke_msg(dic['MsgID'], uid, dic['LocalID'])
elif text == 'reply':
wechat.send_text(uid, '自动回复')
def handle_command(self, cmd, msg): def handle_command(self, cmd, msg):
@@ -210,20 +212,22 @@ class WeChatMsgProcessor(object):
g_id = g['UserName'] g_id = g['UserName']
cmd = cmd.strip() cmd = cmd.strip()
if cmd == 'test': if cmd == 'runtime':
# wechat.send_file(g_id, 'test/Data/upload/shake.wav') wechat.send_text(g_id, wechat.get_run_time())
elif cmd == 'test_sendimg':
wechat.send_img(g_id, 'test/emotion/7.gif') wechat.send_img(g_id, 'test/emotion/7.gif')
elif cmd == 'runtime': elif cmd == 'test_sendfile':
wechat.webwxsendmsg(wechat.get_run_time(), g_id) wechat.send_file(g_id, 'test/Data/upload/shake.wav')
else: elif cmd == 'test_bot':
# reply bot # reply bot
# --------- # ---------
# if wechat.bot: if wechat.bot:
# r = wechat.bot.reply(cmd) r = wechat.bot.reply(cmd)
# if r: if r:
# wechat.webwxsendmsg(r, g_id) wechat.send_text(g_id, r)
# else: else:
# pass pass
elif cmd == 'test_emot':
img_name = [ img_name = [
'0.jpg', '1.jpeg', '2.gif', '3.jpg', '4.jpeg', '0.jpg', '1.jpeg', '2.gif', '3.jpg', '4.jpeg',
'5.gif', '6.gif', '7.gif', '8.jpg', '9.jpg' '5.gif', '6.gif', '7.gif', '8.jpg', '9.jpg'
@@ -231,6 +235,8 @@ class WeChatMsgProcessor(object):
name = img_name[int(time.time()) % 10] name = img_name[int(time.time()) % 10]
emot_path = os.path.join('test/emotion/', name) emot_path = os.path.join('test/emotion/', name)
wechat.send_emot(g_id, emot_path) wechat.send_emot(g_id, emot_path)
else:
pass
def check_schedule_task(self): def check_schedule_task(self):
# update group member list at 00:00 am every morning # update group member list at 00:00 am every morning