def wechat(): signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId) if request.method == 'GET': echo_str = request.args.get('echostr', '') try: echo_str = crypto.check_signature( signature, timestamp, nonce, echo_str ) except InvalidSignatureException: abort(403) return echo_str else: try: msg = crypto.decrypt_message( request.data, signature, timestamp, nonce ) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg).render() else: reply = create_reply('Can not handle this for now', msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res
def app_main(request): #获取要设置的微信 wx_name = request.args.get('wx') TOKEN = wx_conf[wx_name]['TOKEN'] EncodingAESKey = wx_conf[wx_name]['EncodingAESKey'] AppId = wx_conf[wx_name]['AppId'] signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, AppId) if request.method == 'GET': echo_str = request.args.get('echostr', '') try: echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str) except InvalidSignatureException: abort(403) return echo_str else: try: msg = crypto.decrypt_message(request.data, signature, timestamp, nonce) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) if msg.type == 'text': res = msg.content reply = create_reply(res, msg).render() else: reply = create_reply('Can not handle this for now', msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res
def receive_msg(): signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId) if request.method == 'GET': echo_str = request.args.get('echostr', '') try: echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str) print(echo_str) print('Success') except InvalidSignatureException: abort(403) return echo_str else: try: msg = crypto.decrypt_message(request.data, signature, timestamp, nonce) msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg).render() else: reply = create_reply('Can not handle this for now', msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res except (InvalidSignatureException, InvalidCorpIdException): abort(403)
def wechat(): signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId) if request.method == 'GET': echo_str = request.args.get('echostr', '') try: echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str) except InvalidSignatureException: abort(403) return echo_str else: try: msg = crypto.decrypt_message(request.data, signature, timestamp, nonce) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg).render() else: reply = create_reply('Can not handle this for now', msg).render() res = make_response(crypto.encrypt_message(reply, nonce, timestamp)) res.headers['Content-Type'] = 'application/xml' return res
def do_POST(self): logging.info('POST request from %s', str(self.client_address)) self._set_response() params = parse_qs(urlparse(self.path).query) content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) try: msg_signature = params['msg_signature'][0] timestamp = params['timestamp'][0] nonce = params['nonce'][0] decrypted_xml = crypto.decrypt_message(post_data, msg_signature, timestamp, nonce) message = parse_message(decrypted_xml) reply_xml = None if message.type != 'text' and message.type != 'event': reply_xml = create_reply('不支持的消息类型', message).render() elif message.type == 'event' and message.event == 'click': if message.key == 'login_jd': if message.source not in qrcode_pending: reply_xml = create_reply('使用京东App扫描下方二维码登录(有效期3分钟)', message).render() if reply_xml: encrypted_xml = crypto.encrypt_message(reply_xml, nonce, timestamp) self.wfile.write(encrypted_xml.encode()) if message.type == 'event' and message.event == 'click': if message.key == 'login_jd': if message.source not in qrcode_pending: qrcode_pending.add(message.source) send_jd_qrcode(message.source) elif message.key == 'invite_link': send_invite_link(message.source) except InvalidSignatureException as e: logging.exception('Failed to process the POST request')
def wechat(self, **args): signature = args.get('msg_signature', '') timestamp = args.get('timestamp', '') nonce = args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId) if request.httprequest.method == 'GET': echo_str = args.get('echostr', '') try: echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str) except InvalidSignatureException: reply = u'抱歉,签名解析失败' return echo_str else: try: msg = crypto.decrypt_message(request.httprequest.data, signature, timestamp, nonce) except (InvalidSignatureException, InvalidCorpIdException): reply = u'抱歉,请求解析失败' msg = parse_message(msg) if msg.type == 'text': return_val = msg.content if re.match(r'^[D](\d){6}', msg.content, re.I): return_val = self.atuo_log_in(msg) reply = create_reply(return_val, msg).render() elif msg.type == 'event' and msg.event == 'scancode_waitmsg' and msg.scan_type == 'qrcode': reply = create_reply(self._login(msg)).render() elif msg.type == 'event' and msg.event == 'view': reply = create_reply(u'成功').render() else: reply = create_reply(u'不可以支持当前类型', msg).render() return crypto.encrypt_message(reply, nonce, timestamp)
def text_action(msg): action = msg.content if action.startswith('sc'): # 控制服务指令 ret = create_reply('服务控制 {}'.format(action), msg).render() else: ret = create_reply('未能识别的指令', msg).render() return ret
def handle_encrypt(self, **kwargs): msg_signature = request.params.get('msg_signature', '') signature = request.params.get('signature', '') timestamp = request.params.get('timestamp', '') nonce = request.params.get('nonce', '') encrypt_type = request.params.get('encrypt_type', 'raw') echo_str = request.args.get('echostr', '') try: check_signature(self.TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': return echo_str # POST if encrypt_type == 'raw': # plaintext mode msg = parse_message(request.httprequest.data) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return reply.render() else: # encryption mode from wechatpy.crypto import WeChatCrypto crypto = WeChatCrypto(self.TOKEN, self.AES_KEY, self.APPID) # 公众号 try: msg = crypto.decrypt_message( request.httprequest.data, msg_signature, timestamp, nonce ) except (InvalidSignatureException, InvalidAppIdException): abort(403) else: msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return crypto.encrypt_message(reply.render(), nonce, timestamp)
def wechat(): signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(Token, EncodingAESKey, corpid) if request.method == 'GET': echo_str = request.args.get('echostr', '') try: echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str) except InvalidSignatureException: abort(403) print(echo_str) return echo_str else: try: msg = crypto.decrypt_message(request.data, signature, timestamp, nonce) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) user_name = msg.source if msg.type == 'text': message = msg.content rep = process_message(message) reply = create_reply(rep, msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) print(res) return res
def wechat(): signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId) if request.method == 'GET': # 验证 echo_str = request.args.get('echostr', '') try: echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str) except InvalidSignatureException: abort(403) return echo_str else: # 接收消息 try: msg = crypto.decrypt_message(request.data, signature, timestamp, nonce) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) if msg.type == 'text': # 文本消息 # reply = create_reply('点击下面的按钮进行操作!', msg).render() reply = text_action(msg) elif msg.type == 'event': # 按钮事件 reply = click_action(msg) else: reply = create_reply('暂时不支持的消息类型!', msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res
def process_debug(self, request, code, msg_signature, timestamp, nonce, msg=None, echostr=None): _logger.debug('WeChat Enterprise connected: code=%s, msg_signature=%s, timestamp=%s, nonce=%s, echostr=%s', code, msg_signature, timestamp, nonce, echostr) request.uid = 1 application_obj = request.registry['odoosoft.wechat.enterprise.application'] application = application_obj.search(request.cr, request.uid, [('code', '=', code)], context=request.context) if not application: _logger.warning('Cant not find application.') abort(403) else: application = application_obj.browse(request.cr, request.uid, application[0], context=request.context) # wechat_crypto = WeChatCrypto(application.token, application.ase_key, application.account.corp_id) try: reply_msg = application.process_request(msg) if reply_msg: # if isinstance(reply_msg, list): # reply_msg = reply_msg[0] reply = create_reply(reply_msg, msg).render() _logger.info('reply_msg is %s', reply) request.registry['odoosoft.wechat.enterprise.log'].log_info(request.cr, 1, u'过滤器', reply, context=request.context) return '' else: request.registry['odoosoft.wechat.enterprise.log'].log_info(request.cr, 1, u'过滤器', 'reply_msg is None', context=request.context) _logger.info('reply_msg is None') except Exception, e: _logger.error('process_request error: %s', e) request.registry['odoosoft.wechat.enterprise.log'].log_info(request.cr, 1, u'过滤器', 'process_request error: %s' % e, context=request.context) return ''
def process(self, request, code, msg_signature, timestamp, nonce, echostr=None): _logger.debug( 'WeChat Enterprise connected: code=%s, msg_signature=%s, timestamp=%s, nonce=%s, echostr=%s', code, msg_signature, timestamp, nonce, echostr) request.uid = 1 application_obj = request.registry['wechat.enterprise.application'] application = application_obj.search(request.cr, request.uid, [('code', '=', code)], context=request.context) if not application: _logger.warning('Cant not find application.') abort(403) else: application = application_obj.browse(request.cr, request.uid, application[0], context=request.context) wechat_crypto = WeChatCrypto(application.token, application.ase_key, application.account.corp_id) if request.httprequest.method == 'GET': echo_str = '' try: echo_str = wechat_crypto.check_signature( msg_signature, timestamp, nonce, echostr) except InvalidSignatureException: _logger.warning('check_signature fail.') abort(403) return echo_str else: try: msg = wechat_crypto.decrypt_message(request.httprequest.data, msg_signature, timestamp, nonce) msg = parse_message(msg) reply_msg = application.process_request(msg)[0] if reply_msg: # if isinstance(reply_msg, list): # reply_msg = reply_msg[0] reply = create_reply(reply_msg, msg).render() return wechat_crypto.encrypt_message( reply, nonce, timestamp) else: _logger.info('reply None! msg= %s, reply_msg= %s', msg, reply_msg) return '' except (InvalidSignatureException, InvalidCorpIdException), e: _logger.warning('decrypt_message fail. %s', e) abort(403) except Exception, e: _logger.error('process_request error: %s', e) abort(403)
def click_action(msg): action = msg.key if action == 'click001': vps_info = vmStatus() hdd = vps_info['hdd'] hdd_usage = hdd.split(',')[3] bw = vps_info['bw'] bw_usage = bw.split(',')[3] vmstat = vps_info['vmstat'] ret_msg = "主机状态: {}\n带宽已使用: {}% \n磁盘已使用: {}%".format( vmstat, bw_usage, hdd_usage) rep = create_reply(ret_msg, msg).render() elif action == 'click002': rep = create_reply('通过API获取VPS面板信息.', msg).render() elif action in ["boot", "shutdown", "reboot"]: print(action) vmctl(action) rep = create_reply("操作成功, 稍后刷新状态查看", msg).render() return rep
def handle(self, **kwargs): msg_signature = request.params.get("msg_signature") timestamp = request.params.get("timestamp") nonce = request.params.get("nonce") echo_str = request.params.get('echostr', '') if request.httprequest.method == 'GET': try: echo_str = self.crypto.decrypt_message( {'Encrypt': echo_str}, msg_signature, timestamp, nonce ) except InvalidSignatureException: abort(403) return echo_str # POST msg = None try: msg = self.crypto.decrypt_message( request.httprequest.data, msg_signature, timestamp, nonce ) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) ss = '>>> handle msg: %s %s %s'%(msg.type, msg.id, msg) _logger.info(ss) ret = '' if msg.type in ['text', 'image', 'voice', 'location']: #reply = create_reply(msg.content, msg).render() from .handlers.text_handler import kf_handler ret = kf_handler(request, msg) elif msg.type == 'event': if msg.event=='subscribe': from .handlers.event_handler import subscribe_handler ret = subscribe_handler(request, msg) elif msg.event=='unsubscribe': from .handlers.event_handler import unsubscribe_handler ret = unsubscribe_handler(request, msg) elif msg.type == 'unknown': data = msg._data if data.get('Event')=='open_approval_change': from .handlers.approval_handler import approval_handler approval_handler(request, msg) reply = create_reply(ret, msg).render() res = self.crypto.encrypt_message(reply, request.params.get("nonce"), request.params.get("timestamp")) return res
def process(self, request, code, msg_signature, timestamp, nonce, echostr=None): _logger.debug('WeChat Enterprise connected: code=%s, msg_signature=%s, timestamp=%s, nonce=%s, echostr=%s', code, msg_signature, timestamp, nonce, echostr) request.uid = 1 application_obj = request.registry['wechat.enterprise.application'] application = application_obj.search(request.cr, request.uid, [('code', '=', code)], context=request.context) if not application: _logger.warning('Cant not find application.') abort(403) else: application = application_obj.browse(request.cr, request.uid, application[0], context=request.context) wechat_crypto = WeChatCrypto(application.token, application.ase_key, application.account.corp_id) if request.httprequest.method == 'GET': echo_str = '' try: echo_str = wechat_crypto.check_signature( msg_signature, timestamp, nonce, echostr ) except InvalidSignatureException: _logger.warning('check_signature fail.') abort(403) return echo_str else: try: msg = wechat_crypto.decrypt_message( request.httprequest.data, msg_signature, timestamp, nonce ) msg = parse_message(msg) reply_msg = application.process_request(msg)[0] if reply_msg: # if isinstance(reply_msg, list): # reply_msg = reply_msg[0] reply = create_reply(reply_msg, msg).render() return wechat_crypto.encrypt_message(reply, nonce, timestamp) else: _logger.info('reply None! msg= %s, reply_msg= %s', msg, reply_msg) return '' except (InvalidSignatureException, InvalidCorpIdException), e: _logger.warning('decrypt_message fail. %s', e) abort(403) except Exception, e: _logger.error('process_request error: %s', e) abort(403)
def handle(self, **kwargs): msg_signature = request.params.get("msg_signature") timestamp = request.params.get("timestamp") nonce = request.params.get("nonce") echo_str = request.params.get('echostr', '') if request.method == 'GET': try: echo_str = crypto.check_signature( msg_signature, #新增 timestamp, nonce, echo_str ) except InvalidSignatureException: abort(403) # POST try: msg = crypto.decrypt_message( request.httprequest.data, msg_signature, timestamp, nonce ) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg).render() else: reply = create_reply('Can not handle this for now', msg).render() res = crypto.encrypt_message(reply, request.params.get("nonce"), request.params.get("timestamp")) return res
def handle(self, **kwargs): msg_signature = request.params.get("msg_signature") timestamp = request.params.get("timestamp") nonce = request.params.get("nonce") echo_str = request.params.get('echostr', '') if request.httprequest.method == 'GET': try: echo_str = crypto.check_signature( msg_signature, #新增 timestamp, nonce, echo_str ) except InvalidSignatureException: abort(403) return echo_str # POST try: msg = crypto.decrypt_message( request.httprequest.data, msg_signature, timestamp, nonce ) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) ss = '------------------%s %s'%(msg.type, msg) _logger.info(ss) ret = '' if msg.type == 'text': #reply = create_reply(msg.content, msg).render() from .handlers.text_handler import kf_handler ret = kf_handler(request, msg.content, msg.source) elif msg.type == 'event': if msg.event=='subscribe': from .handlers.event_handler import subscribe_handler ret = subscribe_handler(request, msg) elif msg.event=='unsubscribe': from .handlers.event_handler import unsubscribe_handler ret = unsubscribe_handler(request, msg) reply = create_reply(ret, msg).render() res = crypto.encrypt_message(reply, request.params.get("nonce"), request.params.get("timestamp")) return res
def handle(self, **kwargs): msg_signature = request.params.get("msg_signature") timestamp = request.params.get("timestamp") nonce = request.params.get("nonce") echo_str = request.params.get('echostr', '') if request.httprequest.method == 'GET': try: echo_str = self.crypto.check_signature( msg_signature, #新增 timestamp, nonce, echo_str ) except InvalidSignatureException: abort(403) return echo_str # POST msg = None try: msg = self.crypto.decrypt_message( request.httprequest.data, msg_signature, timestamp, nonce ) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) ss = '------------------%s %s'%(msg.type, msg) _logger.info(ss) ret = '' if msg.type == 'text': #reply = create_reply(msg.content, msg).render() from .handlers.text_handler import kf_handler ret = kf_handler(request, msg.content, msg.source) elif msg.type == 'event': if msg.event=='subscribe': from .handlers.event_handler import subscribe_handler ret = subscribe_handler(request, msg) elif msg.event=='unsubscribe': from .handlers.event_handler import unsubscribe_handler ret = unsubscribe_handler(request, msg) reply = create_reply(ret, msg).render() res = self.crypto.encrypt_message(reply, request.params.get("nonce"), request.params.get("timestamp")) return res
def __app_weixin(request): from wechatpy.enterprise.crypto import WeChatCrypto from wechatpy.exceptions import InvalidSignatureException from wechatpy.enterprise.exceptions import InvalidCorpIdException from wechatpy.enterprise import parse_message, create_reply TOKEN=wx_conf[wx_name]['TOKEN'] EncodingAESKey=wx_conf[wx_name]['EncodingAESKey'] AppId=wx_conf[wx_name]['AppId'] signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, AppId) if request.method == 'GET': echo_str = request.args.get('echostr', '') try: echo_str = crypto.check_signature( signature, timestamp, nonce, echo_str ) except InvalidSignatureException: abort(403) return echo_str else: try: msg = crypto.decrypt_message( request.data, signature, timestamp, nonce ) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) reply = create_reply(func(msg), msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res
def wechat(): signature = request.args.get('msg_signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId) if request.method == 'GET': echo_str = request.args.get('echostr', '') try: echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str) except InvalidSignatureException: abort(403) return echo_str else: try: msg = crypto.decrypt_message(request.data, signature, timestamp, nonce) except (InvalidSignatureException, InvalidCorpIdException): abort(403) msg = parse_message(msg) user_name = msg.source help_message = """ 未识别的命令.目前已支持的命令为: !问题 : 获取当前存在的问题列表 !监控信息,[获取主机名]/[获取监控项]/ !监控信息,主机名(datanode01),监控项 ... """ if msg.type == 'text': message = msg.content if message == 'help': reply = create_reply(help_message, msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res if message.find('!') == 0: #这里进入到命令匹配模式 if "!问题" in message or "!获取问题" in message: import time zabbix = ZabbixGraph() events = zabbix.get_cur_problems() evt_str = "\n".join([ "{:<20}{:<25}{}".format( e['eventid'], str( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int( e['clock'])))), e['name']) for e in events ]) reply = create_reply(evt_str, msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res else: if "!监控信息" in message: zabbix = ZabbixGraph() message_list = message.split(',') if len(message_list) == 2: message_c = message_list[1] if "获取主机名" == message_c: hosts = zabbix.get_hosts() message = "\n".join(hosts) if "获取监控项" == message_c: hosts = zabbix.get_graphs(10257) message = "\n".join(hosts) elif len(message_list) == 3: hostname = message_list[1] item = message_list[2] hostids = zabbix.get_host_id(hostname) for h in hostids: gids = zabbix.get_graph_id(h, item) for gid in gids: values = {"graphid": gid} fpath = zabbix.GetGraph( values, config.TMP_DIR) print(fpath) with open(fpath, 'rb') as ff: resp = WeChatMedia( client=client).upload("image", ff) media_id = resp["media_id"] reply = ImageReply( media_id=media_id).render() res = crypto.encrypt_message( reply, nonce, timestamp) return res else: message = help_message reply = create_reply(message, msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res else: rep = talks_robot(msg) reply = create_reply(rep, msg).render() res = crypto.encrypt_message(reply, nonce, timestamp) return res return ''