def weixinCheck(request): ''' 所有的消息都会先进入这个函数进行处理,函数包含两个功能, 微信接入验证是GET方法, 微信正常的收发消息是用POST方法。 :param request: :return: ''' 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) token = WEIXIN_TOKEN print('进来了') try: check_signature(token, signature, timestamp, nonce) return HttpResponse(request.GET.get('echostr', ''), content_type="text/plain") except InvalidSignatureException: # 处理异常情况或忽略 print('验证失败') elif request.method == 'POST': xml_message = smart_str(request.body) msg = parse_message(xml_message) reply = TextReply(content='你好,这是测试', message=msg) xml_respose = reply.render() return HttpResponse(xml_respose, content_type="application/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(self, request, message, wechat): """ 发布中测试 """ logger = getLogger('django.request.test_ProcessServerEventView') logger.info(message) if message.get('MsgType').lower() == 'event': reply = TextReply() reply.target = message['FromUserName'] reply.source = message['ToUserName'] reply.content = message['Event'] + 'from_callback' xml_str = reply.render() headers = {'CONTENT_TYPE': request.META['CONTENT_TYPE']} return Response(xml_str, headers=headers) elif message.get('MsgType').lower() in consts.MESSAGE_TYPES: if message.get('Content') == 'TESTCOMPONENT_MSG_TYPE_TEXT': reply = TextReply() reply.target = message['FromUserName'] reply.source = message['ToUserName'] reply.content = 'TESTCOMPONENT_MSG_TYPE_TEXT_callback' xml_str = reply.render() headers = {'CONTENT_TYPE': request.META['CONTENT_TYPE']} return Response(xml_str, headers=headers) elif message.get('Content').startswith('QUERY_AUTH_CODE'): from datetime import timedelta now = datetime.utcnow() + timedelta(seconds=2) query_auth_code = message.get('Content').split(':')[1] process_wechat_query_auth_code_test.apply_async( (message['FromUserName'], query_auth_code), eta=now) return Response('')
def 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 _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 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 state_bind(request, user, msg, data, step): if step == 0: return TextReply(content='Twitter ID:', message=msg), data elif step == 1: data['twitter_id'] = msg.content return TextReply(content='Tag (e.g. #NintendoSwitch):', message=msg), data elif step == 2: data['tag'] = msg.content if 'twitter_id' not in data: logger.error( f'twitter_id not found in state @bind at step: {step}, {msg}, {data}' ) return None, None with transaction.atomic(): tasks = Task.objects.select_for_update().filter(owner=user.user) if tasks.exists(): tasks.update(username=data['twitter_id'], tag=msg.content, last_update=timezone.now()) else: Task.objects.create(username=data['twitter_id'], tag=msg.content, owner=user.user) return TextReply(content='Bind success.', message=msg), None else: logger.error(f'Unknown step for state @bind: {step}, {msg}, {data}') return None, None
def token(): if request.method == 'GET': signature = request.args.get('signature') timestamp = request.args.get('timestamp') nonce = request.args.get('nonce') echo_str = request.args.get('echostr') # echo_str是微信用来验证服务器的参数,需原样返回 print(signature, timestamp, nonce, echo_str) try: print('正在验证服务器签名') # 无法验证成功??? # check_signature(token, signature, timestamp, nonce) print('验证签名成功') except InvalidSignatureException as e: print('检查签名出错: '.format(e)) return 'Check Error' return echo_str # POST print('开始处理用户消息') msg = parse_message(request.data) reply_text = handle_msg(msg) reply = TextReply(message=msg) reply.content = reply_text return reply.render()
def get_robot_reply(msg): if "你叫什么" in msg.content: answer = "洋葱骑士" elif "你名字" in msg.content: answer = "洋葱骑士" elif "你是谁" in msg.content: answer = "洋葱骑士" elif "小组编号" in msg.content: answer = "02" elif "小组成员" in msg.content: answer = "杨涵越(组长),华豪,邹鹏程,许金仓,张诚,王清洋,李书宽" elif "军事新闻" in msg.content: answer = NEWS() # elif "二维码" in msg.content: # answer = "请输入你要生成的内容:" # qr() else: try: # 调用NLP接口实现智能回复 params = urllib.parse.urlencode({ 'msg': msg.content }).encode() # 接口参数需要进行URL编码 req = urllib.request.Request("http://api.itmojun.com/chat_robot", params, method="POST") # 创建请求 answer = urllib.request.urlopen( req).read().decode() # 调用接口(即向目标服务器发出HTTP请求,并获取服务器的响应数据) if answer == "": answer = "人家听不懂你在说什么" except Exception as e: answer = "AI机器人出现故障!(原因:%s)" % e reply = TextReply(content='%s' % answer, message=msg) return reply.render()
async def weixin_reply(request): if request.method == 'GET': res = request_para(request) sign_ture = res.get('signature') time_stamp = res.get('timestamp') nonce_ = res.get('nonce') echo_str = res.get('echostr') try: check_signature(token='4725471112', signature=sign_ture, timestamp=time_stamp, nonce=nonce_) return_str = echo_str except InvalidSignatureException: log_exp.error('InvalidSignatureException') return_str = 'InvalidSignatureException' return response.text(body=return_str) elif request.method == 'POST': xml = request.body msg = parse_message(xml) if msg.type == 'text' and msg.source == 'opfB6w88fRxMh6DJirlzW8biOFNw': # 固定1148270327这个用户 res_msg = web_call_main(msg.content.strip()) reply = TextReply(content=res_msg, message=msg) xml = reply.render() return response.text(body=xml, status=200) else: return response.text(body='NaN') else: return response.text(body='NaN')
def reply(self, msg): reply = TextReply(content=MESSAGE_HELLO, message=msg) if msg.type == 'event': reply = TextReply(content=self.hello(), message=msg) elif msg.type == 'text': content = self.record_diet(msg.content, msg.source) reply = TextReply(content=content, message=msg) return reply
def reply_message(self, to_open_message, msg): """ :param to_open_messgae 要回复给访客的消息 :param msg 收到的消息解析后保存在msg """ reply = TextReply(content=to_open_message, message=msg) # 转换成 XML xml = reply.render() return xml
def home(request): if request.method == 'GET': signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce', None) echo_str = request.GET.get('echostr') print(signature, " ", timestamp, " ", nonce) try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: return HttpResponse("hello world") return HttpResponse(echo_str, content_type="text/plain") msg = parse_message(request.body) print(msg.type) if (msg.type == 'text'): reply = TextReply(content="you say:%s" % msg.content, message=msg) xml = reply.render() return HttpResponse(xml) elif (msg.type == 'image'): url = msg.image f = open(path + "/aaa.jpg", 'wb') str1 = urllib.urlopen(url).read() f.write(str1) f.close() image = cv.LoadImage(path + "/aaa.jpg", 1) size = (image.width, image.height) iUD = cv.CreateImage(size, image.depth, image.nChannels) h = image.height w = image.width for i in range(h): for j in range(w): iUD[i, w - j - 1] = image[i, j] cv.WaitKey(0) cv.SaveImage(path + "/bbb.jpg", iUD) json_str = urllib.urlopen( "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % (appID, appsecret)).read().decode("utf-8") access_token = json.loads(json_str)['access_token'] json_str = commands.getoutput( "curl -F media=@%s/bbb.jpg 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=image'" % (path, access_token)) print(json_str) media_id = json_str.split(',')[1].split(':')[1].replace('"', '') print(type(media_id)) print(media_id) print(dir(media_id)) xml = """<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[image]]></MsgType> <Image> <MediaId><![CDATA[%s]]></MediaId> </Image> </xml> """ % (msg.source, msg.target, time.time() + 1, media_id) return HttpResponse(xml)
def weixin(request): if request.method == 'POST': msg = parse_message(request.body) if msg.type == 'text': replay = TextReply(content=msg.content, message=msg) return HttpResponse(replay.render()) return HttpResponse(TextReply(content="hah")) elif request.method == 'GET': print(request.GET) return HttpResponse(request.GET.get('echostr', default='110'))
def Reply_text(msg, reply_text): """ 用于回复文本数据 :param msg: :param reply_text: :return: """ reply_data = TextReply(content=reply_text, message=msg) reply_xml = reply_data.render() return reply_xml
async def postWechat(request: Request, user_agent: Optional[str] = Header(None)): headers = {'CONTENT_TYPE': 'text/html'} __data = await request.body() __msg = parse_message(__data) if __msg.type == 'text': __p = re.compile('doge') if __p.match(__msg.content) != None: __reply = TextReply(content=__topDoge.run(), message=__msg) __xml = __reply.render() #return __xml #return Response(content=__xml, headers=headers) #articles = [ # { # 'title': 'test', # 'description': 'test \n second line \n description', # 'image': 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png', # 'url': 'https://www.yahoo.co.jp' # } #] #__reply = TextReply(content=__msg.content, message=__msg) #__reply = create_reply(articles, __msg) else: __reply = TextReply( content="I don't know what are you talking about.", message=__msg) __xml = __reply.render() else: __reply = TextReply(content="I don't know what are you talking about.", message=__msg) __xml = __reply.render() return Response(content=__xml, headers=headers)
def reply_message(self, message, content): """ 回复公众号消息 """ reply = TextReply() reply.target = message.FromUserName reply.source = message.ToUserName reply.content = content xml_str = reply.render() headers = {'CONTENT_TYPE': self.request.META['CONTENT_TYPE']} return Response(xml_str, headers=headers)
def 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 responMsg(self, pstr, xml): #signature=pstr["signature"][0] #nonce=pstr["nonce"][0] #timestam=pstr["timestamp"][0] msg = parse_message(xml) reply = TextReply(message=msg) reply.content = '你好啊,扑街!' restr = reply.render() bstr = bytes(restr, encoding='utf-8') returncode = bytes(str(bstr, encoding='utf-8').replace('\n', ''), encoding='utf-8') #self.wfile.write(returncode) print(returncode) return returncode
def get_send_msg(self, message): content = message.content + 'hello slient.' json_data = { 'key': '23bef26bd5424f2d80428a6c2cf2867b', 'info': message.content, 'loc': u'上海嘉定区', 'userid': message.source, } r = requests.post(TULINGURL, data=json.dumps(json_data)) try: data = r.json() context = data['text'] except KeyError: context = content reply = TextReply(content=context, message=message) return reply.render()
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 test_reply_init_ok(self): timestamp = int(time.time()) reply = TextReply(source='user1', target='user2') self.assertEqual('user1', reply.source) self.assertEqual('user2', reply.target) self.assertTrue(timestamp <= reply.time)
def test_reply_render(self): timestamp = int(time.time()) reply = TextReply(source='user1', target='user2', time=timestamp, content='test') r = reply.render() self.assertTrue(r.startswith('<xml>\n')) self.assertTrue(r.endswith('\n</xml>')) self.assertTrue('<ToUserName><![CDATA[user2]]></ToUserName>' in r) self.assertTrue('<FromUserName><![CDATA[user1]]></FromUserName>' in r) self.assertTrue('<MsgType><![CDATA[text]]></MsgType>' in r) self.assertTrue('<Content><![CDATA[test]]></Content>' in r) create_time = '<CreateTime>{time}</CreateTime>'.format(time=timestamp) self.assertTrue(create_time in r)
def time_out_reply(event): event = re.sub(r'\<xml\>', '<xml>\n', event) xml = event msg = parse_message(xml) reply = TextReply(content='【系统已激活,请再次提问】', message=msg) resp = apiReply(reply, txt=True, content_type="application/xml") return resp
def test_reply_render(self): timestamp = int(time.time()) reply = TextReply(source="user1", target="user2", time=timestamp, content="test") r = reply.render() self.assertTrue(r.startswith("<xml>\n")) self.assertTrue(r.endswith("\n</xml>")) self.assertTrue("<ToUserName><![CDATA[user2]]></ToUserName>" in r) self.assertTrue("<FromUserName><![CDATA[user1]]></FromUserName>" in r) self.assertTrue("<MsgType><![CDATA[text]]></MsgType>" in r) self.assertTrue("<Content><![CDATA[test]]></Content>" in r) create_time = "<CreateTime>{time}</CreateTime>".format(time=timestamp) self.assertTrue(create_time in r)
def textHandle(self, user='', master='', time='', content=''): template = """ <xml> <ToUserName><![CDATA[{}]]></ToUserName> <FromUserName><![CDATA[{}]]></FromUserName> <CreateTime>{}</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[{}]]></Content> </xml> """ # 对用户发过来的数据进行解析,并执行不同的路径 try: response = get_response_by_keyword(self.msg.content) if response['type'] == "image": result = self.imageHandle(response['content']) elif response['type'] == "music": data = response['content'] result = self.musicHandle(data['title'], data['description'], data['url'], data['hqurl']) elif response['type'] == "news": items = response['content'] result = self.newsHandle(items) # 这里还可以添加更多的拓展内容 else: CYB = MyCybex() RecMsg = self.msg.content.split(" ") if len(RecMsg)==1: responseCYB = CYB.GetAccountBalanceByName(RecMsg[0],'CYB') if responseCYB != 'Error': responseETH = CYB.GetAccountBalanceByName(RecMsg[0],'ETH') responseUSDT = CYB.GetAccountBalanceByName(RecMsg[0],'USDT') responseBTC = CYB.GetAccountBalanceByName(RecMsg[0],'BTC') result = TextReply(content="该账户有:\n"+str(responseCYB)+'CYB\n'+str(responseETH)+'ETH\n'+str(responseUSDT)+'USDT\n'+str(responseBTC)+'BTC', message=self.msg) else: result = TextReply(content="目前支持的命令有:大户持仓排行(十天更新一次)。或者输入账号,查询账户资产信息(crypto-vault CYB)", message=self.msg) elif len(RecMsg)==2: response = CYB.GetAccountBalanceByName(RecMsg[0],RecMsg[1].upper()) if response != 'Error': result = TextReply(content="该账户有:\n"+str(response)+RecMsg[1].upper(),message = self.msg) else: result = TextReply(content="请输入正确的账号和资产", message=self.msg) else: result = TextReply(content="目前支持的命令有:大户持仓排行(十天更新一次)。或者输入账号,查询账户资产信息(crypto-vault CYB)", message=self.msg) except Exception as e: with open("./debug.log", 'a') as f: f.write("text handler:"+str(e)) f.close() return result
def welcome_article(msg): """新关注用户发送介绍图文 """ # msg_openid = msg.source content = u""" Hi,朋友,很高兴认识你! 如果你是拼拼网的老朋友,<a href="http://mp.weixin.qq.com/s?__biz=MzI3MjM5MTI2MA==&mid=100000015&idx=1&sn=311cb4a695d5964399b6b1d2d6f798bb#rd">绑定账号</a>即可随时查看拼团动态。 如果你是拼拼网的新朋友,不妨看看<a href="http://mp.weixin.qq.com/s?__biz=MzI3MjM5MTI2MA==&mid=100000017&idx=1&sn=bb1b4b2f0468306b92dafb17d3b41acb#rd">拼拼网介绍</a>。 最后,感谢你关注拼拼网微信号,享受每周一推的<a href="http://mp.weixin.qq.com/mp/getmasssendmsg?__biz=MzI3MjM5MTI2MA==#wechat_webview_type=1&wechat_redirect">好货分享</a>吧~ ----PinPin Team """ reply = TextReply(content=content, message=msg) return reply.render()
def echo_server(): error = None if request.method == 'GET': # The WeChat server will issue a GET request in order to verify the chatbot backend server upon configuration. return verify_backend(request) elif request.method == 'POST': # Messages will be POSTed from the WeChat server to the chatbot backend server, message = parse_message(request.data) print(message) if message.type == 'text': reply = TextReply(content=message.content, message=message) elif message.type == 'image': reply = VoiceReply(media_id=message.media_id, message=message) elif message.type == 'voice': reply = VoiceReply(media_id=message.media_id, message=message) return reply.render()
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 custom_business(message): """ :type message: wechat_django.models.WeChatMessageInfo """ user = message.user msg = message.message text = "hello, {0}! we received a {1} message.".format(user, msg.type) return TextReply(content=text.encode())
def wexin(request): """ 所有的消息都会先进入这个函数进行处理,函数包含两个功能, 微信接入验证是GET方法, 微信正常的收发消息是用POST方法。 """ # 这个WEIXIN_TOKEN是在测试号的配置页面中配置的,等会会讲到 WEIXIN_TOKEN = 'investment' if request.method == "GET": logging.error(request.GET) logging.error('---------------wexin----------------') signature = request.GET.get("signature", None) timestamp = request.GET.get("timestamp", None) nonce = request.GET.get("nonce", None) echostr = request.GET.get("echostr", None) token = WEIXIN_TOKEN tmp_list = [token, timestamp, nonce] tmp_list.sort() tmp_str = "%s%s%s" % tuple(tmp_list) tmp_str = hashlib.sha1(tmp_str).hexdigest() if tmp_str == signature: return HttpResponse(echostr) else: return HttpResponse("error") else: logging.error(request.POST) logging.error('---------------wexin----------------') current_date = datetime.datetime.now() xml = request.body msg = parse_message(xml) content = '' logging.error(msg) if msg.type == 'event': pass if msg.type == 'text' or msg.type == 'voice': # 如何处理,自行处理,回复一段文本或者图文 content = '感谢您的反馈,小编将在48小时内给您回复!' reply = TextReply(content=content, message=msg) r_xml = reply.render() return HttpResponse(r_xml) return HttpResponse('success')
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 test_reply_render(self): timestamp = int(time.time()) reply = TextReply( source='user1', target='user2', time=timestamp, content='test' ) r = reply.render() self.assertTrue(r.startswith('<xml>\n')) self.assertTrue(r.endswith('\n</xml>')) self.assertTrue('<ToUserName><![CDATA[user2]]></ToUserName>' in r) self.assertTrue('<FromUserName><![CDATA[user1]]></FromUserName>' in r) self.assertTrue('<MsgType><![CDATA[text]]></MsgType>' in r) self.assertTrue('<Content><![CDATA[test]]></Content>' in r) create_time = '<CreateTime>{time}</CreateTime>'.format(time=timestamp) self.assertTrue(create_time in r)
def dispose_message(msg): # respond to message if isinstance(msg, BaseEvent): if isinstance(msg, SubscribeEvent): get_logger().info('be subscribed by: ' + msg.source) return TextReply(content=MESSAGES['subscribe'], message=msg) elif isinstance(msg, UnsubscribeEvent): get_logger().info('be unsubscribed by: ' + msg.source) else: get_logger().info('undefined event: ' + msg.event) else: if isinstance(msg, TextMessage): get_logger().info('receive message: ' + msg.content) return TextReply(content=dispose_text_message(msg), message=msg) elif isinstance(msg, VoiceMessage): return TextReply(content=MESSAGES['default'], message=msg) else: return TextReply(content=MESSAGES['default'], message=msg)
def sign_in(msg): """每日签到。 未绑定拼拼网的用户签到无效,并告知绑定方法。 绑定用户,redis中控制每日签到一次 db中纪录签到总天数、连续签到天数 """ # 检查微信号是否绑定了拼拼账号 msg_openid = msg.source msg_user = UserWechat.query.filter_by(wechat_openid=msg_openid).first() if msg_user: user = User.query.get(msg_user.uid) today = arrow.utcnow().to('local') key = USER_SIGN_IN.KEY.format(dayid=today.format('YYYYMMDD')) field = USER_SIGN_IN.FIELD.format(user=user.id) # 检查当日是否已签到 r = RedisApp() rs = r.hgetJson(key, field) if rs: reply = TextReply( content=u'{nickname} , 今天已经签到过了,明天继续加油。'.format(nickname=user.nickname), message=msg) return reply.render() rs = r.hsetJson(key, field, today.timestamp) if rs: # 获取用户签到历史 s = UserSignIn.query.filter_by(uid=user.id).first() if s: s.tot_sign_in_days += 1 last_sign_in_dt = arrow.get( arrow.get(s.last_sign_in_dt).format('YYYYMMDD'), 'YYYYMMDD').timestamp this_sign_in_dt = arrow.get( today.format('YYYYMMDD'), 'YYYYMMDD').timestamp if this_sign_in_dt - last_sign_in_dt == 86400: s.continuous_sign_in_days += 1 else: s.continuous_sign_in_days = 1 s.last_sign_in_dt = today.naive s.save else: s = UserSignIn() s.uid = user.id s.tot_sign_in_days = 1 s.continuous_sign_in_days = 1 s.last_sign_in_dt = today.naive s.save reply = TextReply(content=u'{nickname} ,今天是您和拼拼在一起的第{days}天,第{total_days}天签到,您已经连续签到{continuous_days}天,连续签到会有意外惊喜喔。'.format( nickname=user.nickname, days=user.get_regdays(), total_days=s.tot_sign_in_days, continuous_days=s.continuous_sign_in_days), message=msg) return reply.render() reply = TextReply(content='签到机发生错误,请稍候再试。', message=msg) return reply.render() reply = TextReply(content='你还未关联拼拼网账号,签到无效,科科。', message=msg) return reply.render()
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 test1(request): print('!!!!!!') if request.method == 'GET': signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') echo_str = request.GET.get('echostr') check_signature(TOKEN, signature, timestamp, nonce) print('!!!') return HttpResponse(echo_str) elif request.method == 'POST': body = request.body msg = parse_message(body) print(msg.content) print(msg.source) print(msg.target) rep = TextReply() rep.source = msg.target rep.target = msg.source rep.content = '<a href="http://www.baidu.com">草泥马</a>' repxml = rep.render() return HttpResponse(repxml)
def parse_msg(self, msg): print msg.type print msg if msg.type == "event": content = "" if msg._data.get("Event", "") == "subscribe": content = "1、每日标准上班时间 10:00到19:00;" + \ "2、打卡时间10:03之前,之后记为迟到;" + \ "3、每月3次以内(含3次)迟到10:30之内,不做处理," + \ "超出3次,从第四次开始累计罚款20 40 80 160 平方递增," + \ "迟到超过30分钟按照事假2小时处理;" + \ "4、每人每月带薪病事假1天,不可跨月累计," + \ "超出部分病假发放50%工资(1天以上的需要医院假条)" + \ ",事假不发工资;" + \ "5、全勤奖,每月无事假病假,及任何迟到显现可获得全勤奖," + \ "奖品每月更换,平均价值300元;" + \ "6、加班,每日加班超过22:00(需要管理人员在加班单上签字)," + \ "第二天可11:00到岗,周末及节假日加班可累计倒休,抵扣事假,病假。" reply = TextReply(message=msg) reply.content = content elif msg.type == "text": reply = TextReply(message=msg) reply.content = msg._data.get("Content") elif msg.type == "image": reply = ImageReply(message=msg) reply.media_id = msg._data.get("MediaId") elif msg.type == "voice": reply = VoiceReply(message=msg) reply.media_id = msg._data.get("MediaId") pass else: return None re_xml = reply.render() return re_xml
def handleMsg(request): if request.method == 'GET': signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') echo_str = request.GET.get('echostr') check_signature(TOKEN, signature, timestamp, nonce) return HttpResponse(echo_str) elif request.method == 'POST': body = request.body msg = parse_message(body) rep = TextReply() rep.source = msg.target rep.target = msg.source print(msg.type) if msg.type == 'event': if msg.event == 'click': if msg.key == 'change_info': rep.content = '请点击下面的链接修改信息\n<a href="http://59.66.139.224/showinfo?openID= '+ msg.source + '">修改信息</a>' else: rep.content = '<a href="http://learn.tsinghua.edu.cn">草泥马</a>' repxml = rep.render() return HttpResponse(repxml)
def handle_msg(request): if request.method == 'GET': signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') echo_str = request.GET.get('echostr') check_signature(TOKEN, signature, timestamp, nonce) return HttpResponse(echo_str) elif request.method == 'POST': body = request.body msg = parse_message(body) rep = TextReply() rep.source = msg.target rep.target = msg.source if msg.type == 'event': if msg.event == 'click': print(msg.key) if msg.key == 'sports_advice': rep.content = recommend_plan(msg.source) elif msg.key == 'view_info': rep.content = get_info(msg.source) elif msg.key == 'add_test': rep.content = add_test(msg.source) elif msg.key == 'show_today': rep.content = get_datatoday(msg.source) elif msg.event == 'subscribe': rep.content = create_newuser(msg.source) else: rep.content = '!!!' else: rep.content = '<a href="http://learn.tsinghua.edu.cn">你好</a>' repxml = rep.render() return HttpResponse(repxml)
def 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 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 weixin(): if request.method == 'GET': _g = lambda k: request.args.get(k) try: print(TOKEN, _g('signature'), _g('timestamp'), _g('nonce')) check_signature(TOKEN, _g('signature'), _g('timestamp'), _g('nonce')) return _g('echostr') except InvalidSignatureException: pass elif request.method == 'POST': msg = parse_message(request.data) if isinstance(msg, ClickEvent): ev = msg if ev.key == WX_BTN_BIND_BX: reply = TextReply() reply.source = ev.target reply.target = ev.source reply.content = '请访问以下链接登陆到BX邮箱\n%s' % ( '%s?%s' % (urljoin(DOMAIN, 'mslogin'), urlencode({'wx': ev.source})) ) return reply.render() elif ev.key == WX_BTN_BEGIN_CHECKIN: reply = TextReply() reply.source = msg.target reply.target = msg.source reply.content = '请访问以下链接选择开始哪个会议\n%s' % ( '%s/check-in-meetings?openid=%s' % (DOMAIN, msg.source) ) return reply.render() else: reply = TextReply() reply.source = msg.target reply.target = msg.source reply.content = '哦' return reply.render() elif isinstance(msg, TextMessage): if msg.content.lower().startswith('e'): reply = TextReply() reply.source = msg.target reply.target = msg.source reply.content = '请访问以下链接选择开始哪个会议\n%s' % ( '%s/check-in-meetings?openid=%s' % (DOMAIN, msg.source) ) return reply.render() else: return '哦' elif isinstance(msg, ScanEvent) or isinstance(msg, SubscribeScanEvent): openid = msg.source meetingid = msg.scene_id meeting = mongo.db.meeting.find_one({'meetingid': meetingid}) checkin_time, ps = emit_checked_in(openid=openid, meeting=meeting) r = check_in(openid=openid, meetingid=meetingid, punish_str=ps, checkin_time=checkin_time) meeting = mongo.db.meeting.find_one({'meetingid': meetingid}) print(meeting) if all_attendees_checked(meeting['attendee']): s = '签到汇总\n%s' ra = [] for u in meeting['attendee']: print(u) full_u = mongo.db.users.find_one({'openid': u['openid']}) ra.append([full_u['outlook']['name'], u['punish_str']]) s %= '\n'.join(map(lambda ss: ': '.join(ss), ra)) tmp = list(map(lambda u: u['openid'], meeting['attendee'])) tmp.append(meeting['organizer']['openid']) if len(tmp) > 1: wx.message.send_mass_text(tmp, s, is_to_all=True) else: wx.message.send_text(tmp[0], s) # return r wx.message.send_text(openid, r) reply = TextReply() reply.source = msg.target reply.target = msg.source reply.content = '请访问以下链接选择查看签到状况\n%s' % ( '%s/check-in-members?meetingid=%s' % (DOMAIN, meetingid) ) return reply.render()