def wechat_handler(): msg = request.wechat_msg reply = EmptyReply() if msg.type == 'text': if msg.content == '课表': schedule_year = '2015-2016' schedule_term = '2' schedule_data = school.schedule(schedule_year, schedule_term) if type(schedule_data) == dict and schedule_data.get('error'): reply = TextReply(content=schedule_data['error'], message=msg) else: data = assemble_schedule(schedule_data) reply = create_reply(data, message=msg) elif msg.content == '成绩': score_year = '2015-2016' score_term = '2' score_data = school.score(score_year, score_term) if type(score_data) == dict and score_data.get('error'): reply = TextReply(content=schedule_data['error'], message=msg) else: data = assemble_score(score_year, score_term, score_data) reply = create_reply(data, message=msg) elif msg.content == '绑定': content = '<a >点击绑定</a>' content = '<a href="https://weixin.gxgk.cc/">点击绑定</a>' reply = TextReply(content=content, message=msg) else: reply = TextReply(content=msg.content, message=msg) return reply
def query_score(msg): msg.content = (msg.content.replace('"', "").replace("“", "").replace( "”", "").replace(",", ",")) # 首先处理一些无用数据 如空格 引号 params = msg.content.split(" ") try: int(params[1]) except: return create_reply('输入内容不合法', msg) else: if len(params) == 2: # 查询 res = get_meStudentScore(params[1]) # 保存到firestore t = time.time() t = str(int(t)) doc_ref = db.collection('score_data').document( params[1]).collection(t).document('data') res_comp = zlib.compress(str.encode(str(res))) doc_ref.set({ t: res_comp, }) # 查询成功 if res['success']: return reply_articles([{ 'title': res['student_name'] + '的成绩单', 'url': app.config['HOST_URL'] + f'/score-report/{params[1]}/{t}' }], msg) else: return create_reply('获取失败,稍后再试', msg)
def wechat(): xml = request.stream.read() msg = parse_message(xml) print(msg) if msg.type == 'event': if isinstance(msg, SubscribeEvent): reply = subscribeevent_handle(msg) else: reply = create_reply('暂不支持其它事件', message=msg) elif msg.type == 'text': reply = text_handler(msg, msg.content) elif msg.type == 'image': reply = create_reply('图片好好哟', message=msg) elif msg.type == 'voice': reply = text_handler(msg, msg.recognition) elif msg.type == 'video': reply = create_reply('视频挺不错哟', message=msg) # elif msg.type in ['location','link']: # pass else: reply = create_reply('暂不支持处理link和location', message=msg) # 转换成 XML xml = reply.render() return xml
def reply_event(self): msg = self.orign_msg print('msg:%s' % msg) # print('msg_key:%s' % msg.key) print('msg_scan_result:%s' % msg.scan_result) if msg.key == 'so_code': # TODO: 增加搜索编号的方法 so_num = msg.scan_result print(so_num[:9]) from sales.models import SalesOrder try: so = SalesOrder.objects.get(order=so_num[:9]) print(so) massage = ( { 'title': '%s' % so, 'description': self.get_description(so), 'url': '%s' % self.request.build_absolute_uri(so.get_absolute_url()), # 'image': '%s' % (image.content.url if image else '') }, ) print(massage) # massages.append(massage) except Exception as e: massage = '没有查找到单号:%s' % so_num[:9] content = create_reply(massage, msg) # print(content) else: content = create_reply('该条形码没有信息', msg) return content.render()
def reply_text(self): msg = self.orign_msg text = msg.content content = create_reply('', msg) if text: massages = [] from product.models import Block blocks = Block.objects.filter(name__istartswith=text) if blocks: image = None for block in blocks: for file in block.files.all(): if file.type == 'image': image = file break # print(block) massage = { 'title': '%s' % block, 'description': self.get_description(block), 'url': '%s' % self.request.build_absolute_uri( block.get_absolute_url()), 'image': '%s' % (image.content.url if image else '') } massages.append(massage) else: massages = '没有查找到编号:%s' % text content = create_reply(massages, msg) # print(content) return content.render()
def handle_wx(request): global IMG_MEDIA_ID # 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", "") try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: echo_str = "error" response = HttpResponse(echo_str) return response if request.method == "POST": msg = parse_message(request.body) if msg.type == "text": reply = do_text_reply(msg) elif msg.type == 'image': IMG_MEDIA_ID = msg.media_id reply = create_reply("图片已收到" + msg.media_id, msg) elif msg.type == 'event': if msg.key == "func_detail": content = "------功能详情------\n回复关键字即可 如:\n" \ "[天气:郑州]\n[翻译:你好]\n[猜谜语]\n[音乐:天空之城]\n说句语音试一试O(∩_∩)O~~" reply = create_reply(content, message=msg) elif msg.key == "daily_image": reply = ImageReply(message=msg) reply.media_id = IMG_MEDIA_ID elif msg.key == "daily_music": reply = MusicReply(message=msg) reply.title = "偏偏喜欢你" reply.description = "陈百强" reply.thumb_media_id = IMG_MEDIA_ID reply.music_url = "http://bd.kuwo.cn/yinyue/28409674" reply.hq_music_url = "http://bd.kuwo.cn/yinyue/28409674" elif msg.key == "daily_push": reply = ArticlesReply(message=msg) for data in get_news(): reply.add_article({ 'title': data["title"], 'description': data["source"], 'image': data["imgsrc"], 'url': data["url"] }) else: reply = do_event_reply(msg) elif msg.type == 'voice': result = speech_tran(msg) reply = create_reply(result, msg) else: reply = create_reply('你发送的消息已经收到', msg) response = HttpResponse(reply.render(), content_type="application/html") return response
def test_create_empty_reply(self): from wechatpy.replies import EmptyReply reply = create_reply('') self.assertTrue(isinstance(reply, EmptyReply)) reply = create_reply(None) self.assertTrue(isinstance(reply, EmptyReply)) reply = create_reply(False) self.assertTrue(isinstance(reply, EmptyReply))
def test_create_empty_reply(self): from wechatpy.replies import EmptyReply reply = create_reply("") self.assertTrue(isinstance(reply, EmptyReply)) reply = create_reply(None) self.assertTrue(isinstance(reply, EmptyReply)) reply = create_reply(False) self.assertTrue(isinstance(reply, EmptyReply))
def check(): msg = request.wechat_msg event_type = msg.type print(type(msg)) print(msg.type) reply = TextReply(content='谢谢!', message=msg) if event_type == 'text': reply = create_reply(msg.content, message=msg) elif event_type == 'image': reply = TextReply(content='已收到图片!', message=msg) elif event_type == 'event': event = msg.event if event == 'subscribe': reply = TextReply(content=Config.WELCOME_TEXT, message=msg) elif event == 'click': key = msg.key if key == 'CALL_OWNER_BY_PLATE': reply = TextReply(content='抱歉,该功能目前暂未开放!', message=msg) elif key == 'V1001_GOOD': reply = TextReply(content='感谢您的支持!', message=msg) else: reply = TextReply(content='default', message=msg) else: reply = TextReply(content='谢谢反馈!', message=msg) return reply
def handle_wx(request): # GET方式用于微信公众平台绑定验证 if request.method == 'GET': signature = request.GET.get('signature', '') timestamp = request.GET.get('timestamp', '') nonce = request.GET.get('nonce', '') echostr = request.GET.get('echostr', '') try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: echostr = 'error' response = HttpResponse(echostr, content_type="text/plain") return response else: msg = parse_message(request.body) print(msg) # 判断文本消息类型,文本消息处理 if msg.type == 'text': reply = do_reply(msg) elif msg.type == 'voice': voice_trans() reply = create_reply('还没识别出来,稍等...', msg) elif msg.type == 'event': reply = do_event(msg) response = HttpResponse(reply.render(), content_type='application/html') return response
def text_handler(msg, Content): if not Content: reply = create_reply('啥都没有输入啊!', message=msg) return reply if Content.startswith('http'): if 'www.kuaishou.com' in Content: playurl, title, image = get_info_ks(Content) elif 'kg.qq.com' in Content: playurl, title, image = get_info_kg(Content) else: playurl = '' title = u'目前暂不提供非快手及全民K歌来源外的播放地址解析!' image = 'http://qq.yh31.com/tp/zjbq/201612311842344128.gif' reply = ArticlesReply(message=msg, articles=[ { 'title': title, 'description': title, 'url': playurl, 'image': image, }, ]) elif u'违章' in Content: reply = weizhang(msg) elif u'限号' in Content or u'限行' in Content: reply = xianhao(msg) else: reply = tuling_Ai(msg, Content) #reply = create_reply('不是网址', message=msg) return reply
def command_not_found(message): """ 非关键词回复 """ content = app.config['COMMAND_NOT_FOUND_TEXT'] + app.config['HELP_TEXT'] return create_reply(content, message)
def wechat_handler(): msg = request.wechat_msg if msg.type == 'text': reply = create_reply(msg.content, message=msg) else: reply = TextReply(content='hello', message=msg) return reply
def test_create_reply_with_message(self): from wechatpy.messages import TextMessage msg = TextMessage({"FromUserName": "******", "ToUserName": "******"}) reply = create_reply("test", msg, render=False) self.assertEqual("user1", reply.target) self.assertEqual("user2", reply.source) reply.render()
def keywordsReply(self, msg, content=None, media_id=None): ret = self.keywordsRules(msg) print("ret:", ret) if ret == -1: content = "新年歌词活动:\n昵称长度必须在1~10个字符之间。\n请重新输入\"新年歌词@昵称\"!" reply = create_reply(content, message=msg) xml = reply.render() return xml elif ret == -2: content = "新年歌词活动:\n昵称含有敏感词,请使用一个合法昵称。\n请重新输入\"新年歌词@昵称\"!" reply = create_reply(content, message=msg) xml = reply.render() return xml elif ret == -3: content = "新年歌词活动:\n昵称中不能含有@。\n请重新输入\"新年歌词@昵称\"!" reply = create_reply(content, message=msg) xml = reply.render() return xml
def test_create_reply_with_message(self): from wechatpy.messages import TextMessage msg = TextMessage({ 'FromUserName': '******', 'ToUserName': '******', }) reply = create_reply('test', msg, render=False) self.assertEqual('user1', reply.target) self.assertEqual('user2', reply.source)
def test_create_reply_with_message(self): from wechatpy.messages import TextMessage msg = TextMessage({ "FromUserName": "******", "ToUserName": "******", }) reply = create_reply("test", msg, render=False) self.assertEqual("user1", reply.target) self.assertEqual("user2", reply.source) reply.render()
def tuling_Ai(msg, text): url = 'http://openapi.tuling123.com/openapi/api/v2' key = 'e4be290b52a94f6ab2667cae5eca7e71' input_data = {} input_data['perception'] = {} input_data['userInfo'] = {"apiKey": key, 'userId': 1} input_data['perception']['inputText'] = {"text": text} input_data['perception']['selfInfo'] = '' r = requests.post(url, data=str(json.dumps(input_data))) data = json.loads(r.text) code = data.get('intent').get('code') reply = create_reply(u'出错啦,请重试', message=msg) if code > 10000: result = data.get('results') for res in result: resultType = res.get('resultType') if resultType == 'text': values = res.get('values').get('text') reply = create_reply(values, message=msg) return reply
def subscribeReply(self, msg, content=None, media_id=None): if content == None and media_id == None: raise Exception("no info be send!") elif content != None and media_id != None: raise Exception("content and media_id args only one != None") elif content != None: reply = create_reply(content, message=msg) xml = reply.render() return xml else: reply = ImageReply(message=msg) reply.media_id = media_id xml = reply.render() return xml
def qrcode_process(content, TOKEN, signature, timestamp, nonce, encrypt_type, msg_signature): try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': echo_str = request.args.get('echostr', '') return echo_str # POST request if encrypt_type == 'raw': # plaintext mode msg = parse_message(request.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(TOKEN, Config.wechat_mp_encodingaes_key, Config.wechat_appid_mp) try: msg = crypto.decrypt_message(request.data, msg_signature, timestamp, nonce) except (InvalidSignatureException, InvalidAppIdException): return "" else: msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply(content, msg) return crypto.encrypt_message(reply.render(), nonce, timestamp)
def wechat_response(message): ''' 微信消息处理函数 :message 从微信服务器传来的数据 ''' response = '未知错误' try: get_resp_handler = msg_type_resp[message.type] response = get_resp_handler(message) except KeyError as e: content = app.config['CANT_HANDLE_THIS_MESSAGE_TYPE'] response = create_reply(content, message) app.logger.warning(e) return response
def wechat(): if request.method=='GET': token='****' data=request.args signature=data.get('signature','') timestamp=data.get('timestamp','') nonce=data.get('nonce','') echostr=data.get('echostr','') try: check_signature(token,signature,timestamp,nonce) except InvalidSignatureException: return "" return echostr else: try: msg=parse_message(request.data) except InvalidSignatureException: return "" if msg.type=='text': retmsg=[{"title": "检索结果","image": "http://*.*.*.*:*/*.jpg", "url": u"http://*.*.*.*:*/*.php?title="+msg.content},] reply = ArticlesReply(message=msg, articles=retmsg) return reply.render() if msg.type=='image': image_content='图片.jpg' reply=create_reply(image_content,msg) return reply.render() if msg.type=='voice': voice_content='喂喂喂?' reply=create_reply(voice_content,msg) return reply.render() if msg.type=='event': welcome_content='欢迎关注我的微信公众号~~ 直接输入关键字可检索有关Github项目' reply=create_reply(welcome_content,msg) return reply.render() else : return ""
def post(self, request): msg = parse_message(request.body) print(msg) if msg.type == 'text': reply = create_reply('这是条文字消息', message=msg) elif msg.type == 'image': reply = create_reply('这是条图片消息', message=msg) elif msg.type == 'voice': reply = create_reply('这是条语音消息', message=msg) elif msg.type == 'event': openid = request.GET.get('openid', None) print(openid) if msg.event == 'subscribe': reply = create_reply('感谢你的关注', message=msg) inf = client.user.get('o-Njg0grnFp0LNHidvhKNek6_H88') # print(user["nickname"]) Users.objects.create(nickname=inf["nickname"], headimgurl=inf["headimgurl"], sex=inf["sex"], country=inf["country"], province=inf["province"], city=inf["city"], subscribe_time=inf["subscribe_time"], openid=inf["openid"]) elif msg.event == 'unsubscribe': Users.objects.get(openid=openid).delete() elif msg.event == 'click': reply = ImageReply(message=msg) media_id = '9kT9-alo_ph3g2I45zACW5X59Dqxbf45k-0Z89XXOSta_H_gqfnAhJvG557pqOEM' reply.media_id = media_id Menu_click_count.picture_click_count += 1 elif msg.event == 'view': Menu_click_count.url_click_count += 1 else: reply = create_reply('这是条其他类型消息', message=msg) return HttpResponse(reply.render(), content_type=" ")
def reply_test(url, request): self.assertEqual(url.scheme, scheme) self.assertEqual(url.netloc, netloc) self.assertEqual(url.path, path) query = dict(parse_qsl(url.query)) self.assertEqual(query["timestamp"], timestamp) self.assertEqual(query["nonce"], nonce) self.assertEqual(query["signature"], signature) check_signature(self.app.token, query["signature"], timestamp, nonce) msg = parse_message(request.body) self.assertIsInstance(msg, messages.TextMessage) self.assertEqual(msg.source, sender) self.assertEqual(msg.content, content) reply = replies.create_reply(reply_text, msg) return response(content=reply.render())
async def reply_handler( msg_signature: str, timestamp: str, nonce: str, request: Request, ): xml_body = await request.body() decrypted = crypto.decrypt_message(xml_body.decode(), msg_signature, timestamp, nonce) msg = parse_message(decrypted) dispatcher = MsgDispatcher(BaseReplyLoader()) answer = await dispatcher.dispatch(msg) reply = create_reply(answer, message=msg, render=True) encrypted = crypto.encrypt_message(reply, nonce) return Response(encrypted, media_type='application/xml')
def message_reply(): if request.method == 'POST': try: webData = request.data app.logger.info("Handle Post webdata is " + str(webData)) # 后台日志 recMsg = parse_message(webData) if recMsg.type == 'text': reply = create_reply('text reply', message=recMsg) # 转换成 XML xml = reply.render() return xml elif recMsg.type == 'event': handle_event(recMsg) return 'success' else: app.logger.warning("Unsupported message type. Do nothing.") return "success" except Exception as e: app.logger.error(e)
def _(msg): openid = msg.source client = wechat_client() user = client.user.get(openid) logging.debug(user) # 有人关注公众号后通知我:oz1ZK1KdUY-QTPJirfaI_lZhAQic res = client.message.send_text(_MY_OPENID, '%s 关注公众号' % user['nickname']) logging.debug(res) headimgurl = user['headimgurl'] size_index = headimgurl.rfind('/') size_index = len(headimgurl) if size_index == -1 else size_index headimgurl = headimgurl[0:size_index] reply_msg = [{ 'title': '欢迎%s' % user['nickname'], 'description': '', 'image': headimgurl + '/0', 'url': headimgurl + '/0' }] reply = create_reply(reply_msg, message=msg) return reply.render()
def test_create_reply_with_articles(self): articles = [ { 'title': 'test 1', 'description': 'test 1', 'image': 'http://www.qq.com/1.png', 'url': 'http://www.qq.com/1' }, { 'title': 'test 2', 'description': 'test 2', 'image': 'http://www.qq.com/2.png', 'url': 'http://www.qq.com/2' }, { 'title': 'test 3', 'description': 'test 3', 'image': 'http://www.qq.com/3.png', 'url': 'http://www.qq.com/3' }, ] reply = create_reply(articles, render=False) self.assertEqual('news', reply.type)
def test_create_reply_with_articles(self): articles = [ { "title": "test 1", "description": "test 1", "image": "http://www.qq.com/1.png", "url": "http://www.qq.com/1", }, { "title": "test 2", "description": "test 2", "image": "http://www.qq.com/2.png", "url": "http://www.qq.com/2", }, { "title": "test 3", "description": "test 3", "image": "http://www.qq.com/3.png", "url": "http://www.qq.com/3", }, ] reply = create_reply(articles, render=False) self.assertEqual("news", reply.type) reply.render()
def test_create_reply_with_reply(self): _reply = TextReply(content='test') reply = create_reply(_reply, render=False) self.assertEqual(_reply, reply)
def subscribeevent_handle(msg): reply = create_reply('欢迎关注,直接回复全民K歌或快手的网址,用来获取真实播放地址\n回复"违章"或"限号"可查询相关信息!', message=msg) return reply
def test_create_reply_with_text_not_render(self): text = "test" reply = create_reply(text, render=False) self.assertEqual("text", reply.type) self.assertEqual(text, reply.content) reply.render()
def test_create_reply_with_text_not_render(self): text = 'test' reply = create_reply(text, render=False) self.assertEqual('text', reply.type) self.assertEquals(text, reply.content)
def reply_articles(articles, msg): return create_reply(articles, msg)
def test_create_reply_with_text_render(self): text = 'test' reply = create_reply(text) self.assertTrue(isinstance(reply, six.text_type))
def _(msg): reply = create_reply("welcome", message=msg) return reply.render()
def test_create_reply_should_return_none(self): reply = create_reply(None) self.assertTrue(reply is None)