def remove_img_bg(msg, accessToken=None): resp_xml = None try: if msg.type == 'text': no_bg_img_path = wechat.rmBg.get_result_bytaskid(msg.content) if no_bg_img_path == 'error': return get_rmbg_error_reply(msg) elif no_bg_img_path: media_id = upload('image', no_bg_img_path, accessToken) from wechatpy.messages import ImageMessage newMsg = ImageMessage(msg._data) reply = ImageReply(media_id=media_id, message=newMsg) return reply.render() else: return get_imgerr_reply(msg) # 通过公众号接收到的图片信息下载图片到本地 path = download(msg.image, msg.source) # 调用ai去除背景接口,保存结果图片后,返回对应路径 taskid = wechat.rmBg.do_remove(path) import threading print(threading.current_thread().name, taskid) text = '下载注意事项:请用[5a4490.../red]的格式发送消息,用于下载处理后图像文件。\n颜色默认为白色(white),同时支持红色(red),蓝色(blue)。\n验证码:%s' % taskid resp_xml = create_reply(text, message=msg, render=True) except Exception as e: resp_xml = get_error_reply(msg) return resp_xml
def _response2xml(self, response, msg): """ 将response解析成需要的xml :param response: :return: """ # 图片型 if response.startswith("#Image"): path = response.replace("#Image:", "") medie_id = self._weixin_util.upload(path) replay = ImageReply(media_id=medie_id, message=msg) xml = replay.render() return xml else: # 文本型的xml if response.startswith("#json:"): response = response.replace("#json:", "") response_json = json.loads(response) # print(response_json) # 处理url类的 for key in response_json: if "url" in key: response = "你自己看吧。\n{}".format(response_json[key]) break reply = TextReply(content=response, message=msg) xml = reply.render() return xml
def test_image_reply_properties(self): from wechatpy.replies import ImageReply reply = ImageReply(image='7890') self.assertEqual('7890', reply.image) self.assertEqual('7890', reply.media_id) reply.media_id = '123456' self.assertEqual('123456', reply.image) self.assertEqual('123456', reply.media_id)
def weixinInterface(): if check_signature: data = request.data msg = parse_message(data) path = get_qcode(request.args['openid']) md_id = get_media_id(CLIENT, path) reply = ImageReply(media_id=md_id, message=msg) xml = reply.render() return xml else: return 'signature error'
def test_image_reply_properties(self): from wechatpy.replies import ImageReply reply = ImageReply(image="7890") self.assertEqual("7890", reply.image) self.assertEqual("7890", reply.media_id) reply.media_id = "123456" self.assertEqual("123456", reply.image) self.assertEqual("123456", reply.media_id)
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 weixin(): import hashlib, lxml, time, os, json from lxml import etree if request.method == 'GET': signature = request.values.get('signature') timestamp = request.values.get('timestamp') nonce = request.values.get('nonce') echostr = request.values.get('echostr') global token try: check_signature(token, signature, timestamp, nonce) return echostr except InvalidSignatureException: return echostr + 'failed' elif request.method == 'POST': str_xml = request.data msg = parse_message(str_xml) print(str_xml) if msg.type == 'text': return TextReply(content='u just say : ' + msg.content, message=msg).render() elif msg.type == 'image': return ImageReply(media_id=add_watermark( msg.media_id, appId, appSecret).get_media_id_with_watermark(), message=msg).render() return 'wassup'
def on_post(self, req, resp): xml = req.stream.read() msg = parse_message(xml) if msg.type == 'text': try: text = msg.content c = len(text) if c == 1 and '啊' not in text and '哼' not in text and '嗨' not in text: poem_flag = 24 poem = self.pchat.gen_poem(text, poem_flag) replyTxt = self.pchat.pretty_print_poem(poem_=poem) tf.reset_default_graph() else: eliza = ElizaChat() replyTxt = eliza.analyze(text) if replyTxt == "@$@": replyTxt, score = self.retrieval.api(text) replyTxt = replyTxt reply = TextReply(content=replyTxt, message=msg) xml = reply.render() resp.body = (xml) resp.status = falcon.HTTP_200 except Exception as e: print(e) elif msg.type == 'image': reply = ImageReply(media_id=msg.media_id, message=msg) xml = reply.render() resp.body = (xml) resp.status = falcon.HTTP_200
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 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 wechat_msg(): token = app.config.get('WX_TOKEN') sign = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') echostr = request.args.get('echostr', '') if request.method == 'GET': try: check_signature(token, sign, timestamp, nonce) except InvalidSignatureException: logger.warning("Signature check failed.") return Response(echostr) # if request.method == "POST": header = {"content_type": "application/xml;charset=utf-8"} body = request.data logger.info(body) msg = parse_message(body) if not msg: logger.info('Empty message, ignored') return if msg.type == 'text': logger.info('message type text from %s', msg.source) response = respond(msg.content, msg.source) if response: pass else: response = '你说的我接不上啊,试着夸夸我鸭' reply = create_reply(response, msg, render=True) logger.info('Replied to %s with "%s"', msg.source, response) return Response(reply, content_type=header['content_type']) elif msg.type == 'location': # if options.debug: logger.info('message type location from %s', msg.source) elif msg.type == 'image': # if options.debug: logger.info('message type image from %s', msg.source) logger.info(msg.image) myimage = image_process(msg.image) if not myimage: replay = create_reply('失败', msg, render=True) elif myimage == "": replay = create_reply(myimage, msg, render=True) else: myimage_id = weChatClient.api.WeChatMaterial.add('image', myimage) replay = ImageReply(type='image' ,media_id =myimage_id).render() return Response(replay, content_type=header['content_type']) else: logger.info('message type unknown')
def handle_click_event(self): if self.message.key.lower() == 'time_remind_today': now = timezone.now() time_reminds = self.user.get_time_reminds().filter(time__date=now).order_by('time').all() remind_text_list = self.format_remind_list(time_reminds) if remind_text_list: return self.text_reply('/:sunHi %s, 你今天的提醒有:\n\n%s' % (self.user.get_full_name(), '\n'.join(remind_text_list))) return self.text_reply('/:coffee今天没有提醒,休息一下吧!') elif self.message.key.lower() == 'time_remind_tomorrow': tomorrow = timezone.now()+timedelta(days=1) time_reminds = self.user.get_time_reminds().filter(time__date=tomorrow).order_by('time').all() remind_text_list = self.format_remind_list(time_reminds, True) if remind_text_list: return self.text_reply('/:sunHi %s, 你明天的提醒有:\n\n%s' % (self.user.get_full_name(), '\n'.join(remind_text_list))) return self.text_reply('/:coffee明天还没有提醒,休息一下吧!') elif self.message.key.lower() == 'customer_service': logger.info('Transfer to customer service for %s', self.user.get_full_name()) return TransferCustomerServiceReply(message=self.message).render() elif self.message.key.lower() == 'join_group': logger.info('Sending 小密圈 QR code to %s', self.user.get_full_name()) wechat_client.message.send_text(self.user.openid, u'喜欢微定时?请加入微定时小密圈,欢迎各种反馈和建议~') # http://mmbiz.qpic.cn/mmbiz_jpg/U4AEiaplkjQ3olQ6WLhRNIsLxb2LD4kdQSWN6PxulSiaY0dhwrY4HUVBBYFC8xawEd6Sf4ErGLk7EZTeD094ozxw/0?wx_fmt=jpeg return ImageReply(message=self.message, media_id='S8Jjk9aHXZ7wXSwK1qqu2UnkQSAHid-VQv_kxNUZnMI').render() elif self.message.key.lower() == 'donate': logger.info('Sending donation QR code to %s', self.user.get_full_name()) wechat_client.message.send_text(self.user.openid, u'好的服务离不开大家的鼓励和支持,如果觉得微定时给你的生活带来了一丝便利,' u'请使劲用赞赏来支持(别忘了备注微信名,否则微信不让我看到是谁赞赏的)。') # http://mmbiz.qpic.cn/mmbiz_png/U4AEiaplkjQ26gI5kMFhaBda9CAcI5uxE4FDwWp8pOduoyBDDuWXtdgxx9UMH3GxUgrRoqibsqDHtwMMNjHJkjVg/0?wx_fmt=png return ImageReply(message=self.message, media_id='S8Jjk9aHXZ7wXSwK1qqu2b6yDboZT6UIvYWF4dKLyQs').render() elif self.message.key.lower() == 'donate_geizang': logger.info('Sending donation GeiZang QR code to %s', self.user.get_full_name()) wechat_client.message.send_text(self.user.openid, u'好的服务离不开大家的鼓励和支持,如果觉得微定时给你的生活带来了一丝便利,' u'请使劲用赞赏来支持。') # http://mmbiz.qpic.cn/mmbiz_png/U4AEiaplkjQ0DypiahsELePfHTh2NysKvQmqTBoqVTHabpPPJiaqg5aFunCUdVwraGMdcCo2Tz9GngWccoch3YWow/0?wx_fmt=png return ImageReply(message=self.message, media_id='S8Jjk9aHXZ7wXSwK1qqu2d1M_OVm4CoEECgdDlrG0mQ').render() elif self.message.key.lower() == 'add_friend': logger.info('Sending personal QR code to %s', self.user.get_full_name()) wechat_client.message.send_text(self.user.openid, u'长按下面的二维码,添加作者个人微信,等你来撩~') # http://mmbiz.qpic.cn/mmbiz_jpg/U4AEiaplkjQ1x2YoD9GRticXvMk5iaWJCtEVuChsHecnwdfHFbiafJarWXyiaABTu4pPUKibvnJ1ZGwUF7arzCaFkArw/0?wx_fmt=jpeg return ImageReply(message=self.message, media_id='S8Jjk9aHXZ7wXSwK1qqu2SXTItktLfgk4Cv9bod5l8k').render() return self.handle_unknown_event()
def wechat(request): if request.method == 'GET': signature = request.GET.get('signature', None) timestamp = request.GET.get('timestamp', None) nonce = request.GET.get('nonce', None) echostr = request.GET.get('echostr', None) try: check_signature(WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: echostr = 'error' return HttpResponse(echostr) elif request.method == 'POST': msg = parse_message(request.body) print(msg) # if msg.type == 'text': # if msg.content == '民事案件': # reply = getDogLossList(request, msg) # elif msg.content == '刑事案件': # reply = getDogOwnerList(request, msg) # else: # reply = TransferCustomerServiceReply(message=msg) # code = request.POST.get('code',None) # print(code,1111111111) if msg.type == 'image': reply = ImageReply(message=msg) reply.media_id = msg.media_id elif msg.type == 'voice': reply = VoiceReply(message=msg) reply.media_id = msg.media_id reply.content = '语音信息' elif msg.type == 'event': print('eventkey=', msg.event) if msg.event == 'subscribe': print(333333333333) saveWxLaw(msg.source) reply = create_reply('感谢您关注【辽宁大潮律师事务所】', msg) elif msg.event == 'unsubscribe': reply = create_reply('取消关注公众号', msg) unSubUserinfo(msg.source) elif msg.event == 'subscribe_scan': reply = create_reply('感谢您关注【辽宁大潮律师事务所】', msg) saveWxLaw(msg.source, msg.scene_id) print('scene_id=', msg.scene_id) elif msg.event == 'scan': print('scan====', msg.scene_id) # setUserToMember(msg.source, msg.scene_id) reply = create_reply('', msg) else: reply = create_reply('view', msg) response = HttpResponse(reply.render(), content_type="application/xml") return response
def photo_score(msg, accessToken=None): resp_xml = chk_msg_types(msg, ['image'], '该功能只能处理图像数据。') if resp_xml: return resp_xml try: # 通过公众号接收到的图片信息下载图片到本地 path = download(msg.image, msg.source) # 调用腾讯ai人脸识别接口接口 r = wechat.face.access_api(path) if r == 'success': # 上传图片,得到 media_id media_id = upload('image', path, accessToken) reply = ImageReply(media_id=media_id, message=msg) else: reply = TextReply(content='人脸检测失败,请上传1M以下人脸清晰的照片', message=msg) resp_xml = reply.render() except Exception as e: resp_xml = get_error_reply(msg) return resp_xml
def get_image_url(self, msg): url = 'http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1' response = requests.get(url, headers=headers) strJson = json.loads(response.content) url = 'http://s.cn.bing.net' + strJson['images'][0]['url'] context = '' context += '<a href="{}">每日必应图片</a>'.format(url) # reply = create_reply(str(context), msg) reply = ImageReply( message=msg, media_id= 'Ve1pve6vOfZerye0t8gV8V6DKiEC-hOvsZRMdHmK5-oRZuHZspMlJSsn9ei2_N0o') return reply
def image_resp(self, msg, resp): if resp['ret'] == 0: file_obj = StringIO(base64.b64decode(resp['data']['image'])) # https://stackoverflow.com/questions/26300054/set-name-header-of-multipart-encoded-file-post mid = self._media_upload(media_file=('tmp.jpg', file_obj)) if not mid: return create_reply('系统暂时不能处理此格式的图,请尝试其他图!', msg) reply = ImageReply(media_id=mid, message=msg) # 本次步骤已经结束了,删除当前指令 self.cache.delete(msg.source) else: reply = create_reply(u'%s, 重新发送一张图试试吧!' % resp['msg'], msg) return reply
def on_post(self, req, resp): xml = req.stream.read() msg = parse_message(xml) if msg.type == 'text': reply = TextReply(content=msg.content, message=msg) xml = reply.render() resp.body = (xml) resp.status = falcon.HTTP_200 elif msg.type == 'image': reply = ImageReply(media_id=msg.media_id, message=msg) xml = reply.render() resp.body = (xml) resp.status = falcon.HTTP_200
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 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 response(msg, bot=None): keyword = None if msg.type == 'text': keyword = msg.content.replace(u'斗图', '').strip() result = search(keyword) if not result or not bot: if bot: # 退出斗图. bot.cache.clear() return u'我败了,无图可战<系统将自动退出斗图模式>' try: result = bot.wechat_client.media.upload(media_type='image', media_file=result) mid = result['media_id'] return ImageReply(message=msg, media_id=mid) except WeChatClientException, e: return u'我败了.....,如果需要退出请输入字母 Q'
def wechat(request): if request.method == 'GET': signature = request.GET.get('signature', None) timestamp = request.GET.get('timestamp', None) nonce = request.GET.get('nonce', None) echostr = request.GET.get('echostr', None) try: check_signature(settings.WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: echostr = 'error' return HttpResponse(echostr) elif request.method == 'POST': msg = parse_message(request.body) if msg.type == 'text': reply = TransferCustomerServiceReply(message=msg) 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 = msg.media_id reply.content = '语音信息' elif msg.type == 'event': print('eventkey=', msg.event) if msg.event == 'subscribe': saveUserinfo(msg.source) reply = create_reply('你好,欢迎关注亚电新能源', msg) elif msg.event == 'unsubscribe': reply = create_reply('取消关注公众号', msg) unSubUserinfo(msg.source) elif msg.event == 'subscribe_scan': reply = create_reply('你好,欢迎关注亚电新能源', msg) saveUserinfo(msg.source, msg.scene_id) elif msg.event == 'scan': reply = create_reply('', msg) else: reply = create_reply('view', msg) else: reply = create_reply('', msg) response = HttpResponse(reply.render(), content_type="application/xml") return response
def on_post(self, req, resp): xml = req.stream.read() msg = parse_message(xml) if msg.type == 'text': reply = TextReply(content=msg.content, message=msg) xml = reply.render() resp.body = (xml) resp.status = falcon.HTTP_200 elif msg.type == 'image': name = img_download(msg.image, msg.source) print(name) r = access_api('images/' + name) if r == 'success': media_id = img_upload('image', 'faces/' + name) reply = ImageReply(media_id=media_id, message=msg) else: reply = TextReply(content='人脸检测失败,请上传1M以下人脸清晰的照片', message=msg) xml = reply.render() resp.body = (xml) resp.status = falcon.HTTP_200
def on_post(self, req, resp): # 猜测是打开数据流 xml = req.stream.read() # 解析xml格式数据 msg = parse_message(xml) if msg.type == 'text': reply = TextReply(content='露露我爱你', message=msg) # content=msg.content xml = reply.render() resp.body = (xml) resp.status = falcon.HTTP_200 elif msg.type == 'image': reply = ImageReply(media_id=msg.media_id, message=msg) xml = reply.render() resp.body = (xml) resp.status = falcon.HTTP_200 elif msg.type == 'voice': reply = VoiceReply(media_id=msg.media_id, message=msg) xml = reply.render() resp.body = (xml) resp.status = falcon.HTTP_200
def on_post(self, req, resp): xml = req.stream.read() msg = parse_message(xml) if msg.type == 'text': if msg.content == '笑话': cursor = table.find({'id': random.randint(1, 6)}) for i in cursor: content = i["joke"] print(content) reply = TextReply(content=content, message=msg) xml = reply.render() else: print(msg, msg.content) reply = TextReply(content=msg.content, message=msg) xml = reply.render() resp.body = (xml) resp.status = falcon.HTTP_200 elif msg.type == 'image': reply = ImageReply(media_id=msg.media_id, message=msg) xml = reply.render() resp.body = (xml) resp.status = falcon.HTTP_200
def on_post(self, req, resp): xml = req.stream.read() msg = parse_message(xml) from_user_name = self.extract_from_username(msg) input_language_zh = True if len(self.cache_dict) > 200: del (self.cache_dict) self.cache_dict = {} if msg.type == 'text': inputTxt = msg.content if inputTxt in self.cache_dict: if self.cache_dict[inputTxt]: replyTxt = self.cache_dict[inputTxt] reply = TextReply(content=replyTxt, message=msg) del (self.cache_dict) self.cache_dict = {} xml = reply.render() resp.body = (xml) resp.status = falcon.HTTP_200 return language = self.judge_language(inputTxt) if language == 'en': input_language_zh = False inputTxt = translate(inputTxt, 'en') replyTxt, reply_type = self.getReply(inputTxt, input_language_zh, msg.id, from_user_name) if "@@##$$@@" not in replyTxt and replyTxt and reply_type == "chat": self.cache_dict[inputTxt] = replyTxt reply = TextReply(content=replyTxt, message=msg) xml = reply.render() resp.body = (xml) resp.status = falcon.HTTP_200 elif msg.type == 'image': reply = ImageReply(media_id=msg.media_id, message=msg) xml = reply.render() resp.body = (xml) resp.status = falcon.HTTP_200
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 wechat_check(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(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: return HttpResponse(status=403) return HttpResponse(echo_str) else: # 自动回复文本 try: msg = parse_message(request.body) if isinstance(msg, BaseEvent): if msg.event == 'subscribe': reply = create_reply(article_leizhu, message=msg) elif msg.event == 'click': if msg.key == 'inform_articles': reply = create_reply(inform_articles, msg) elif msg.key == "service": reply = ImageReply(message=msg, media_id='nvnR6egwWE1WzzIcMXo403dxqfcx5fV_GRhQnRH8Wsw') # 添加扫描二维码关注事件 elif msg.event == "scan": reply = create_reply(article_leizhu, message=msg) try: xml_data = str(request.body.decode()) dict = xmltodict.parse(xml_data) user = dict["xml"]["FromUserName"] print("扫码用户的openid:{}".format(user)) # user_li = re.findall(r"qrscene_(\d+)", user) # user_id = int("".join(user_li)) + 100000 # openid = dict["xml"]["FromUserName"] except Exception as e: print(e) elif msg.event == "subscribe_scan": reply = create_reply(article_leizhu, message=msg) xml_data = str(request.body.decode()) print(xml_data, "454545454") dict = xmltodict.parse(xml_data) user = dict["xml"]["EventKey"] user_li = re.findall(r"qrscene_(\d+)", user) user_id = int("".join(user_li)) + 100000 openid = dict["xml"]["FromUserName"] print("扫码用户的openid:{},id:{}".format(openid, user_id)) userinfo = UserInfo.objects.check_user(openid) create_time = timezone.now() # if create_time.strftime("%Y-%m-%d") == "2018-04-1": # fools_day = 1 # else: # fools_day = 0 # 如果该用户关系已经存在,那么就不创建该用户关系表 if len(UserInvite.objects.filter(invite=openid)) > 0: print("用户关系已经存在,则什么也不做") pass else: print("用户关系不存在,则创建用户关系表") # 创建用户关系 UserInvite.objects.create(user_id=user_id, invite=openid, create_time=create_time, fools_day=0) # 创建用户邀请数量表 Invitenum.objects.undate_num(user_id=user_id) # 增加用户赚取收益比例 Invitenum.objects.earning(user_id=user_id) else: reply = create_reply('请重试', msg) elif isinstance(msg, BaseMessage): if msg.type == 'text': content = msg.content if "说明" in content: reply = create_reply(inform_articles, message=msg) elif "客服" in content: reply = ImageReply(message=msg, media_id='nvnR6egwWE1WzzIcMXo403dxqfcx5fV_GRhQnRH8Wsw') elif "2018" in content: reply = create_reply(article_2018, message=msg) elif "提现" in content: reply = create_reply(withdraw, message=msg) elif "测试" in content: reply = create_reply(menu, message=msg) elif "999" in content: reply = ImageReply(message=msg, media_id='nvnR6egwWE1WzzIcMXo403dxqfcx5fV_GRhQnRH8Wsw') else: reply = create_reply(menu, message=msg) else: reply = create_reply('', message=msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return HttpResponse(reply.render(), content_type="application/xml") except (InvalidSignatureException, InvalidAppIdException): return HttpResponse(status=403)
def handle_wx(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(token, signature, timestamp, nonce) except InvalidSignatureException: echo_str = '错误的请求' response = HttpResponse(echo_str) # client = WeChatClient("wx058a1e6adf42dede", "d4631adb81c598c1f9acddfb4bc2ba10") # menu = client.menu.get() # print(menu) return response elif request.method == 'POST': xml = request.body msg = parse_message(xml) openid = msg.source try: if msg.type == 'text': reply = TextReply(content=msg.content, message=msg) print(msg.content) return HttpResponse(reply.render()) elif msg.type == 'image': print(msg.media_id) reply = ImageReply(media_id=msg.media_id, message=msg) return HttpResponse(reply.render()) elif msg.type == 'voice': print(msg.media_id) reply = VoiceReply(media_id=msg.media_id, message=msg) return HttpResponse(reply.render()) elif msg.type == 'video': print(msg) reply = VideoReply(media_id=msg.media_id, thumb_media_id=msg.thumb_media_id, title='title', description='description', message=msg) print(reply) print(msg.media_id) return HttpResponse(reply.render()) elif msg.type == 'music': print(msg.thumb_media_id, msg.title, msg.description) reply = MusicReply(thumb_media_id=msg.thumb_media_id, title='title', description='description', music_url=msg.music_url, hq_music_url=msg.hq_music_url, message=msg) return HttpResponse(reply.render()) # elif msg.type == 'news': # reply = ArticlesReply(message=msg, articles=[ # { # 'title': u'标题1', # 'description': u'描述1', # 'url': u'http://www.qq.com', # }, # { # 'title': u'标题2', # 'description': u'描述2', # 'url': u'http://www.qq.com', # 'image': 'http://img.qq.com/1.png', # }, # ]) # # 继续添加 # reply.add_article({ # 'title': u'标题3', # 'description': u'描述3', # 'url': u'http://www.qq.com', # }) # r_xml = reply.render() # return HttpResponse(r_xml) elif msg.type == 'event': push = ScanCodeWaitMsgEvent(msg) #获取二维码信息,字符串 content = msg.scan_result print(content) # 如何处理,自行处理,回复一段文本或者图文 reply = TextReply(content="Someting", message=msg) r_xml = reply.render() return HttpResponse(r_xml) #pass except Exception as e: print("Exception:", e) return "success" return HttpResponse('ok')
def POST(self): try: xml = web.data() msg = parse_message(xml) if msg.type == 'text': content = msg.content if content.startswith(('表情包:', '表情包:')): words = ''.join(content.replace(':', ':').split(':')[1:]) wechat_client = WeChatClient( appid='wx19a2591b2a719add', secret='c46fa65dbc2803b90431fbf9c803cbd4', ) access_token = wechat_client.access_token json_data = pics.upload_pic(pics.get_random_pic(words), access_token) # print(json_data) if 'errcode' not in json_data: media_id = json_data['media_id'] reply = ImageReply(message=msg) reply.media_id = media_id # print(web.url() + ' get_pic. words: ' + words + ' return: ' + str(json_data)) logger.info(web.url() + ' get_pic. words: ' + words + ' return: ' + str(json_data)) else: reply = TextReply(message=msg) reply.content = json_data['link'] logger.warning(web.url() + ' get_pic faild,return link. words:' + words + ' return: ' + json_data['link']) elif content.startswith(('影视:', '影视:')): words = ''.join(content.replace(':', ':').split(':')[1:]) if words == '': string = '没有输入要搜索的名字!' logger.info(web.url() + ' get_movie without words') else: data = search(words) data1 = data[0] data2 = data[1] if len(data1) != 0: string = '' if len(data1) <= 12: for each in data1: string += '%s %s %s %s\n' % (each[0], each[1], each[3], each[4]) else: for each in data1[:12]: string += '%s %s %s %s\n' % (each[0], each[1], each[3], each[4]) elif len(data2) != 0: string = '' if len(data2) <= 12: for each in data2: string += '%s %s %s %s\n' % (each[0], each[1], each[3], each[4]) else: for each in data2[:12]: string += '%s %s %s %s\n' % (each[0], each[1], each[3], each[4]) else: string = '竟然没有搜索到!!!\n请检查名称输入的是否正确,请尽量使用中文哦' # print(web.url() + ' get_pic. words: ' + words + ' data: ' + str(data) + ' return: ' + string) logger.info(web.url() + ' get_movie. words: ' + words + ' data: ' + str(data) + ' return: ' + string) reply = TextReply(message=msg) reply.content = string elif content.startswith(('在线:', '在线:')): words = ''.join(content.replace(':', ':').split(':')[1:]) if words == '': string = '没有输入要搜索的名字!' logger.info(web.url() + ' see_movie without words') else: data = get_link(words) if data: string = data else: string = '竟然没有搜索到!!!\n请检查名称输入的是否正确,请试试英文名哦' # print(web.url() + ' see_pic. words: ' + words + ' data: ' + str(data) + ' return: ' + string) logger.info(web.url() + ' see_movie. words: ' + words + ' data: ' + str(data) + ' return: ' + string) reply = TextReply(message=msg) reply.content = string else: reply = TextReply(message=msg) response = get_response(content) logger.info(web.url() + ' turing. words: ' + content + ' response: ' + response) reply.content = response elif msg.type == 'event' and msg.event: mscontent = msg.event if mscontent == "subscribe": string = '终于等到你!欢迎关注Snoopy同学~\n' \ '输入"表情包:xxx"获取自定义文字的表情\n' \ '输入"影视:xxx"获取电影的网盘链接\n' \ '输入"在线:xxx"获取在线观看视频的链接,需要复制到浏览器使用哦~' reply = TextReply(message=msg) reply.content = string elif mscontent == "unsubscribe": string = '有什么不足之处还请谅解,我会慢慢改进,欢迎您以后再来' reply = TextReply(message=msg) reply.content = string # 转换成 XML reply_xml = reply.render() return reply_xml except Exception as e: logger.error(e) # print(e) return "success"
def image_reply(msg): reply = ImageReply(message=msg) id = random.randint(0, 7) if id == 0: reply.media_id = "3nZjDfLSZGG6pM1moOgVpiIxl77Ii501riZPHS7NdOY" elif id == 1: reply.media_id = "3nZjDfLSZGG6pM1moOgVpm4_XftO2zaJxsCO9KHOpZE" elif id == 2: reply.media_id = "3nZjDfLSZGG6pM1moOgVphls0UeRqcAHael9a_KTrM4" elif id == 3: reply.media_id = "3nZjDfLSZGG6pM1moOgVpteYUBCK3Evkc3YYnQcDf3E" elif id == 4: reply.media_id = "3nZjDfLSZGG6pM1moOgVppGMwQTVoaNRb5nQMIPYMmE" elif id == 5: reply.media_id = "3nZjDfLSZGG6pM1moOgVpp21QXwC-r14DremI0PdZjQ" elif id == 6: reply.media_id = "3nZjDfLSZGG6pM1moOgVpgWdPB8IBUo57Avk3Med_4k" else: k = msg.media_id reply.media_id = "%s" % k return reply.render()