def sub_event(msg): reply = TextReply(message=msg) new_uid = reply.target if views.check_band_user(new_uid) == False: views.insert_band_user(new_uid) return HttpResponse(create_reply("太平洋手环保太平,欢迎您使用太平洋手环!", message=msg)) else: return HttpResponse(create_reply("欢迎您重归太平洋手环!", message=msg))
def handle(self, message): if not self.check_match(message): return parts = message.content.strip().split() if len(parts) == 1 or len(parts) > 2: return create_reply('IP地址无效', message) ip = parts[1] pattern = r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$' if not re.match(pattern, ip): return create_reply('IP地址无效', message) result = self.q.lookup(ip) if result is None: return create_reply('未找到', message) else: return create_reply(result[0], message)
def unsubEvent(msg): # try: # user = User.objects.get(openId=msg.source) # user.delete() # except: # user = None return HttpResponse(create_reply(u"Hello World!I am 用户取关事件", message=msg))
def subEvent(msg): data = tools.client.user.get(msg.source) try: username = data["nickname"] users = User.objects.filter(openId=msg.source) if len(users) > 0: user = users[0] else: user = User(name=data["nickname"],sex=int(data["sex"]),openId=msg.source,comment=u"现在还是空的><") user.save() team = Team(name=basic_tools.teamName(None, username),type=0) team.save() team.members.add(user) user.name = username user.uid = int(random.random() * 100) if "headimgurl" in data: user.image = data["headimgurl"] user.save() date = basic_tools.getDate() #如果DayData不存在,则创建 if DayData.objects.filter(user=user,date=date).count() == 0: dayData = DayData(user=user,date=date) basic_tools.updateDayData(dayData, user) dayData.save() except: username = "" return HttpResponse(create_reply(u"%s!欢迎使用新中韩无敌了的手环公众号!\n%s" % (username, tools.help_text), message=msg))
def wechat(): signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') echo_str = request.args.get('echostr', '') try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': return echo_str else: msg = parse_message(request.data) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return reply.render()
def wechat(): signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') echo_str = request.args.get('echostr', '') 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(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': return echo_str else: print('Raw message: \n%s' % request.data) crypto = WeChatCrypto(TOKEN, EncodingAESKey, AppId) try: msg = crypto.decrypt_message( request.data, msg_signature, timestamp, nonce ) print('Descypted message: \n%s' % msg) except (InvalidSignatureException, InvalidAppIdException): abort(403) msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return crypto.encrypt_message( reply.render(), nonce, timestamp )
def wechat(): signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') encrypt_type = request.args.get('encrypt_type', 'raw') msg_signature = request.args.get('msg_signature', '') try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': echo_str = request.args.get('echostr', '') return echo_str # POST request if encrypt_type == 'raw': # plaintext mode msg = parse_message(request.data) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return reply.render() else: # encryption mode from wechatpy.crypto import WeChatCrypto crypto = WeChatCrypto(TOKEN, AES_KEY, APPID) try: msg = crypto.decrypt_message( request.data, msg_signature, timestamp, nonce ) except (InvalidSignatureException, InvalidAppIdException): abort(403) else: msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return crypto.encrypt_message(reply.render(), nonce, timestamp)
def post(self, request): message = request.data handler_name = self.handlers.get(message.type, '') if callable(handler_name): handler = handler_name else: handler = getattr(self, handler_name, self.message_not_handled) reply = handler(message) result = create_reply(reply, message) return result.render()
def textHandle(msg): if msg.type == "text": textstr = msg.content.encode("utf-8") if ( (textstr == "我是谁") or (textstr == "我是谁?") or (textstr == "我是谁?") or (textstr == "你猜我是谁?") or (textstr == "你猜我是谁?") ): return HttpResponse( create_reply("你是:".decode("utf-8") + "%s" % User.objects.get(openid=msg.source).name, message=msg) ) if textstr == "运动步数": tools.customSendArticle( msg.source, u"运动步数", u"", "https://raw.githubusercontent.com/wmc54321/wrist/hj/%E4%BA%8C%E5%90%88%E4%B8%80/wrist/static/images/sports.png", "http://" + tools.IP + "/" + msg.source + "/steps/", ) return HttpResponse(create_reply("谢谢查询".decode("utf-8"), message=msg)) if textstr == "睡眠状况": tools.customSendArticle( msg.source, u"睡眠状况", u"", "https://raw.githubusercontent.com/wmc54321/wrist/hj/%E4%BA%8C%E5%90%88%E4%B8%80/wrist/static/images/sleep.jpg", "http://" + tools.IP + "/" + msg.source + "/sleep/", ) return HttpResponse(create_reply("谢谢查询".decode("utf-8"), message=msg)) if textstr.find("帮我将签名改为:") == 0: if len(textstr) > 54: return HttpResponse(create_reply("您的签名太长啦> <".decode("utf-8"), message=msg)) else: User.objects.filter(openid=msg.source).update(sign=textstr[24:]) return HttpResponse(create_reply("修改成功".decode("utf-8"), message=msg)) if textstr.find("帮我将签名改为:") == 0: if len(textstr) > 52: return HttpResponse(create_reply("您的签名太长啦> <".decode("utf-8"), message=msg)) else: User.objects.filter(openid=msg.source).update(sign=textstr[22:]) return HttpResponse(create_reply("修改成功".decode("utf-8"), message=msg)) tools.customSendArticle( msg.source, u"或许你要寻求的服务能在这里找到?", u"", "https://raw.githubusercontent.com/wmc54321/wrist/hj/%E4%BA%8C%E5%90%88%E4%B8%80/wrist/static/images/help.png", "http://" + tools.IP + "/handbook/", ) return HttpResponse(create_reply("抱歉,我们找不到您要的服务".decode("utf-8"), message=msg))
def text_handle(request): msg = parse_message(request.body) reply = TextReply(message=msg) content = msg.content new_uid = reply.target if content == "来数据": views.update_database_randomly(new_uid) return HttpResponse(create_reply("注入了数据!", message=msg)) elif content == "xp好帅": views.test2(new_uid) return HttpResponse(create_reply("获得了浇水次数和施肥次数!!", message=msg)) if new_uid in sessions and sessions[new_uid] == 1: if content == "退出": sessions[reply.target] = 0 return HttpResponse(create_reply("生命之树期待与您再次相会", message=msg)) rebot_key = "da0d72f6aacebe4301f685e2c11f22c0" url = "http://www.tuling123.com/openapi/api?key=%s&info=%s" % (rebot_key,urllib.parse.quote(content)) # return HttpResponse(create_reply(u"生命之树期待与您再次相会", message=msg)) response = urllib.request.urlopen(url).read() #调用urllib2向服务器发送get请求url reply_text = json.loads(response.decode("utf-8"))['text'] reply_text.replace('图灵机器人','生命之树') # reply_text.replace(u'图灵机器人'.encode('utf-8'),u'生命之树') return HttpResponse(create_reply(reply_text, message=msg)) if(views.check_band_user(new_uid) == False): views.insert_band_user(new_uid) return HttpResponse(create_reply(u"太平洋手环保太平,欢迎您使用太平洋手环!", message=msg)) else: return HttpResponse(create_reply(u"欢迎您重归太平洋手环!", message=msg))
def click_event(request): reply = TextReply(message = request) if request.key == 'ranklist': #排行榜 t = get_template('ranklist.xml') html = t.render(Context({'to_user': reply.target, 'from_user': reply.source, "create_time": reply.time})) return HttpResponse(html, content_type="application/xml") elif request.key == "talk_with_tree": # request.session["talk_flag"] = True return HttpResponse(create_reply(u"你好,我是你粗大的生命之树。能和你聊聊天真好。\n\n回复‘退出’可退出交谈模式", message=request)) elif request.key == "get_today_mission": i = random.uniform(0, 2) if i < 1: i = 1 else: i = 0 str = "欢迎您领取每日任务。完成每日任务可获得大量肥料与水的奖励。\n\n您今天的任务是【" + mission_detail[i]["description"] + "】" print (str) return HttpResponse(create_reply(str, message=request)) elif request.key == "set_today_mission": print (views.check_today_mission(reply.target)) if views.check_today_mission(reply.target): return HttpResponse(create_reply(u"恭喜您完成了今天的每日任务!您的奖励已到账!", message=request)) else: return HttpResponse(create_reply(u"您的每日任务尚未完成,继续努力吧~", message=request)) elif request.key == "hit_card": if views.check_today_plan(reply.target): return HttpResponse(create_reply(u"本日打卡成功!", message=request)) else: return HttpResponse(create_reply(u"您本日的运动计划尚未完成,继续努力吧!", message=request))
def clickEvent(msg): if msg.key == "V1000_FRIEND": tools.customSendArticle( msg.source, u"好友排行", u"", "https://raw.githubusercontent.com/wmc54321/wrist/hj/%E4%BA%8C%E5%90%88%E4%B8%80/wrist/static/images/rank.jpg", "http://" + tools.IP + "/" + msg.source + "/friend/", ) return HttpResponse(create_reply("谢谢查询".decode("utf-8"), message=msg)) if msg.key == "V1000_HELP": tools.customSendArticle( msg.source, u"产品简介", u"", "https://raw.githubusercontent.com/wmc54321/wrist/hj/%E4%BA%8C%E5%90%88%E4%B8%80/wrist/static/images/help.png", "http://" + tools.IP + "/handbook/", ) return HttpResponse(create_reply("谢谢查询".decode("utf-8"), message=msg)) if msg.key == "V1000_STEP": tools.customSendArticle( msg.source, u"运动步数", u"", "https://raw.githubusercontent.com/wmc54321/wrist/hj/%E4%BA%8C%E5%90%88%E4%B8%80/wrist/static/images/sports.png", "http://" + tools.IP + "/" + msg.source + "/steps/", ) return HttpResponse(create_reply("谢谢查询".decode("utf-8"), message=msg)) if msg.key == "V1000_SLEEP": tools.customSendArticle( msg.source, u"睡眠状况", u"", "https://raw.githubusercontent.com/wmc54321/wrist/hj/%E4%BA%8C%E5%90%88%E4%B8%80/wrist/static/images/sleep.jpg", "http://" + tools.IP + "/" + msg.source + "/sleep/", ) return HttpResponse(create_reply("谢谢查询".decode("utf-8"), message=msg)) return HttpResponse(create_reply(u"Hello World!I am 点击菜单跳转链接事件", message=msg))
def textHandle(msg): tools.customSendText(msg.source, u"我是主动发送的信息") if tools.tmp_media_id: tools.customSendImage(msg.source, None, tools.tmp_media_id) else: tools.tmp_media_id = tools.uploadMedia("image", "test.jpg")["media_id"] tools.customSendImage(msg.source, None, tools.tmp_media_id) #tools.customSendImage(msg.source, "test.jpg") tools.customSendArticle(msg.source, u"我是单条的文章", u"圣光会制裁你的!", "http://image.baidu.com/search/down?tn=download&ipn=dwnl&word=download&ie=utf8&fr=result&url=http%3A%2F%2Fimg1.91.com%2Fuploads%2Fallimg%2F141208%2F723-14120P95G23Q.jpg", "http://www.hearthstone.com.cn/landing") articles = [] articles.append({"title":u"我是多条文章_0", "description":u"过来好好打一架,胆小鬼!", "image":"http://image.baidu.com/search/down?tn=download&ipn=dwnl&word=download&ie=utf8&fr=result&url=http%3A%2F%2Fdynamic-image.yesky.com%2F300x-%2FuploadImages%2F2014%2F014%2F9N1OO1139Y57_big_500.png", "url":"http://www.hearthstone.com.cn/landing"}) articles.append({"title":u"我是多条文章_1", "description":u"信仰圣光吧!", "image":"http://image.baidu.com/search/down?tn=download&ipn=dwnl&word=download&ie=utf8&fr=result&url=http%3A%2F%2Fdb.hs.tuwan.com%2Fcard%2Fpremium%2FEX1_383.png", "url":"http://www.hearthstone.com.cn/landing"}) articles.append({"title":u"我是多条文章_2", "description":u"你~需要我的帮助么", "image":"http://image.baidu.com/search/down?tn=download&ipn=dwnl&word=download&ie=utf8&fr=result&url=http%3A%2F%2Fimg.douxie.com%2Fupload%2Fupload%2F2014%2F02%2F12%2Ftb_52fadff8ed62f.jpg", "url":"http://www.hearthstone.com.cn/landing"}) tools.customSendArticles(msg.source, articles) return HttpResponse(create_reply("Hello World!I am text\nyour openid is:%s" % msg.source, message=msg))
def message_entries(): signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') encrypt_type = request.args.get('encrypt_type', 'raw') msg_signature = request.args.get('msg_signature', '') try: check_signature(Config.TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) # 微信验证 if request.method == 'GET': echo_str = request.args.get('echostr', '') return echo_str # POST request if encrypt_type == 'raw': # plaintext mode msg = parse_message(request.data) # 事件处理 if msg.type == 'event': # 关注事件 if msg.event == 'subscribe': mfc = MenuFunc(msg.source) mfc.subscribecreatemenu() reply = create_reply(msg.event, msg) elif msg.type == 'text': reply = create_reply(msg.content, msg) elif msg.type == 'image': reply = create_reply('对不起,暂时不支持图片消息', msg) else: reply = create_reply(msg.type, msg) return reply.render() else: # encryption mode from wechatpy.crypto import WeChatCrypto crypto = WeChatCrypto(Config.TOKEN, Config.AES_KEY, Config.APPID) try: msg = crypto.decrypt_message( request.data, msg_signature, timestamp, nonce ) except (InvalidSignatureException, InvalidAppIdException): abort(403) else: msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return crypto.encrypt_message(reply.render(), nonce, timestamp)
def tuling(msg): query_params = { 'key': '8519004c8bd2dcad54b7c097b217f0e7', 'info': msg.content, 'userid': msg.source } url = 'http://www.tuling123.com/openapi/api?%s' % urllib.urlencode( query_params) res = requests.get(url) reply = None if res.status_code == 200: data = res.json() if data.get('code') == 100000: text = data.get('text', '') print text if text.startswith(u'[tuling]'): text = text[8:-1] reply = create_reply(text, msg) return reply
def post(): msg = parse_message(request.data) city = msg.content city_id = city_2_id.get(city) if city_id: req = requests.get("http://t.weather.sojson.com/api/weather/city/" + city_id) data = json.loads(req.text) today = data['data'] tpl = "{} 今天{} {} {} {}" high = today['forecast'][0]['high'] low = today['forecast'][0]['low'] notice = today['forecast'][0]['notice'] ganmao = today['ganmao'] content = tpl.format(city, high, low, notice, ganmao) else: content = "没有找到您想要查找的城市" reply = create_reply(content, msg) return reply.render()
def subEvent(msg): try: User.objects.get(openid=msg.source) except: User.objects.create(openid=msg.source, likenum=0, coins=0, sign="真懒,啥也没留下") tools.updateInfo(msg.source) menu = ( '{"button":[{"type":"click","name":"好友排行","key":"V1000_FRIEND"},' + '{"type":"click","name":"产品简介","key":"V1000_HELP"},' + '{"name":"健康数据","sub_button":[{"type":"click","name":"运动步数","key":"V1000_STEP"},{"type":"click","name":"睡眠状况","key":"V1000_SLEEP"}]}]}' ) tools.menuCreate(menu) tools.customSendArticle( msg.source, u"或许这些能对您有帮助", u"", "https://raw.githubusercontent.com/wmc54321/wrist/hj/%E4%BA%8C%E5%90%88%E4%B8%80/wrist/static/images/help.png", "http://" + tools.IP + "/handbook/", ) return HttpResponse(create_reply(u"感谢您的关注", message=msg))
def wx(request): if request.method == 'GET': print('wx get msg') signature = request.GET.get('signature', '') timestamp = request.GET.get('timestamp', '') nonce = request.GET.get('nonce', '') echostr = request.GET.get('echostr', '') try: check_signature(WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: echostr = 'error' return HttpResponse(echostr, content_type="text/plain") if request.method == 'POST': print('') msg = parse_message(request.body) if msg.type == 'text' or msg.type == 'image' or msg.type == 'voice': reply = '<xml><ToUserName><![CDATA[' + msg.source + ']]></ToUserName><FromUserName><![CDATA[' + msg.target + \ ']]></FromUserName><CreateTime>' + str(create_timestamp()) + '</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>' return HttpResponse(reply, content_type="application/xml") elif msg.type == 'event': subcribe_event = SubscribeEvent(msg) if msg.event == subcribe_event.event: reply_msg = '全球自拍达人都在用的智能共享自拍杆,快来一起玩吧!\n\n' \ '当你自拍手短或拍照没电的时候,正是我挺"伸"而出之时~\n\n' \ '作为一款时尚的共享自拍神器,希望与你一起记录旅游的精彩~' reply = create_reply(reply_msg, msg) openid = msg.source subcribe_save_openid(openid) else: return 'success' else: return 'success' response = HttpResponse(reply.render(), content_type="application/xml") return response else: print('error')
def post(self): signature = self.get_argument('signature', '') timestamp = self.get_argument('timestamp', '') nonce = self.get_argument('nonce', '') try: check_signature(options.token, signature, timestamp, nonce) except InvalidSignatureException: logging.warning("Signature check failed.") return self.set_header("Content-Type", "application/xml;charset=utf-8") body = self.request.body msg = parse_message(body) if not msg: logging.info('Empty message, ignored') return # new bot bot = AI(msg) if msg.type == 'text': if options.debug: logging.info('message type text from %s', msg.source) response = bot.respond(msg.content, msg) reply = create_reply(response, msg, render=True) self.write(reply) if options.debug: logging.info('Replied to %s with "%s"', msg.source, response) elif msg.type == 'location': if options.debug: logging.info('message type location from %s', msg.source) elif msg.type == 'image': if options.debug: logging.info('message type image from %s', msg.source) else: logging.info('message type unknown')
def weixin(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": if Carinfo.objects.filter(car_number=msg.content): car_msg = Carinfo.objects.filter(car_number=msg.content) for p in car_msg: car_state = p.car_state if car_state == 'dj': car_state = "待检测" reply = create_reply(car_state, msg) if car_state == 'jc': car_state = "检测中" reply = create_reply(car_state, msg) if car_state == 'yj': car_state = "检测完毕" reply = create_reply(car_state, msg) else: reply = create_reply('您输入的车辆不存在', msg) elif msg.type == 'image': reply = create_reply('B', msg) elif msg.type == 'voice': reply = create_reply('C', msg) else: reply = create_reply('D', msg) response = HttpResponse(reply.render(), content_type='application/xml') return response else: logger.info('----------------')
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 wechat(): signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') echo_str = request.args.get('echostr', '') encrypt_type = request.args.get('encrypt_type', '') msg_signature = request.args.get('msg_signature', '') try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': return echo_str else: crypto = WeChatCrypto(TOKEN, EncodingAESKey, AppId) try: msg = crypto.decrypt_message( request.data, msg_signature, timestamp, nonce ) except (InvalidSignatureException, InvalidAppIdException): abort(403) msg = parse_message(msg) reply = create_reply(rpl.reply(msg), msg) return crypto.encrypt_message( reply.render(), nonce, timestamp )
def onclick(request, message): _name, action_id = message.key.split(',') action_id = int(action_id) if _name: action = request.env()[_name].sudo().browse(action_id) ret = action.get_wx_reply(message.source) if type(ret) == dict: media = ret media_type = media['media_type'] media_id = media['media_id'] if media_type == 'image': return replies.ImageReply(message=message, media_id=media_id) elif media_type == 'voice': return replies.VoiceReply(message=message, media_id=media_id) elif media_type == 'video': return replies.VideoReply(message=message, media_id=media_id) elif media_type == 'news': entry = request.entry entry.wxclient.send_articles(message.source, media_id) else: return create_reply(ret, message=message)
def reply_text(msg): reply=create_reply('Text:'+msg.content.encode('utf-8'),message=msg) return reply
def news(request): """ 所有的消息都会先进入这个函数进行处理,包含两个功能: 1.微信接入验证是用GET请求; 2.微信收发消息是用POST请求,传输消息类型是xml。 """ TOKEN = 'piatto' # 服务器配置中的token if request.method == 'GET': """ 微信服务器发送GET请求到指定的服务器URL上, GET请求携带参数包括signature、timestamp、nonce、echostr, 服务端程序通过检验signature对请求进行校验。 若确认此次GET请求来自微信服务器,则原样返回echostr参数内容给微信服务器,微信服务器确认后此次接入才会生效。 """ # 接受微信服务器get请求中的参数 # request.GET('x') 如果GET请求中没有参数 x ,会报错。 # request.GET.get('x', None) 如果GET请求中没有参数 x ,会返回 None ,不会报错。 signature = request.GET.get('signature', None) timestamp = request.GET.get('timestamp', None) nonce = request.GET.get('nonce', None) echo_str = request.GET.get('echostr', None) # # 服务器配置中的token # token = TOKEN # # # 把参数放到list中排序后合成一个字符串, # # 再用sha1加密得到新的字符串与微信发来的signature对比,如果相同就返回echostr给服务器,校验通过。 # hash_list = [token, timestamp, nonce] # hash_list.sort() # hash_str = ''.join([x for x in hash_list]) # # 使用sha1加密 # hash_str = hashlib.sha1(hash_str.encode('utf-8')).hexdigest() # if signature == hash_str: # return HttpResponse(echo_str) # else: # return HttpResponse('signature error') try: # check_signature()检查signature是否正确, 若正确则自动返回echostr, 若错误则捕获错误。 check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: echo_str = 'signature error' return HttpResponse(echo_str) else: # 即 request.method == 'POST' """ 微信消息类型是xml, 例: 用户给公众号发送文本消息:我是津巴布韦小将, 在开发者后台,收到公众平台发送的xml 如下: <xml> <ToUserName><![CDATA[公众号]]></ToUserName> <FromUserName><![CDATA[用户号]]></FromUserName> <CreateTime>1460537339</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[我是津巴布韦小将]]></Content> <MsgId>6272960105994287618</MsgId> </xml> CreateTime 是微信公众平台记录用户发送该消息的具体时间 MsgType: 用于标记该xml 是什么类型消息【这里是text类型】,一般用于区别判断 Content: 说明该用户发给公众号的具体内容是【我是津巴布韦小将】 MsgId: 是公众平台为记录识别该消息的一个标记数值, 微信后台系统自动产生 """ # 使用 wechatpy 中的 parse_message 作为解析器,解析微信服务器发送的 XML 消息 weixin_msg = parse_message(request.body) if weixin_msg.type == 'text': # 利用 wechatpy 的 create_reply 进行快速回复 resp = create_reply('文字已收到!', weixin_msg) elif weixin_msg.type == 'image': resp = create_reply('图片已收到!', weixin_msg) elif weixin_msg.type == 'voice': resp = create_reply('语音已收到!', weixin_msg) else: resp = create_reply('无法识别此类型的消息!', weixin_msg) # render() 将python类中的reply渲染为xml post_response = resp.render() return HttpResponse(post_response)
def weixinchat(): signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') encrypt_type = request.args.get('encrypt_type', 'raw') msg_signature = request.args.get('msg_signature', '') try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': echo_str = request.args.get('echostr', '') return echo_str # POST request _help = "1.输入城市名称查询天气。\n 2.输入帮助查询帮助信息. \n 3.输入历史查询历史记录。" msg = parse_message(request.data) if msg.type == 'text': if msg.content in ['历史']: con = sql.connect("weather.db") cur = con.cursor() cur.execute("select city from chaxun where ctime=date('now')") citylist = cur.fetchall() strlist = "s%s%s%s%" % (citylist[0],citylist[1],citylist[2],citylist[3]) reply = create_reply(strlist, msg) elif msg.content in ['帮助']: reply = create_reply(_help, msg) else: con = sql.connect("weather.db") cur = con.cursor() city = request.form['text'] cur.execute("select city from chaxun where ctime=date('now')") citylist = cur.fetchall() i = (city,) try: if i in citylist: a = "" b = "" x = "" y = "" t = (city,) con = sql.connect("weather.db") cur = con.cursor() cur.execute("select * from chaxun where city=? and ctime=date('now')",t) trow = cur.fetchone() con.commit() x = trow[0] y = trow[1] a = trow[2] b = trow[3] starlist = '%s,%s,%s,%s' % (trow[0], trow[1], trow[2], trow[3] reply = create_reply(starlist, msg) else: url = "https://api.seniverse.com/v3/weather/now.json?key=kelsy6uu0gufudjz&" + "location=%s&language=zh-Hans&unit=c" % city r = requests.get(url) dict2 = r.json()['results'] citycloud = dict2[0]['now']['text'] citytem = dict2[0]['now']['temperature'] cityming = dict2[0]['location']['name'] citytime = dict2[0]['last_update'].replace('T',' ')[:10] Tcitytem = citytem +"℃" s_trlist = '%s,%s,%s,%s' % (cityming, citycloud, Tcitytem, citytime) con = sql.connect("weather.db") cur = con.cursor() cur.execute("INSERT INTO chaxun (city,cloud,ctemp,ctime)\ VALUES (?,?,?,?)",(cityming,citycloud,Tcitytem,citytime) ) con.commit() reply = create_reply(s_trlist, msg) except KeyError: return "请重新输入" else: reply = create_reply('对不起无法识别', msg) return reply.render() if __name__ == '__main__': app.run()
def svHandle(msg): return HttpResponse(create_reply(tools.help_text, message=msg))
def select_location_Event(msg): return HttpResponse( create_reply(u"Hello World!I am 弹出地理位置选择器事件", message=msg))
def sc_pushEvent(msg): return HttpResponse(create_reply(u"Hello World!I am 扫码推事件", message=msg))
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)
return fire_raw_content(e, 403) if frappe.request.method == "GET": #frappe.enqueue('wechat.api.create_wechat_menu', app_name=app) return fire_raw_content(echostr) #data = frappe.request.get_data() data = frappe.form_dict.data.decode('utf-8') frappe.logger(__name__).info(_("Received WeChat message {0}").format(data)) # POST request if encrypt_type == 'raw': # plaintext mode msg = parse_message(data) if msg.type == 'text': reply = create_reply(msg.content, msg) else: reply = create_reply( _('Welcome to follow our WeChat Official Accounts'), msg) return fire_raw_content(reply.render(), 200, 'text/xml') else: # encryption mode from wechatpy.crypto import WeChatCrypto AES_KEY = frappe.get_value('Wechat App', app, 'aes_key') APP_ID = frappe.get_value('Wechat App', app, 'app_id') crypto = WeChatCrypto(TOKEN, AES_KEY, APP_ID) try: msg = crypto.decrypt_message(data, msg_signature, timestamp, nonce) except (InvalidSignatureException, InvalidAppIdException), e:
def svHandle(msg): return HttpResponse(create_reply("Hello World!I am short video", message=msg))
def locationHandle(msg): return HttpResponse(create_reply("Hello World!I am location", message=msg))
def clickEvent(msg): return HttpResponse(create_reply(u"Hello World!I am 点击菜单拉取消息事件", message=msg))
def pic_wechat_Event(msg): return HttpResponse(create_reply(u"Hello World!I am 弹出微信相册发图器事件", message=msg))
def pic_photo_Event(msg): return HttpResponse(create_reply(u"Hello World!I am 弹出系统拍照发图事件", message=msg))
def reply_resource(msg,url): reply=create_reply(url,message=msg) return reply
def reply_encode64(msg,txt): reply=create_reply(txt,message=msg) return reply
def Webpage(self): self.TOKEN = self.oTOLL.get('wx_token','') self.AES_KEY = self.oTOLL.get('wx_aeskey', '') self.APPID = self.oTOLL.get('wx_appid', '') signature = self.objHandle.args.get('signature', '') timestamp = self.objHandle.args.get('timestamp', '') nonce = self.objHandle.args.get('nonce', '') encrypt_type = self.objHandle.args.get('encrypt_type', 'raw') msg_signature = self.objHandle.args.get('msg_signature', '') open_id = self.objHandle.args.get('openid', '') try: check_signature(self.TOKEN, signature, timestamp, nonce) except Exception as e: self.wx_log('验证失败:%s'%open_id, '%s' % e) if encrypt_type == 'raw': msg = parse_message(self.objHandle.data) reply=create_reply('该公众号服务器故障,请休息一会再试', msg) return reply.render() return '' if self.objHandle.method == 'GET': echo_str = self.objHandle.args.get('echostr', '') return echo_str #self.wx_log('恭恭敬敬恭恭敬敬', 'aaaaaaaaaaaaaaaa') # POST request if encrypt_type == 'raw': # plaintext mode msg = parse_message(self.objHandle.data) if msg.type == 'text': reply = create_reply(msg.content, msg) elif msg.type == 'event': if msg.event =='scan' or msg.event=='subscribe_scan': if msg.scene_id == 'login_code' or msg.scene_id == 'register_code': MSG = self.wx_code_msg(open_id) reply = create_reply(MSG, msg) else: reply = create_reply('未知事件', msg) else: reply = create_reply('login_code666666', msg) else: reply = create_reply('Sorry, can not handle this for now', msg) return reply.render() else: # encryption mode from wechatpy.crypto import WeChatCrypto crypto = WeChatCrypto(self.TOKEN, self.AES_KEY, self.APPID) try: msg = crypto.decrypt_message( self.objHandle.data, msg_signature, timestamp, nonce ) except Exception as e: self.wx_log('消息解密失败:%s' % open_id, '%s' % e) else: msg = parse_message(msg) if msg.type == 'text': reply = create_reply(msg.content, msg) elif msg.type == 'event': if msg.event == 'scan' or msg.event == 'subscribe_scan': if msg.scene_id == 'login_code' or msg.scene_id == 'register_code': MSG = self.wx_code_msg(open_id) reply = create_reply(MSG, msg) else: reply = create_reply('未知事件', msg) else: reply = create_reply('login_code666666', msg) else: reply = create_reply('Sorry, can not handle this for now11111111', msg) return crypto.encrypt_message(reply.render(), nonce, timestamp)
def pic_wechat_Event(msg): return HttpResponse( create_reply(u"Hello World!I am 弹出微信相册发图器事件", message=msg))
def masssendEvent(msg): return HttpResponse(create_reply(u"Hello World!I am 群发消息发送任务完成事件", message=msg))
def scanEvent(msg): return HttpResponse( create_reply(u"Hello World!I am 已关注用户扫描带参数二维码事件", message=msg))
def pic_photo_album_Event(msg): return HttpResponse( create_reply(u"Hello World!I am 弹出拍照或者相册发图事件", message=msg))
def viewEvent(msg): return HttpResponse(create_reply(u"Hello World!I am 点击菜单跳转链接事件", message=msg))
def locationEvent(msg): return HttpResponse(create_reply(u"Hello World!I am 上报地理位置事件", message=msg))
def templatesendEvent(msg): return HttpResponse(create_reply(u"Hello World!I am 模板消息发送任务完成事件", message=msg))
def textHandle(msg): #生成文本回复 return HttpResponse(create_reply(tools.help_text, message=msg))
def sc_waitEvent(msg): return HttpResponse(create_reply(u"Hello World!I am 扫码推事件且弹出“消息接收中”提示框", message=msg))
def viewEvent(msg): return HttpResponse( create_reply(u"Hello World!I am 点击菜单跳转链接事件", message=msg))
def pic_photo_album_Event(msg): return HttpResponse(create_reply(u"Hello World!I am 弹出拍照或者相册发图事件", message=msg))
def masssendEvent(msg): return HttpResponse( create_reply(u"Hello World!I am 群发消息发送任务完成事件", message=msg))
def select_location_Event(msg): return HttpResponse(create_reply(u"Hello World!I am 弹出地理位置选择器事件", message=msg))
def templatesendEvent(msg): return HttpResponse( create_reply(u"Hello World!I am 模板消息发送任务完成事件", message=msg))
def imageHandle(msg): return HttpResponse(create_reply("Hello World!I am image", message=msg))
def linkHandle(msg): return HttpResponse(create_reply("Hello World!I am link", message=msg))
def sc_waitEvent(msg): return HttpResponse( create_reply(u"Hello World!I am 扫码推事件且弹出“消息接收中”提示框", message=msg))
def doreply_text(msg): ''' 微信文本消息处理 ''' return create_reply('详细咨询请拨打91小保全国统一咨询热线:0755-83234691。', msg)
def pic_photo_Event(msg): return HttpResponse( create_reply(u"Hello World!I am 弹出系统拍照发图事件", message=msg))