def post(self): msg = parse_message(request.data) # 是文本消息 if msg.type == 'text': reply = TextReply(message=msg) reply.content = 'text reply' xml = reply.render() return xml # 事件类型消息 elif msg.type == 'event': # 处理菜单点击事件 if msg.event == 'click': # MenuClick是自定义类,处理菜单点击事件 click = MenuClick(msg) return click.menu_click() # 其他类型的事件消息不处理 else: reply = TextReply(message=msg) reply.content = 'event未知' xml = reply.render() return xml # 其他消息 else: reply = TextReply(message=msg) reply.content = '未知操作' xml = reply.render() return xml
def test(self, request, message, wechat): """ 发布中测试 """ logger = getLogger('django.request.test_ProcessServerEventView') logger.info(message) if message.get('MsgType').lower() == 'event': reply = TextReply() reply.target = message['FromUserName'] reply.source = message['ToUserName'] reply.content = message['Event'] + 'from_callback' xml_str = reply.render() headers = {'CONTENT_TYPE': request.META['CONTENT_TYPE']} return Response(xml_str, headers=headers) elif message.get('MsgType').lower() in consts.MESSAGE_TYPES: if message.get('Content') == 'TESTCOMPONENT_MSG_TYPE_TEXT': reply = TextReply() reply.target = message['FromUserName'] reply.source = message['ToUserName'] reply.content = 'TESTCOMPONENT_MSG_TYPE_TEXT_callback' xml_str = reply.render() headers = {'CONTENT_TYPE': request.META['CONTENT_TYPE']} return Response(xml_str, headers=headers) elif message.get('Content').startswith('QUERY_AUTH_CODE'): from datetime import timedelta now = datetime.utcnow() + timedelta(seconds=2) query_auth_code = message.get('Content').split(':')[1] process_wechat_query_auth_code_test.apply_async( (message['FromUserName'], query_auth_code), eta=now) return Response('')
def test(self, request, message, wechat): """ 发布中测试 """ logger = getLogger('django.request.test_ProcessServerEventView') logger.info(message) if message.get('MsgType').lower() == 'event': reply = TextReply() reply.target = message['FromUserName'] reply.source = message['ToUserName'] reply.content = message['Event'] + 'from_callback' xml_str = reply.render() headers = {'CONTENT_TYPE': request.META['CONTENT_TYPE']} return Response(xml_str, headers=headers) elif message.get('MsgType').lower() in consts.MESSAGE_TYPES: if message.get('Content') == 'TESTCOMPONENT_MSG_TYPE_TEXT': reply = TextReply() reply.target = message['FromUserName'] reply.source = message['ToUserName'] reply.content = 'TESTCOMPONENT_MSG_TYPE_TEXT_callback' xml_str = reply.render() headers = {'CONTENT_TYPE': request.META['CONTENT_TYPE']} return Response(xml_str, headers=headers) elif message.get('Content').startswith('QUERY_AUTH_CODE'): from datetime import timedelta now = datetime.utcnow() + timedelta(seconds=2) query_auth_code = message.get('Content').split(':')[1] process_wechat_query_auth_code_test.apply_async( (message['FromUserName'], query_auth_code), eta=now) return Response('')
def index(): # print request.args # print json.dumps(request.args) if request.method == 'GET': data = request.args signature = data.get('signature') timestamp = data.get('timestamp') nonce = data.get('nonce') echostr = data.get('echostr') token = current_app.config.get('TOKEN') try: check_signature(token, signature, timestamp, nonce) except InvalidSignatureException: return 'invalid signature' return echostr else: xml = request.data print xml msg = parse_message(xml) if msg.type == 'text': print msg.content reply = TextReply(message=msg) reply.content = u'reply 测试' xml_reply = reply.render() return xml_reply elif msg.type == 'image': reply = ImageReply(message=msg) reply.media_id = msg.media_id xml_reply = reply.render() return xml_reply elif msg.type == 'voice': # reply = VoiceReply(message=msg) # reply.media_id = msg.media_id reply = TextReply(message=msg) reply.content = msg.recognition xml_reply = reply.render() return xml_reply elif msg.type == 'video': reply = VideoReply(message=msg) reply.media_id = msg.media_id reply.title = u'你的video' reply.description = u'wo 爱倪呀' xml_reply = reply.render() return xml_reply pass elif msg.type == 'location': pass elif msg.type == 'link': pass elif msg.type == 'shortvideo': reply = VideoReply(message=msg) reply.media_id = msg.thumb_media_id reply.title = u'你的video' reply.description = u'wo 爱倪呀' xml_reply = reply.render() return xml_reply else: return ''
def server(request): # GET 方式用于微信公众平台绑定验证 if request.method == 'GET': signature = request.GET.get('signature', '') timestamp = request.GET.get('timestamp', '') nonce = request.GET.get('nonce', '') echo_str = request.GET.get('echostr', '') # print(WECHAT_TOKEN, signature, timestamp, nonce) try: check_signature(WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: echo_str = '微信订阅号:错误的请求!!!' return HttpResponse(echo_str) else: msg = parse_message(request.body) # print("消息类型:",msg.type) # print("事件:",msg.event) # print("消息:", msg) reply = TextReply(message=msg) if msg.type == 'event': # print(msg.event) if 'subscribe' in msg.event and (msg.event != "unsubscribe"): # print("新用户订阅:%s" % msg.source, dir(msg)) send_email(subject="新用户订阅!", content="新用户订阅") reply.content = "欢迎您来到重症医学质量控制,在后台回复消息,可获得重症医学相关知识!" elif msg.event == 'unsubscribe': # print("用户取消订阅:%s" % msg.source, dir(msg))s reply.content = "下次再来1!" elif msg.type == 'text': reply.content = msg.content # reply = ArticlesReply(message=msg) # reply.add_article({ # 'title':'test', # 'description':'des of test', # 'image':'http://linux.zicp.vip/static/images/logo.png', # 'url':'http://linux.zicp.vip' # }) elif msg.type == 'image': reply.content = "您发了一张图片吗?图片的地址为:%s" % msg.image elif msg.type == 'voice': reply.content = "您发了一条语音吗?" elif msg.type == 'video': reply.content = "您发了一个视频吗?" elif msg.type == 'location': reply.content = "您发了一个地理位置吗?纬度:%s-经度:%s,位置:%s" % ( msg.location_x, msg.location_y, msg.label) elif msg.type == 'shortvideo': reply.content = "您发了一个短视频吗?" elif msg.type == 'link': reply.content = "您发了一个链接吗?链接:%s ,地址:%s" % (msg.description, msg.url) xml = reply.render() return HttpResponse(xml)
def handle_msg(request): if request.method == 'GET': signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') echo_str = request.GET.get('echostr') check_signature(TOKEN, signature, timestamp, nonce) return HttpResponse(echo_str) elif request.method == 'POST': body = request.body msg = parse_message(body) rep = TextReply() rep.source = msg.target rep.target = msg.source if msg.type == 'event': if msg.event == 'click': if msg.key == 'sports_advice': rep.content = recommend_plan(msg.source) elif msg.key == 'view_info': rep.content = get_info(msg.source) elif msg.key == 'add_bong': rep.content = add_bong(msg.source) elif msg.key == 'add_test': rep.content = add_test(msg.source) elif msg.key == 'add_test_new': rep.content = add_test_new(msg.source) elif msg.key == 'show_today': rep.content = get_datatoday(msg.source) elif msg.key == 'change_remind': rep.content = set_remind(msg.source) elif msg.key == 'build_match': article_rep = ArticlesReply() article_rep.source = msg.target article_rep.target = msg.source article_rep.add_article({ 'title': '创建比赛', 'description': '点此链接以创建比赛', 'image': serverIP+'static/img/run02.jpg', 'url': build_match(msg.source) }) repxml = article_rep.render() return HttpResponse(repxml) elif msg.event == 'subscribe': rep.content = create_newuser(msg.source) else: rep.content = '!!!' else: rep.content = '你好' repxml = rep.render() return HttpResponse(repxml)
def token(): if request.method == 'GET': signature = request.args.get('signature') timestamp = request.args.get('timestamp') nonce = request.args.get('nonce') echo_str = request.args.get('echostr') # echo_str是微信用来验证服务器的参数,需原样返回 print(signature, timestamp, nonce, echo_str) try: print('正在验证服务器签名') # 无法验证成功??? # check_signature(token, signature, timestamp, nonce) print('验证签名成功') except InvalidSignatureException as e: print('检查签名出错: '.format(e)) return 'Check Error' return echo_str # POST print('开始处理用户消息') msg = parse_message(request.data) reply_text = handle_msg(msg) reply = TextReply(message=msg) reply.content = reply_text return reply.render()
def handle_msg(request): if request.method == 'GET': signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') echo_str = request.GET.get('echostr') check_signature(TOKEN, signature, timestamp, nonce) return HttpResponse(echo_str) elif request.method == 'POST': body = request.body msg = parse_message(body) rep = TextReply() rep.source = msg.target rep.target = msg.source if msg.type == 'event': if msg.event == 'click': print(msg.key) if msg.key == 'sports_advice': rep.content = recommend_plan(msg.source) elif msg.key == 'view_info': rep.content = get_info(msg.source) elif msg.key == 'add_test': rep.content = add_test(msg.source) elif msg.key == 'show_today': rep.content = get_datatoday(msg.source) elif msg.event == 'subscribe': rep.content = create_newuser(msg.source) else: rep.content = '!!!' else: rep.content = '<a href="http://learn.tsinghua.edu.cn">你好</a>' repxml = rep.render() return HttpResponse(repxml)
def autoreply(request): try: webData = request.body msg = parse_message(webData) msg_type = msg.type logger.info("询问排名") if msg_type == 'text': content = msg.Content from wechatpy.replies import TextReply if content == '排名': logger.info("询问排名") # reply = TextReply(content='text reply', message=msg) # 或者 reply = TextReply(message=msg) reply.content = '查看详细排名' \ ' <a href="https://qiuplus.cn/zqzb/ranktable/">斯诺克排名 </a>' # 转换成 XML xml = reply.render() return xml else: reply = TextReply(content='text reply', message=msg) # 或者 reply = TextReply(message=msg) reply.content = '近期无比赛' # 转换成 XML xml = reply.render() return xml elif msg_type == 'image': from wechatpy.replies import TextReply reply = TextReply(content='图片已收到', message=msg) # 或者 reply = TextReply(message=msg) reply.content = 'text reply' # 转换成 XML xml = reply.render() return xml except Exception as Argment: logger.exception("error") logger.error(Argment) return Argment
def reply_message(self, message, content): """ 回复公众号消息 """ reply = TextReply() reply.target = message.FromUserName reply.source = message.ToUserName reply.content = content xml_str = reply.render() headers = {'CONTENT_TYPE': self.request.META['CONTENT_TYPE']} return Response(xml_str, headers=headers)
def reply_message(self, message, content): """ 回复公众号消息 """ reply = TextReply() reply.target = message.FromUserName reply.source = message.ToUserName reply.content = content xml_str = reply.render() headers = {'CONTENT_TYPE': self.request.META['CONTENT_TYPE']} return Response(xml_str, headers=headers)
def parse_msg(self, msg): print msg.type print msg if msg.type == "event": content = "" if msg._data.get("Event", "") == "subscribe": content = "1、每日标准上班时间 10:00到19:00;" + \ "2、打卡时间10:03之前,之后记为迟到;" + \ "3、每月3次以内(含3次)迟到10:30之内,不做处理," + \ "超出3次,从第四次开始累计罚款20 40 80 160 平方递增," + \ "迟到超过30分钟按照事假2小时处理;" + \ "4、每人每月带薪病事假1天,不可跨月累计," + \ "超出部分病假发放50%工资(1天以上的需要医院假条)" + \ ",事假不发工资;" + \ "5、全勤奖,每月无事假病假,及任何迟到显现可获得全勤奖," + \ "奖品每月更换,平均价值300元;" + \ "6、加班,每日加班超过22:00(需要管理人员在加班单上签字)," + \ "第二天可11:00到岗,周末及节假日加班可累计倒休,抵扣事假,病假。" reply = TextReply(message=msg) reply.content = content elif msg.type == "text": reply = TextReply(message=msg) reply.content = msg._data.get("Content") elif msg.type == "image": reply = ImageReply(message=msg) reply.media_id = msg._data.get("MediaId") elif msg.type == "voice": reply = VoiceReply(message=msg) reply.media_id = msg._data.get("MediaId") pass else: return None re_xml = reply.render() return re_xml
def weixin_handler(): # 从config文件中获取 token = os.getenv('WECHAT_TOKEN', config.WECHAT_TOKEN) encodingAESKey = os.getenv('WECHAT_ENCODING_AES_KEY', config.WECHAT_ENCODING_AES_KEY) appId = os.getenv('WECHAT_APP_ID', config.WECHAT_APP_ID) # 从请求中获取 signature = flask.request.args.get("signature") timestamp = flask.request.args.get("timestamp") nonce = flask.request.args.get("nonce") echostr = flask.request.args.get("echostr") # encrypt_type = flask.request.args.get("encrypt_type") msg_signature = flask.request.args.get("msg_signature") ''' print('signature:', signature) print('timestamp: ', timestamp) print('nonce:', nonce) print('echo_str:', echostr) print('encrypt_type:', encrypt_type) print('msg_signature:', msg_signature) ''' crypto = WeChatCrypto(token, encodingAESKey, appId) try: check_signature(token, signature, timestamp, nonce) # 签名验证 except InvalidSignatureException: flask.abort(403) # 校验token失败,证明这条消息不是微信服务器发送过来的 if flask.request.method == "GET": # 如果时明文模式 直接返回echoster return echostr elif flask.request.method == "POST": # 如果时加密模式 先对传入的数据解密 try: msg = crypto.decrypt_message(flask.request.data, msg_signature, timestamp, nonce) print('Descypted message: \n%s' % msg) # 输出数据内容 except (InvalidSignatureException, InvalidAppIdException): flask.abort(404) msg = parse_message(msg) # 解析xml if msg.type == 'text': res = get_robot_reply(msg.content) reply = TextReply(message=msg) reply.content = '%s' % (res) elif msg.type == "image": # 图片回复 reply = ImageReply(message=msg) reply.media_id = msg.media_id else: reply = TextReply(content="暂时不支持此种类型的回复哦~", message=msg) print('Enscypted message: \n%s' % reply) # 返回加密信息 return crypto.encrypt_message(reply.render(), nonce, timestamp)
def handleMsg(request): if request.method == 'GET': signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') echo_str = request.GET.get('echostr') check_signature(TOKEN, signature, timestamp, nonce) return HttpResponse(echo_str) elif request.method == 'POST': body = request.body msg = parse_message(body) rep = TextReply() rep.source = msg.target rep.target = msg.source print(msg.type) if msg.type == 'event': if msg.event == 'click': if msg.key == 'change_info': rep.content = '请点击下面的链接修改信息\n<a href="http://59.66.139.224/showinfo?openID= '+ msg.source + '">修改信息</a>' else: rep.content = '<a href="http://learn.tsinghua.edu.cn">草泥马</a>' repxml = rep.render() return HttpResponse(repxml)
def responMsg(self, pstr, xml): #signature=pstr["signature"][0] #nonce=pstr["nonce"][0] #timestam=pstr["timestamp"][0] msg = parse_message(xml) reply = TextReply(message=msg) reply.content = '你好啊,扑街!' restr = reply.render() bstr = bytes(restr, encoding='utf-8') returncode = bytes(str(bstr, encoding='utf-8').replace('\n', ''), encoding='utf-8') #self.wfile.write(returncode) print(returncode) return returncode
def test1(request): print('!!!!!!') if request.method == 'GET': signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') echo_str = request.GET.get('echostr') check_signature(TOKEN, signature, timestamp, nonce) print('!!!') return HttpResponse(echo_str) elif request.method == 'POST': body = request.body msg = parse_message(body) print(msg.content) print(msg.source) print(msg.target) rep = TextReply() rep.source = msg.target rep.target = msg.source rep.content = '<a href="http://www.baidu.com">草泥马</a>' repxml = rep.render() return HttpResponse(repxml)
def wechatHome(request): # get signature, timestamp and nonce signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') encrypt_type = request.GET.get('encrypt_type') msg_signature = request.GET.get('msg_signature') try: check_signature(TOKEN, signature, timestamp, nonce) if request.method == 'GET': response = request.GET.get('echostr') return HttpResponse(response, content_type="application/json") # POST request if encrypt_type != None: # encryption mode print("request is encrypt") from wechatpy.crypto import WeChatCrypto crypto = WeChatCrypto(TOKEN, AES_KEY, APPID) try: # now msg is xml msg = crypto.decrypt_message(request.body, msg_signature, timestamp, nonce) except (InvalidSignatureException, InvalidAppIdException): HttpResponseBadRequest("decrypt message error") else: msg = request.body # plaintext mode print("before parse_message") pprint.pprint(msg) msg = wechatpy.parse_message(msg) print("after parse_message") pprint.pprint(msg) if msg.type == 'text': # text message reply = TextReply(message=msg) reply.content = 'text reply' elif msg.type == 'image': reply = ImageReply(message=msg) reply.media_id = msg.media_id elif msg.type == 'voice': reply = VoiceReply(message=msg) reply.media_id = 'voice media id' elif msg.type == 'video': reply = VideoReply(message=msg) reply.media_id = 'video media id' reply.title = 'video title' reply.description = 'video description' elif msg.type == 'music': reply = MusicReply(message=msg) reply.thumb_media_id = 'thumb media id' reply.title = 'music title' reply.description = 'music description' reply.music_url = 'music url' reply.hq_music_url = 'hq music url' elif msg.type == 'news': reply = ArticlesReply(message=msg, articles=[ { 'title': u'标题1', 'description': u'描述1', 'url': u'http://www.qq.com', }, ]) else: reply = create_reply('Sorry, can not handle this for now', msg) return HttpResponse(reply.render(), content_type="application/json") except InvalidSignatureException as e: print("check_signature failed") HttpResponseBadRequest(e)
def weixin(): if request.method == 'GET': _g = lambda k: request.args.get(k) try: print(TOKEN, _g('signature'), _g('timestamp'), _g('nonce')) check_signature(TOKEN, _g('signature'), _g('timestamp'), _g('nonce')) return _g('echostr') except InvalidSignatureException: pass elif request.method == 'POST': msg = parse_message(request.data) if isinstance(msg, ClickEvent): ev = msg if ev.key == WX_BTN_BIND_BX: reply = TextReply() reply.source = ev.target reply.target = ev.source reply.content = '请访问以下链接登陆到BX邮箱\n%s' % ( '%s?%s' % (urljoin(DOMAIN, 'mslogin'), urlencode({'wx': ev.source})) ) return reply.render() elif ev.key == WX_BTN_BEGIN_CHECKIN: reply = TextReply() reply.source = msg.target reply.target = msg.source reply.content = '请访问以下链接选择开始哪个会议\n%s' % ( '%s/check-in-meetings?openid=%s' % (DOMAIN, msg.source) ) return reply.render() else: reply = TextReply() reply.source = msg.target reply.target = msg.source reply.content = '哦' return reply.render() elif isinstance(msg, TextMessage): if msg.content.lower().startswith('e'): reply = TextReply() reply.source = msg.target reply.target = msg.source reply.content = '请访问以下链接选择开始哪个会议\n%s' % ( '%s/check-in-meetings?openid=%s' % (DOMAIN, msg.source) ) return reply.render() else: return '哦' elif isinstance(msg, ScanEvent) or isinstance(msg, SubscribeScanEvent): openid = msg.source meetingid = msg.scene_id meeting = mongo.db.meeting.find_one({'meetingid': meetingid}) checkin_time, ps = emit_checked_in(openid=openid, meeting=meeting) r = check_in(openid=openid, meetingid=meetingid, punish_str=ps, checkin_time=checkin_time) meeting = mongo.db.meeting.find_one({'meetingid': meetingid}) print(meeting) if all_attendees_checked(meeting['attendee']): s = '签到汇总\n%s' ra = [] for u in meeting['attendee']: print(u) full_u = mongo.db.users.find_one({'openid': u['openid']}) ra.append([full_u['outlook']['name'], u['punish_str']]) s %= '\n'.join(map(lambda ss: ': '.join(ss), ra)) tmp = list(map(lambda u: u['openid'], meeting['attendee'])) tmp.append(meeting['organizer']['openid']) if len(tmp) > 1: wx.message.send_mass_text(tmp, s, is_to_all=True) else: wx.message.send_text(tmp[0], s) # return r wx.message.send_text(openid, r) reply = TextReply() reply.source = msg.target reply.target = msg.source reply.content = '请访问以下链接选择查看签到状况\n%s' % ( '%s/check-in-members?meetingid=%s' % (DOMAIN, meetingid) ) return reply.render()
def return_text(self, text): reply = TextReply(message=self.msg) reply.content = text # 转换成 XML xml = reply.render() return xml