def handle_reply(content, msg): ''' 根据用户选取的回复信息的类型,对相应信息进行处理成xml ''' env = request.env() if content._name == 'wx.text': reply_content = content.text_content reply = TextReply(message=msg, content=reply_content) elif content._name == 'wx.image': reply_content = content.media_id reply = ImageReply(media_id=reply_content, message=msg) elif content._name == 'wx.imagetext': Articles = [{ 'title': content.name, 'description': content.content, 'picurl': content.image_id.url, 'url': content.content_source_url }] reply = ArticlesReply(message=msg, articles=Articles) elif content._name == 'wx.many.imagetext': Articles = [] for content in content.many_image_text: Articles.append({ 'title': content.name, 'description': content.content, 'picurl': content.image_id.url, 'url': content.content_source_url }) reply = ArticlesReply(message=msg, articles=Articles) _logger.info('消息处理reply %s', reply) # debug return reply.render()
def do_reply(msg): if msg.content == '天气': # msg.content 就是发送过来消息的内容 reply = create_reply('今天是晴天', msg) elif msg.content == '王者荣耀': reply = create_reply('万年青铜垃圾游戏,不玩了', msg) elif msg.content == '历史': result = hisutils.request1() reply = create_reply(result, msg) elif msg.content == '星座运势': result = hisutils.request2() res = result['name'] + ':' + '1.时间:' + result[ 'datetime'] + '2.幸运色:' + result['color'] + '3.注意事项:' + result[ 'summary'] reply = create_reply(res, msg) elif msg.content == '倔强': reply = ArticlesReply(message=msg) reply.add_article({ "title": "倔强", "description": "倔强", 'image': '', "url": "https://mp.weixin.qq.com/s?__biz=MzU1OTc0NTQ1OQ==&tempkey=OTgwX1VsOXpaamFiaTJnRGtuMFZZRTVRNE5MQ0NMbTg1TmNrU2tRLWRvZWFxQ2ZGd0djSmdtazJoNC1NZXBMZW5Ob2ptOGNZb3d4VUdYNklFaWkwSHc5NWJoaEI2dl81SjZHZDhYdUwtbEVBRWZSN01acC05OVhST3hXem9wN1RFd0VCQWdxaUpjck12SGg3R0RzdWFYZC1ZeU1RYWZnOFEtcHlNRGpZN3d%2Bfg%3D%3D&chksm=7c13d1f94b6458ef3458ddd1e6bd5e31ae8bc410a21751e6ae5284cfbb6f9f0144d3613bac07#rd" }) else: aip = apiutils.AiPlat('2109307989', '867FI1Wu8YsT3Gd8') data = aip.get_nlp_text_trans(msg.content, 0) reply = create_reply(data['data']['trans_text'], msg) return reply
def wechat(club_name): logger.debug(club_name) query = request.args logger.debug(query) signature = query.get("signature", "") timestamp = query.get("timestamp", "") nonce = query.get("nonce", "") logger.debug(request.args) try: check_signature(TOKEN, signature, timestamp, nonce) except Exception as e: logger.debug("invalid request!") abort(403) if request.method == "GET": return make_response(request.args.get("echostr", "")) else: logger.debug("start make response") encrypt_type = request.args.get("encrypt_type", "raw") xml = request.data msg = None if encrypt_type == "raw": # plain mode logger.debug("plain mode") msg = parse_message(xml) else: try: # encrypt mode crypto = WeChatCrypto(TOKEN, AES_KEY, APP_ID) msg = parse_message( crypto.decrypt_message(xml, signature, timestamp, nonce)) except Exception as e: abort(403) reply_xml = None if msg.type == "text": key_words = [item.strip() for item in str(msg.content).split(" ")] articles = app_controller.search_club_service_article( club_name, key_words) for article in articles: article["image"] = "{}{}".format(get_host(), article["image"]) article["url"] = "{}{}".format(get_host(), article["url"]) reply = ArticlesReply(articles=articles, message=msg) reply_xml = reply.render() else: reply = TextReply(content="Not supported!", message=msg) reply_xml = reply.render() logger.debug("xml:" + reply_xml) if encrypt_type == "raw": return reply_xml else: return crypto.encrypt_message(reply_xml, nonce, timestamp)
def _deal_cl(msg, content): if not content: page = 1 else: try: page = int(content) except: return TextReply(content=u'不要乱搞~~~', message=msg) if page > 10000: return TextReply(content=u'你太贪心了,不给了......', message=msg) posts, count = dao.select(T66Y_COLL, {}, limit=5, skip=(page - 1) * 5, sort=('update', -1)) articles = [{ 'title': u'[%s · %sP] %s' % (item['category'], item['img_count'], item['title']), 'url': 'http://zhihu.photo/wechat/cltt/%s' % item['_id'], 'image': 'http://zhihu.photo/api/cl/download/%s' % choice(item['images'])['hash'] } for item in posts] return ArticlesReply(message=msg, articles=articles)
def xianhao(msg): with open('xianhao.txt', 'r') as rf: data = eval( rf.readlines()[0].strip()) #{'weeks':'18','image_url':'1231'} weeks = int(data.get('weeks')) weeks_now = int(time.strftime("%W")) if weeks_now > weeks: url = 'http://www.bjjtgl.gov.cn/zhuanti/10weihao/' image = get_info_weizhang(url) if image: image = image[0] data['weeks'] = weeks_now data['image'] = image with open('xianhao.txt', 'w') as wf: wf.write(json.dumps(data)) else: image = data.get('image') else: image = data.get('image') reply = ArticlesReply( message=msg, articles=[ { 'title': u'北京限号', 'description': u'北京限号信息', 'url': 'http://www.bjjtgl.gov.cn/zhuanti/10weihao/index.html', 'image': image, }, ]) return reply
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 test_multi_article_reply(self): from wechatpy.replies import ArticlesReply article = {"title": "test", "url": "http://www.qq.com"} r1 = ArticlesReply() r1.add_article(article) r2 = ArticlesReply() self.assertTrue(r1.render() != r2.render())
def test_multi_article_reply(self): from wechatpy.replies import ArticlesReply article = {'title': 'test', 'url': 'http://www.qq.com'} r1 = ArticlesReply() r1.add_article(article) r2 = ArticlesReply() self.assertTrue(r1.render() != r2.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_handler(recv_msg, *args, **kwargs): reply = ArticlesReply() reply.source = recv_msg.to_user_name reply.target = recv_msg.from_user_name reply.add_article({ 'title': '测试图文消息', 'description': '图文消息描述', 'image': 'http://pic1.win4000.com/pic/b/6e/5aee949474.jpg', 'url': 'http://www.baidu.com' }) reply.add_article({ 'title': '测试图文消息', 'description': '图文消息描述', 'image': 'http://pic1.win4000.com/pic/b/6e/5aee949474.jpg', 'url': 'http://www.baidu.com' }) xml = reply.render() return HttpResponse(xml)
def getWeatherMsg(msg): reply = ArticlesReply(message=msg) result = getcityweather() temperature = result['result']['today']['temperature'] weather = result['result']['today']['weather'] wind = result['result']['today']['wind'] reply.add_article({ 'title': temperature, }) reply.add_article({ 'title': weather, }) reply.add_article({ 'title': wind, }) return reply
def send_message(request): if request.method == 'GET': # 验证URL signature = request.GET.get('signature', '') timestamp = request.GET.get('timestamp', '') nonce = request.GET.get('nonce', '') echo_str = request.GET.get('echostr', '') try: check_signature(AUTH_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: echo_str = 'error' response = HttpResponse(echo_str, content_type='text/plain') return response elif request.method == 'POST': # 接收来微信服务器信息 msg = parse_message(request.body) if msg.type == 'text': reply = create_reply("<a href='https://articuly.com'>清心涟漪博客</a>", msg) elif msg.type == 'event': reply = ArticlesReply(message=msg) reply.add_article({ 'title': '清心涟漪博客', 'description': '因缘相见,整合图谱,心理占星,Python全栈', 'image': 'https://articuly.com/wp-content/uploads/2014/07/articuly.jpg', 'url': 'https://articuly.com' }) elif msg.type == 'image': reply = create_reply('你刚才发给我的是一张图片', msg) elif msg.type == 'voice': reply = create_reply('你刚才发给我的是语音', msg) else: reply = create_reply('这是其它类型消息', msg) response = HttpResponse(reply.render(), content_type='application/xml') return response else: print('-' * 50)
def _select_nobody(msg, page): data = dao.get_qbcr_imgs(page) if not data: return TextReply(content=u'你太贪心了,我没这么多图......', message=msg) return ArticlesReply(message=msg, articles=[{ 'title': u'[多图 · 10P] %s' % data[0][2], 'url': 'http://zhihu.photo/wechat/nobody/%s' % page, 'image': data[0][1] }])
def weizhang(msg): reply = ArticlesReply( message=msg, articles=[ { 'title': u'全国违章查询', 'description': u'查询全国违章,方便', 'url': 'http://m.cheshouye.com/api/weizhang/?dp=14&dc=189', 'image': 'http://img02.tooopen.com/images/20160614/tooopen_sy_165048289591.jpg', }, ]) return reply
def wechat_handler(): msg = request.wechat_msg _uuid = insert_message(msg) if msg.type == 'event' and msg.event == 'subscribe': reply = TextReply(content='感谢关注!', message=msg) elif msg.type == 'text': reply_type, reply_txt_or_article = rulebasedrobot(msg) if reply_type == 0: reply = TextReply(content=reply_txt_or_article, message=msg) elif reply_type == 1: reply = ArticlesReply(message=msg) reply.add_article(reply_txt_or_article) elif msg.type == 'image': reply = TextReply(content='别这样,你的图片会被我保存的。', message=msg) else: reply = TextReply(content='仅支持文本、图片消息。', message=msg) insert_response(reply, _uuid) return reply
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 subscribe(msg): reply = ArticlesReply(message=msg) reply.add_article({ 'title': '米客鹿 - 欢迎您', 'description': '米客鹿 - 欢迎您', 'image': 'https://mmbiz.qlogo.cn/mmbiz_png/yPLjxp6uDp30bajsBE2nR9nV5WUaI80NJ6s315CHBP0s3KvruP5pT2TesSNNTpKUiawRqdjNJpvicW1mJtS3RTnw/0?wx_fmt=png', 'url': 'http://wxclientdev.fogcloud.io/welcome/' }) reply.add_article({ 'title': '配置玩具wifi', 'description': '配置玩具wifi', 'image': 'https://mmbiz.qlogo.cn/mmbiz_png/yPLjxp6uDp30bajsBE2nR9nV5WUaI80NMucDbFsLF0FceUIRISpWrsnibRtfPEyEdZdEoibEP5J1gVwTQbk4vI5A/0?wx_fmt=png', 'url': 'http://wxclientdev.fogcloud.io/wifi/' }) reply.add_article({ 'title': '如何使用', 'description': '如何使用', 'image': 'https://mmbiz.qlogo.cn/mmbiz_png/yPLjxp6uDp30bajsBE2nR9nV5WUaI80NBLkJgCOa3lq4udulLw1F8fQhKQic2PvIlMtqQ8E8hRiaDw6MAvvrOJDw/0?wx_fmt=png', 'url': 'http://wxclientdev.fogcloud.io/instructions/' }) return reply
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 wechat_back(event): event = re.sub(r'\<xml\>', '<xml>\n', event) xml = event msg = parse_message(xml) if msg.type == 'text': question = turning(msg.content) s = {} ss = {} lib = {} lib_qt = {} lib_qm = {} s_max = '' for i in range(0, len(ques)): lib_qt[ques[i]] = int(token[i]) for i in range(0, len(ques)): lib_qm[ques[i]] = media_id[i] for i in range(0, len(ques)): lib[ques[i]] = answ[i] text = [x.strip() for x in ques if len(x) > 2] if question in lib: s_max = question answer = lib[question] else: for i in text: similarity = sentence_similarity(i, question, tfidf_dict) s[i] = similarity s_max = max(s, key=s.get) #print(s_max) for i in range(0, 10): if jaccard(s_max, question) < 0.20: del s[s_max] s_max = max(s, key=s.get) else: try: ss[s_max] = s[s_max] + jaccard(s_max, question) except: ss[s_max] = 1.5 #print(ss) try: s_max = max(ss, key=ss.get) except: s_max = ' ' #print(s_max) '''try: print(lib_qt[s_max]) except: lib_qt[s_max] = 9 print(ss)''' if lib_qt[s_max] == 1: answer = lib_qm[s_max] reply = ImageReply(content='AAAAAAAAA', media_id=answer, message=msg) xml = reply.render() elif lib_qt[s_max] == 2: answer = lib[s_max] img = lib_qm[s_max].split(' ')[0] url = lib_qm[s_max].split(' ')[1] reply = ArticlesReply(message=msg) reply.add_article({ 'title': question, 'description': answer, 'image': img, 'url': url }) xml = reply.render() else: try: answer = lib[s_max] except: answer = '暂无此问题' answer = answer.encode('utf-8') #print(answer) reply = TextReply(content=answer, message=msg) xml = reply.render() print('问题:' + question) print('匹配结果:' + s_max) print('答案:', answer) resp = apiReply(reply, txt=True, content_type="application/xml") #resp = json.dumps(reply,encoding = 'utf-8') return resp
def connect(): if request.method == 'GET': args = request.args resp_body = "" for k, v in args.items(): print(f"{k}: {v}") print(args) try: check_signature_str = check_signature(token='001001001001', signature=args['signature'], timestamp=args['timestamp'], nonce=args['nonce']) print(check_signature_str) resp_body = args["echostr"] except InvalidSignatureException: print("Error with check_signature") resp_body = "Error with check_signature" pass return resp_body elif request.method == 'POST': xml = request.stream.read() msg = parse_message(xml) print(msg) if msg.type == 'text': reply = TextReply(content=msg.content, message=msg) elif msg.type == 'image': reply = ImageReply(media_id=msg.media_id, message=msg) ocr_text = '' try: cred = credential.Credential( os.environ.get("TENCENTCLOUD_SECRET_ID"), os.environ.get("TENCENTCLOUD_SECRET_KEY")) httpProfile = HttpProfile() httpProfile.endpoint = "ocr.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = ocr_client.OcrClient(cred, "ap-hongkong", clientProfile) ocrreq = models.GeneralFastOCRRequest() ocrreq.ImageUrl = msg.image #发送过来的消息的url ocrres = client.GeneralFastOCR(ocrreq) print(ocrres.to_json_string()) for x in json.loads(ocrres.to_json_string())["TextDetections"]: print(x["DetectedText"]) ocr_text = ocr_text + x["DetectedText"] except TencentCloudSDKException as err: print(err) reply = ArticlesReply(message=msg) # simply use dict as article reply.add_article({ 'title': 'OCR Test', 'description': ocr_text, 'image': msg.image #'url': 'url' }) else: reply = TextReply(content='Hello,大哥,目前只支持文本和图片', message=msg) xml = reply.render() print(reply) response = make_response(xml) response.content_type = 'application/xml' return response
def send_article(toUser, fromUser): reply = ArticlesReply() reply.source = fromUser reply.target = toUser reply.add_article({"title":"圣光会制裁你!", "description":"The Light Shall Bring Victory!", "image":LIGHT, "url":"http://baike.baidu.com/link?url=QBxKSNA79HbeeaSwsbkcPHdhhVI5ZM9HePZrUpQCwtwKx9xShsZ1vOCd35UuNYP0SxaedrA2UIaPLMvFVW5wD_"}) return HttpResponse(reply.render())
def my_main_api(msg): kuan = Kuan() if msg.key == 'kuan_update': reply = kuan.get_update(msg) elif msg.key == 'kuan_app_push': reply = kuan.get_app_push(msg) elif msg.key == 'kuan_game_push': reply = kuan.get_game_push(msg) elif msg.key == 'day_bing': bing = DayBing() reply = bing.get_image_url(msg) elif msg.key == 'day_music': # http://music.163.com/song/522510615/?userid=311948152 reply = MusicReply( message=msg, title='千禧', thumb_media_id= 'EpZ4EJF9njZOorkr2TnVAquSxXF2eoQW2Bk6DdKS07kycz-hwYnRSLAmfubPNvzh', description='徐秉龙', music_url='http://www.ytmp3.cn/down/54100.mp3', hq_music_url='http://www.ytmp3.cn/down/54100.mp3') elif msg.key == 'm_review': ren = RenRen() news = ren.get_info() reply = ArticlesReply(message=msg) print(news) for new in news: reply.add_article({ 'title': new['title'], 'description': new['description'], 'image': new['image'], 'url': new['url'] }) elif msg.key == 'recom': ren = RenRen() ren.url = 'http://www.zimuzu.tv/article?type=recom' news = ren.get_info() reply = ArticlesReply(message=msg) # print(news) articles = [{ 'thumb_media_id': 'Pp8iDnCrxFlb8CUfmmpGOYuoj3EisK_t4xtHvBA_blg', 'title': '哈哈哈哈', 'content': '红红火火恍恍惚惚红火火恍恍惚惚', 'author': '张宇', 'content_source_url': 'http://mp.weixin.qq.com/s?__biz=MzUxNzk3MTQ5NA==&mid=100000003&idx=1&sn=85ac89b7f597ebae2ea6373d3a2e922b&chksm=79914a4a4ee6c35c3c9c4147ea169692df3a84feeb992d442848f2c67ccd5de1e90e905d7af7#rd', 'digest': '你好', 'show_cover_pic': '1', }] # 上传永久素材 # client = WeChatClient('wx892238d68ae6f860', 'dcb0a16bc13e183f3e20aa0fa30b23e6') # material = WeChatMaterial(client) # 图片 # obj_file = open('test.jpg','rb') # resp = material.add('thumb',obj_file,'缩略图.test') # 图文 # resp = material.add_articles(articles) # 获取素材 # resp = material.get('Pp8iDnCrxFlb8CUfmmpGOaF0tYuqXkQKNn0qufc5HsA') # print(resp) for new in news: reply.add_article({ 'title': new['title'], 'description': new['description'], 'image': new['image'], 'url': 'http://mp.weixin.qq.com/s?__biz=MzUxNzk3MTQ5NA==&mid=100000003&idx=1&sn=85ac89b7f597ebae2ea6373d3a2e922b&chksm=79914a4a4ee6c35c3c9c4147ea169692df3a84feeb992d442848f2c67ccd5de1e90e905d7af7#rd' }) else: reply = '' return reply
def post(self, request): xml = request.body msg = parse_message(xml) if msg.type == 'text': # 获取文本内容 try: content = msg.content # print(res) # print(json.dump(res)) reply = TextReply(content=content, message=msg) r_xml = reply.render() # 获取唯一标记用户的openid,下文介绍获取用户信息会用到 openid = msg.source # print(openid) return HttpResponse(r_xml) except Exception as e: # 自行处理 return HttpResponse('success') # return HttpResponse('') elif msg.type == 'image': print(msg.image, msg.media_id) reply = ArticlesReply(message=msg) reply.add_article({ 'title': 'Welcome tom my channel!', 'description': 'Finally, we meet you here,\nYou must know you are very important for us!', 'image': msg.image, 'url': 'https://baidu.com' }) r_xml = reply.render() return HttpResponse(r_xml) elif msg.type == 'voice': print(msg.format, msg.recognition) reply = VoiceReply(media_id=msg.media_id, message=msg) return HttpResponse(reply.render()) elif msg.type == 'video': print(msg) print(msg.media_id, msg.thumb_media_id) reply = VideoReply(media_id=msg.media_id, title='Test video', description='Description', message=msg) return HttpResponse(reply.render()) elif msg.type == 'location': print(msg.location_x, msg.location_y, msg.scale, msg.label, msg.location) return HttpResponse('Success') elif msg.type == 'event': # print(msg.type) if msg.event == 'subscribe': try: reply = TextReply(content='Welcome to my channel', message=msg) r_xml = reply.render() return HttpResponse(r_xml) except: return HttpResponse('Success') elif msg.event == 'unsubscribe': try: reply = TextReply(content='See you again!', message=msg) r_xml = reply.render() return HttpResponse(r_xml) except: return HttpResponse('Success') elif msg.event == 'subscribe_scan': try: print(msg.scene_id, msg.ticket) reply = TextReply(content='See you again!', message=msg) r_xml = reply.render() return HttpResponse(r_xml) except: return HttpResponse('Success') elif msg.event == 'scan': try: print(msg.scene_id, msg.ticket) reply = TextReply(content='See you again!', message=msg) r_xml = reply.render() return HttpResponse(r_xml) except: return HttpResponse('Success') elif msg.event == 'location': try: print(msg.latitude, msg.longitude, msg.precision) reply = TextReply(content='See you again!', message=msg) r_xml = reply.render() return HttpResponse(r_xml) except: return HttpResponse('Success') elif msg.event == 'click': try: print(msg.key) reply = TextReply(content=msg.key, message=msg) r_xml = reply.render() return HttpResponse(r_xml) except: return HttpResponse('Success') elif msg.event == 'view': try: print(f'{msg.url}\n=========') reply = TextReply(content=msg.url, message=msg) r_xml = reply.render() return HttpResponse(r_xml) except: return HttpResponse('Success')
def wechat(request): """ 此地址为响应微信发送的Token验证,验证服务器配置是否正确 :param request: :return: """ signature = request.GET.get('signature', 'c58469c4151fac046efe180b277c51b1e5b563d3') timestamp = request.GET.get('timestamp', '1451138472') nonce = request.GET.get('nonce', '1432579014') echo_str = request.GET.get('echostr', '2691756735856574460') encrypt_type = request.args.get('encrypt_type', '') msg_signature = request.args.get('msg_signature', '') print('signature:', signature) print('timestamp: ', timestamp) print('nonce:', nonce) print('echo_str:', echo_str) print('encrypt_type:', encrypt_type) print('msg_signature:', msg_signature) try: check_signature(settings.WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: return HttpResponseForbidden() if request.method == 'GET': return echo_str else: print('Raw message: \n%s' % request.data) crypto = WeChatCrypto(settings.WECHAT_TOKEN, settings.EncodingAESKey, settings.WECHAT_APPID) try: msg = crypto.decrypt_message( request.data, msg_signature, timestamp, nonce ) print('Descypted message: \n%s' % msg) except (InvalidSignatureException, InvalidAppIdException): return HttpResponseForbidden() msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg) elif msg.type == 'image': reply = ArticlesReply(message=msg) # simply use dict as article reply.add_article({ 'title': 'test', 'description': 'test', 'image': 'image url', 'url': 'url' }) # or you can use ObjectDict article = ObjectDict() article.title = 'test' article.description = 'test' article.image = 'image url' article.url = 'url' reply.add_article(article) # reply = create_reply([article], msg) else: reply = create_reply('Sorry, can not handle this for now', msg) msg= crypto.encrypt_message( reply.render(), nonce, timestamp) print(msg) return HttpResponse(msg)
def Reply_Article(msg, reply_dic): reply = ArticlesReply(message=msg) # simply use dict as article reply.add_article(reply_dic) return reply.render()
def do_event(msg): if msg.event == 'subscribe': reply = create_reply('欢迎您关注我的公众号:请输入天气查看当前天气!', msg) elif msg.event == 'unsubscribe': pass elif msg.event == "click": if msg.key == "V1001_TODAY_MUSIC": # 回复音乐信息 reply = MusicReply(message=msg) reply.title = '音乐' reply.description = '今日音乐 ' thumb = MaterialModel.objects.get(id=5) reply.thumb_media_id = thumb.media_id reply.music_url = "http://www.xiami.com/song/1792541433" reply.hq_music_url = "http://www.xiami.com/song/1792541433" elif msg.key == "V1001_TODAY_SINGER": reply = ArticlesReply(message=msg) reply.add_article({ "title": "阿信", "description": "陈信宏(Ashin),昵称阿信,1975年12月6日生于台北市北投区。中国台湾男歌手、词曲创作者,中国台湾摇滚乐团五月天的主唱,创意潮牌STAYREAL总裁。", "image": "https://gss1.bdstatic.com/9vo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike80%2C5%2C5%2C80%2C26/sign=f8e67f4769061d95694b3f6a1a9d61b4/e4dde71190ef76c6f608fd549a16fdfaae5167f2.jpg", 'url': 'https://mp.weixin.qq.com/s?__biz=MzU1OTc0NTQ1OQ==&tempkey=OTgwX2tBU25rdGFHcjRuU0s2THJZRTVRNE5MQ0NMbTg1TmNrU2tRLWRvZWFxQ2ZGd0djSmdtazJoNC1NZXBKdEdlSmFuLU85ZHRJV2JkUlVHeTRienhCSVdQeGZpQ3BzajdBWUJJWC1zSWhfNlJWekc4ZEd5NGVrV2xkckZMTTUwX0FCdlNKN1BHc21JdldHSG1rZF9UT3g3V1NFQUpKcWFxcmNvLUQ3QVF%2Bfg%3D%3D&chksm=7c13d1c14b6458d7daa04b4a5e2737c2293aa2c678abfc3bad271bf63f11a961067f83183d63#rd' }) elif msg.key == 'V1001_ABOUT_ME': reply = ArticlesReply(message=msg) reply.add_article({ "title": "关于我", "description": "也没啥说的", 'image': 'http://i.dyt6.cc/0f/4d/04/cf/ea/c8/b2/f6/b2/79/7f/7f/0c/f5/db/0e.jpg', "url": "https://mp.weixin.qq.com/s/3u6BlqYLx8r9DiLBXbFU5g" }) else: # 回复图片信息 reply = ArticlesReply(message=msg) reply.add_article({ "title": "阿信", "description": "陈信宏(Ashin)", "image": "http://img5.imgtn.bdimg.com/it/u=1430011000,1084796449&fm=26&gp=0.jpg", "url": "https://baike.baidu.com/item/%E9%99%88%E4%BF%A1%E5%AE%8F/334?fr=aladdin" }) reply.add_article({ "title": "百度图库", "description": "图片", 'image': 'http://img3.imgtn.bdimg.com/it/u=1241905237,194043770&fm=26&gp=0.jpg', "url": "http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E9%98%BF%E4%BF%A1" }) reply.add_article({ "title": "百度图库", "description": "图片", 'image': 'http://img1.imgtn.bdimg.com/it/u=2285845240,3067239871&fm=26&gp=0.jpg', }) else: reply = create_reply('我们不知道这个时间类型是什么', msg) return reply
def get_reply_msg(): # 被动回复 https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Passive_user_reply_message.html if isinstance(msg, SubscribeScanEvent) or isinstance( msg, ScanEvent): # 未关注用户扫描带参数二维码事件 - 订阅关注 # 已关注用户扫描带参数二维码事件 platform_id = int(msg.scene_id) platform = Platform.get(platform_id=platform_id) assert platform user = User.get(openid=from_user_openid) if not user: # 创建 user user = User.create(openid=from_user_openid, bind_platform_id=platform.platform_id) else: # user 表记录, 存在 if user.bind_platform_id != platform.platform_id: log.w( f'platform_id change: {user.bind_platform_id} -> {platform.platform_id}, openid: {user.openid}' ) user.update(bind_platform_id=platform.platform_id) account = Account.get(user_id=user.user_id, platform_id=user.bind_platform_id) if not account: # 创建 account username = MyRandom.random_digit(length=8) expired_at = Datetime.localtime() + datetime.timedelta( days=1) # 新账户一天内免费 account = Account.create( user_id=user.user_id, platform_id=user.bind_platform_id, username=username, password=username, radius_password=username, role=Account.Role.PAY_USER.value, expired_at=expired_at, ) sentry_sdk.capture_message( f'有用户扫描带参数二维码, platform_id: {platform.platform_id}, openid: {from_user_openid}' ) # 判断是否允许房东注册 if platform.platform_id == settings.ADMIN_PLATFORM_ID: redis = get_redis() if redis.get('enable_platform_register'): # 新创建平台 new_platform = create_new_platform( user_id=user.user_id) platform_url = f'{settings.API_SERVER_URL}/platform/{new_platform.platform_id}' sentry_sdk.capture_message( f'房东平台已建立, platform_url: {platform_url}') redis.delete('enable_platform_register') # 应答 return TextReply( source=appid, target=from_user_openid, content= f'账号: {account.username}\n密码: {account.password}\n状态: {account.status}' ) if isinstance(msg, ClickEvent): # 点击按钮 - 账号中心 if msg.key == WeClient.ACCOUNT_VIEW_BTN_EVENT: user = User.get(openid=from_user_openid) if not user or user.bind_platform_id is None: # 用户未经扫码, 进入公众号 return TextReply(source=appid, target=from_user_openid, content=f'请先扫描房东的WIFI二维码') else: platform = Platform.get( platform_id=user.bind_platform_id) if platform.is_platform_owner( user_id=user.user_id ) and not settings.is_admin(openid=from_user_openid): # 房东不能打开充值页面, 但 admin 可以 return TextReply(source=appid, target=from_user_openid, content=f'房东不允许打开充值页面') r = ArticlesReply(source=appid, target=from_user_openid) r.add_article({ 'title': f'点击进入', 'description': '查询WIFI密码 / WIFI续费', 'image': 'http://zlxpic.lynatgz.cn/zhuzaiyuan_mini.jpg', 'url': WeClient.ACCOUNT_VIEW_URI, }) return r elif msg.key == WeClient.CUSTOMER_SERVICE_BTN_EVENT: return TextReply(source=appid, target=from_user_openid, content=settings.MP_DEFAULT_REPLY) elif isinstance(msg, SubscribeEvent): # 关注公众号事件 pass elif isinstance(msg, TextMessage): # 文本消息 if msg.content in ['help', '帮助', '命令']: command = [ 'id', '搜索 $name', 'free', '放通mac', '房东注册', ] message = '命令:\n ' + '\n '.join(command) return TextReply(source=appid, target=from_user_openid, content=message) elif msg.content == 'id': # 查看用户ID user = User.get(openid=from_user_openid) messages = [ f'你的信息:', f'openid: {user.openid}', f'user_id: {user.user_id}', ] return TextReply(source=appid, target=from_user_openid, content='\n'.join(messages)) # 以下命令需要 admin 权限 elif msg.content.startswith('搜索') and settings.is_admin( openid=from_user_openid): # 搜索用户信息 name = msg.content.split('搜索')[1].strip() return TextReply( source=appid, target=from_user_openid, content= f'{settings.API_SERVER_URL}/search/user?name={name}') elif msg.content.startswith('放通mac') and settings.is_admin( openid=from_user_openid): redis = get_redis() ex = 60 * 5 redis.set('enable_mac_authentication', str(datetime.datetime.now()), ex=ex) return TextReply(source=appid, target=from_user_openid, content=f'有效时间: {ex}秒') elif msg.content.startswith('房东注册') and settings.is_admin( openid=from_user_openid): redis = get_redis() ex = 60 * 5 redis.set('enable_platform_register', str(datetime.datetime.now()), ex=ex) return TextReply(source=appid, target=from_user_openid, content=f'有效时间: {ex}秒') elif msg.content.startswith('free') and settings.is_admin( openid=from_user_openid): expired_at = Datetime.localtime() + datetime.timedelta( minutes=30) account = Account.get(user_id=0, platform_id=0) if not account: account = Account.create( user_id=0, platform_id=0, username='******', password='******', radius_password='******', role=Account.Role.FREE_USER.value, expired_at=expired_at, ) else: account.update(expired_at=expired_at) content = f'用户名: {account.username}, 密码: {account.password}, 失效时间: {Datetime.to_str(expired_at, fmt="%Y-%m-%d %H:%M:%S")}' return TextReply(source=appid, target=from_user_openid, content=content) else: return TextReply(source=appid, target=from_user_openid, content=settings.MP_DEFAULT_REPLY) return None
def home(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', '') try: check_signature(WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: echo_str = 'error' response = HttpResponse(echo_str, content_type="text/plain") return response elif request.method == 'POST': msg = parse_message(request.body) if msg.type == 'text': muser = MagicUser.objects.get_or_create(openid=msg.source) print(muser[0].snumber) if '成绩' in msg.content and '更新' not in msg.content: reply = create_reply( str(muser[0].uuid) + str(msg.content), msg) print(str(muser[0].uuid)) if None == muser[0].snumber: url = BASEURL + reverse('index') + '?uuid=' + str( muser[0].uuid) + "&type=chengji&create=" + str( muser[1]) else: url = BASEURL + reverse('chengji') + '?uuid=' + str( muser[0].uuid) reply = ArticlesReply(message=msg) reply.add_article({ 'title': '成绩', 'description': '成绩', 'image': BASEURL + '/static/mags/imgs/weixinmsggrade.png', 'url': url }) elif '课表' in msg.content and '更新' not in msg.content: reply = create_reply( str(muser[0].uuid) + str(msg.content), msg) if None == muser[0].snumber: url = BASEURL + reverse('index') + '?uuid=' + str( muser[0].uuid) + "&type=kebiao&create=" + str(muser[1]) else: url = BASEURL + reverse('kebiao') + '?uuid=' + str( muser[0].uuid) reply = ArticlesReply(message=msg) reply.add_article({ 'title': '课表', 'description': '课表', 'image': 'http://pic1.sc.chinaz.com/files/pic/pic9/201803/zzpic10731.jpg', 'url': url }) elif '更新成绩' in msg.content or '更新课表' in msg.content: if None == muser[0].snumber: url = BASEURL + reverse('index') + '?uuid=' + str( muser[0].uuid) + "&type=chengji&create=" + str( muser[1]) else: url = BASEURL + reverse('gengxin') + '?uuid=' + str( muser[0].uuid) reply = ArticlesReply(message=msg) reply.add_article({ 'title': '更新成绩和课表', 'description': '更新成绩和课表点击前往更新', 'image': 'http://pic1.sc.chinaz.com/files/pic/pic9/201803/zzpic10731.jpg', 'url': url }) else: flag = False buildings = [ '致高楼A幢', '管理楼', '致用楼', '科学会堂', '致高楼B幢', '水利馆', '闻天馆', '博学楼', '工程馆', '北教楼', '致远楼', '江宁体育场', '研究生综合楼', '水文楼', '励学楼', '勤学楼' ] for i in buildings: if msg.content in i: flag = True break if flag: d = datetime.datetime.now() index = d.weekday() #false空闲 true有课 #西康路校区 江宁校区 江宁西校区 常州校区 todayres = test_curl_fetch( 'http://map.hhu.edu.cn/mapi/api/v2.0/classRoom.json?day=' + str(index)) tomorrowres = test_curl_fetch( 'http://map.hhu.edu.cn/mapi/api/v2.0/classRoom.json?day=' + str((index + 1) % 7)) todayjisoshi = json.loads(todayres)['data'] tomorrowjisoshi = json.loads(tomorrowres)['data'] today = '您查询的教学楼为: {}\n今天空闲的教室有:'.format(msg.content) tomorrow = '\n明天空闲的教室有:'.format(msg.content) for i in todayjisoshi: if msg.content in i['buildName']: today += i['code'] + ' ' for index, j in enumerate(i['lessons']): if not j: today += str(index + 1) + ' ' today += '小节|' for i in tomorrowjisoshi: if msg.content in i['buildName']: tomorrow += i['code'] + ' ' for index, j in enumerate(i['lessons']): if not j: today += str(index + 1) + ' ' tomorrow += '小节|' reply = create_reply(today, msg) else: reply = create_reply('暂不支持相关信息的查询', msg) elif msg.type == 'image': reply = create_reply('这是条图片消息', msg) elif msg.type == 'voice': reply = create_reply('这是条语音消息', msg) else: reply = create_reply('这是条其他类型消息', msg) response = HttpResponse(reply.render(), content_type="application/xml") return response
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 clickEvent(msg): reply = TextReply(content=u"I am 菜单拉取事件", message=msg) user = User.objects.get(openId=msg.source) id = user.id data = tools.client.user.get(msg.source) #更新用户姓名、头像 user.name = data["nickname"] if "headimgurl" in data: user.image = data["headimgurl"] else: user.image = "" user.save() date = basic_tools.getDate() datetime = basic_tools.getDateTime() now = basic_tools.getNow() if msg.key == "V1001_DATA_TODAY": #今日战况 data = DayData.objects.filter(user=user, date=date) if len(data) == 0: data = DayData(user=user, date=date) basic_tools.updateDayData(data, user) data.save() else: data = data[0] steps = data.steps dayPlan = user.dayPlan if steps < dayPlan: per = steps * 100 / dayPlan else: per = 100 if per <= 25: remark = u"前路漫漫,要加油噢!" elif per >= 40 and per <= 60: remark = u"成功的路已经走了一半,继续努力!" elif per == 100: remark = u"已经完成预定计划了!你真棒!" elif per >= 90: remark = u"就快要成功了!加油加油!" else: remark = "" url = "%s/basic/redirect/profile?page=0" % tools.domain data = { "steps": { "value": str(steps), "color": "#ff0000", }, "per": { "value": str(per), "color": "#007fff", }, "remark": { "value": remark, "color": "#666666" } } tools.customSendTemplate(msg.source, tools.template_id["data"], "#000000", data, url) reply = "" elif msg.key == "V1001_DATA_BIND": #绑定手环 url = "%s/basic/bind?openId=%s" % (tools.domain, msg.source) data = {"content": {"value": u"请点击进入绑定", "color": "#ff5656"}} tools.customSendTemplate(msg.source, tools.template_id["msg"], "#000000", data, url) reply = "" elif msg.key == "V1001_DATA_HELP": #帮助 reply = TextReply(content=tools.help_text, message=msg) elif msg.key == "V1001_DATA_PROFILE": #个人主页 dayPlan = user.dayPlan sleepPlan = user.sleepPlan if dayPlan == 0 or sleepPlan == 0: remark = u"您的计划设置不完整,请点击进入设置" else: remark = user.comment if remark == "": remark = u"点击查看个人信息" url = "%s/basic/redirect/profile?page=3" % tools.domain data = { "dayPlan": { "value": str(dayPlan), "color": "#ff0000" }, "sleepPlan": { "value": str(sleepPlan), "color": "#007fff" }, "remark": { "value": remark, "color": "#666666" } } tools.customSendTemplate(msg.source, tools.template_id["profile"], "#000000", data, url) reply = "" elif msg.key == "V1001_PLAN_MAKE": #制定计划 articles = [] articles.append({ "title": u"制定计划", "description": u"快来制定你自己的运动计划吧!", "image": "%s/static/img/plan_make.jpg" % tools.domain, "url": "%s/plan/redirect/profile?page=0" % tools.domain }) reply = ArticlesReply(articles=articles, message=msg) elif msg.key == "V1001_PLAN_OWN": #我的计划 articles = [] articles.append({ "title": u"查看我的", "description": u"来看看你都有什么运动计划吧", "image": "%s/static/img/plan_own.jpg" % tools.domain, "url": "%s/plan/redirect/profile?page=3" % tools.domain }) reply = ArticlesReply(articles=articles, message=msg) elif msg.key == "V1001_PLAN_SQUARE": #计划广场 articles = [] articles.append({ "title": u"计划广场", "description": u"新鲜出炉的运动计划", "image": "%s/static/img/plan_square.jpg" % tools.domain, "url": "%s/plan/redirect/profile?page=2" % tools.domain }) reply = ArticlesReply(articles=articles, message=msg) elif msg.key == "V1001_PLAN_RANK": #计划排行榜 articles = [] articles.append({ "title": u"计划排行榜", "description": u"想知道什么计划更受欢迎么", "image": "%s/static/img/plan_rank.jpg" % tools.domain, "url": "%s/plan/redirect/profile?page=1" % tools.domain }) reply = ArticlesReply(articles=articles, message=msg) elif msg.key == "V1001_MATCH_MAKE": #创建比赛 articles = [] articles.append({ "title": u"创建比赛", "description": u"开始一场新的比赛吧!", "image": "%s/static/img/match_make.jpg" % tools.domain, "url": "%s/match/redirect/profile?page=0" % tools.domain }) reply = ArticlesReply(articles=articles, message=msg) elif msg.key == "V1001_MATCH_CHECK": #我的比赛进度查看 closest_match = match_tools.closest_match(user, now) if not closest_match: #没有未结束的比赛 data = { "title": { "value": u"比赛进度提醒", "color": "#000000" }, "content": { "value": u"没有未结束的比赛", "color": "#ff0000" }, "remark": { "value": u"来亲自发起一场比赛吧!", "color": "#666666" } } url = "%s/match/redirect/profile?page=0" % tools.domain tools.customSendTemplate(msg.source, tools.template_id["msg"], "#000000", data, url) else: #返回最近的比赛的进度 left_time = basic_tools.left_time(now, closest_match.endTime) steps = match_tools.getProgress(closest_match, user) data = { "object": { "value": u"%s 比赛" % closest_match.title, "color": "#007fff" }, "lastTime": { "value": left_time, "color": "#ff0000" }, "steps": { "value": str(steps), "color": "#007fff" }, "remark": { "value": u"请继续努力!", "color": "#666666" } } url = "%s/match/redirect/profile?page=1" % tools.domain tools.customSendTemplate(msg.source, tools.template_id["progress"], "#000000", data, url) reply = "" elif msg.key == "V1001_MATCH_SQUARE": #比赛广场 articles = [] articles.append({ "title": u"比赛广场", "description": u"新鲜出炉的比赛", "image": "%s/static/img/match_square.jpg" % tools.domain, "url": "%s/match/redirect/profile?page=2" % tools.domain }) reply = ArticlesReply(articles=articles, message=msg) return HttpResponse(reply)
reply = '' if msg.type == 'text': reply = create_reply('Text:' + msg.content.encode('utf-8'), message=msg) elif msg.type == 'image': reply = create_reply('图片', message=msg) try: r = requests.get(msg.image) # download image filename = 'img/' + str(int(time.time())) + '.jpg' convertfilename = filename.replace('.', '.convert.') with open(filename, 'w') as f: f.write(r.content) if cv2.imread(filename) is not None: # load model with open('model.json', 'r') as f: model = model_from_json(f.read()) model.load_weights('model.h5') cv2.imwrite(convertfilename, convert(filename)) url = 'http://w.luckiestcat.com/' + convertfilename reply = ArticlesReply(message=msg, articles=[{ 'title': u'识别成功', 'url': url, 'description': u'', 'image': url }]) except: reply = create_reply('识别失败', message=msg) print reply