def wechattest(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') wechat_instance = WechatBasic(conf = conf) if not wechat_instance.check_signature(signature = signature, timestamp = timestamp, nonce = nonce) : return HttpResponseBadRequest('Verify Failed') else : if request.method == 'GET' : response = request.GET.get('echostr', 'err') else : try: wechat_instance.parse_data(request.body) message = wechat_instance.get_message() wechat_user_openid = wechat_instance.message.source # res = wechat_instance.create_qrcode({ # "expire_seconds": "QR_LIMIT_SCENE", # "action_name": "QR_SCENE", # "action_info": { # "scene": { # "scene_id": 123 # } # } # }) # response = wechat_instance.show_qrcode(res['ticket']) # with open('tmpfile', 'wb') as fd: # for chunk in response.iter_content(1024): # fd.write(chunk) if isinstance(message, ImageMessage) : try: link = WechatQRCode.objects.get(wechat_openid = wechat_user_openid) link.qrcode_url = message.picurl link.save() response = wechat_instance.download_media(message.media_id) # import pdb; pdb.set_trace() # filename = os.path.join(os.path.pardir,'/static/img/' + link.account.account_name + '.jpeg') with open('ILink/static/img/' + link.account.account_name + '.jpeg', 'wb') as fd : for chunk in response.iter_content(1024) : fd.write(chunk) reply_text = '二维码上传成功' except Exception, e: reply_text = '请先绑定帐号\n\n绑定ILink帐号,请使用 - 为分隔符输入帐号密码\n上传个人微信二维码,请直接发送图片' elif isinstance(message, TextMessage) : content = message.content if content.find("-") > -1 : # User varification account, passwd = content.split("-") # Encode account password md5 = hashlib.md5() md5.update(passwd.encode('utf-8')) passwd = md5.hexdigest() # Account validation try: account_for_validation = Account.objects.get(_account_name = account) except Exception, e: reply_text = '绑定ILink帐号,请使用 - 为分隔符输入帐号密码\n上传个人微信二维码,请直接发送图片' # import pdb; pdb.set_trace() if account_for_validation : if account_for_validation.account_passwd == passwd : try: link = WechatQRCode.objects.get(wechat_openid = wechat_user_openid) link.account = account_for_validation reply_text = '重新绑定ILink帐号成功' except Exception, e: newlink = WechatQRCode.create(account = account_for_validation, openid=wechat_user_openid) newlink.save() reply_text = '绑定ILink帐号成功' else : reply_text = '绑定ILink帐号验证失败' else :
def wechattest(request): signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') wechat_instance = WechatBasic(conf=conf) if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': response = request.GET.get('echostr', 'err') else: try: wechat_instance.parse_data(request.body) message = wechat_instance.get_message() wechat_user_openid = wechat_instance.message.source # res = wechat_instance.create_qrcode({ # "expire_seconds": "QR_LIMIT_SCENE", # "action_name": "QR_SCENE", # "action_info": { # "scene": { # "scene_id": 123 # } # } # }) # response = wechat_instance.show_qrcode(res['ticket']) # with open('tmpfile', 'wb') as fd: # for chunk in response.iter_content(1024): # fd.write(chunk) if isinstance(message, ImageMessage): try: link = WechatQRCode.objects.get( wechat_openid=wechat_user_openid) link.qrcode_url = message.picurl link.save() response = wechat_instance.download_media( message.media_id) # import pdb; pdb.set_trace() # filename = os.path.join(os.path.pardir,'/static/img/' + link.account.account_name + '.jpeg') with open( 'ILink/static/img/' + link.account.account_name + '.jpeg', 'wb') as fd: for chunk in response.iter_content(1024): fd.write(chunk) reply_text = '二维码上传成功' except Exception, e: reply_text = '请先绑定帐号\n\n绑定ILink帐号,请使用 - 为分隔符输入帐号密码\n上传个人微信二维码,请直接发送图片' elif isinstance(message, TextMessage): content = message.content if content.find("-") > -1: # User varification account, passwd = content.split("-") # Encode account password md5 = hashlib.md5() md5.update(passwd.encode('utf-8')) passwd = md5.hexdigest() # Account validation try: account_for_validation = Account.objects.get( _account_name=account) except Exception, e: reply_text = '绑定ILink帐号,请使用 - 为分隔符输入帐号密码\n上传个人微信二维码,请直接发送图片' # import pdb; pdb.set_trace() if account_for_validation: if account_for_validation.account_passwd == passwd: try: link = WechatQRCode.objects.get( wechat_openid=wechat_user_openid) link.account = account_for_validation reply_text = '重新绑定ILink帐号成功' except Exception, e: newlink = WechatQRCode.create( account=account_for_validation, openid=wechat_user_openid) newlink.save() reply_text = '绑定ILink帐号成功' else: reply_text = '绑定ILink帐号验证失败' else:
class Server: def __init__(self, ip='0.0.0.0', port=9000, log_level=logging.DEBUG): self.ip = ip self.port = port self.author = __author__ self.version = __version__ self.file_path = os.path.realpath(__file__) self.dir_path = os.path.dirname(self.file_path) # mark system start time self.system_initialized = datetime.now() # weixin about self.appid = 'wxb1efccbbb5bafcbb' self.appsecret = '9d64356f48062e46159b4d179dea5c44' self.token = 'shenhailuanma' self.access_token = '' self.signature = None self.echostr = None self.timestamp = None self.nonce = None self.wechat = WechatBasic(token=self.token, appid=self.appid, appsecret=self.appsecret) self.weather = weather() # database self.database = Database() # set the logger self.log_level = logging.DEBUG self.log_path = 'myWeixinServer.log' self.logger = logging.getLogger('myWeixinServer') self.logger.setLevel(self.log_level) # create a handler for write the log to file. fh = logging.FileHandler(self.log_path) fh.setLevel(self.log_level) # create a handler for print the log info on console. ch = logging.StreamHandler() ch.setLevel(self.log_level) # set the log format formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) # add the handlers to logger self.logger.addHandler(fh) self.logger.addHandler(ch) self.logger.info('init over.') ####### web test ###### @bottle.route('/') def index_get(): try: # get the post data self.logger.debug('handle a GET request: /, ') # e.g : /?signature=04d39d841082682dc7623945528d8086cc9ece97&echostr=8242236714827861439×tamp=1440564411&nonce=2061393952 # get the data self.logger.debug('handle the request data: %s' %(bottle.request.query_string)) #self.logger.debug('handle the request signature:%s' %(bottle.request.query.signature)) #self.logger.debug('handle the request echostr:%s' %(bottle.request.query.echostr)) #self.logger.debug('handle the request timestamp:%s' %(bottle.request.query.timestamp)) #self.logger.debug('handle the request nonce:%s' %(bottle.request.query.nonce)) return bottle.request.query.echostr except Exception,ex: return "%s" %(ex) return "Hello, this is myWeixinServer." @bottle.route('/', method="POST") def index_post(): try: response = '' self.logger.debug('handle a POST request: /, ') self.logger.debug('handle the request data: %s' %(bottle.request.query_string)) post_data = bottle.request.body.getvalue() self.logger.debug('handle the request post data: %s' %(post_data)) echostr = bottle.request.query.echostr signature = bottle.request.query.signature timestamp = bottle.request.query.timestamp nonce = bottle.request.query.nonce if self.wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce): self.logger.debug('check_signature ok.') self.wechat.parse_data(post_data) message = self.wechat.get_message() if message.type == 'text': if message.content == 'wechat': response = self.wechat.response_text(u'^_^') elif u'天气' in message.content: city = u'北京' data = self.database.get_weather_data(city) self.logger.debug('get the weather response:{0}'.format(data)) response = self.wechat.response_text(data) else: response = self.wechat.response_text(u'文字') elif message.type == 'image': response = self.wechat.response_text(u'图片') elif message.type == 'video': self.logger.debug('message.media_id:%s' %(message.media_id)) response = self.wechat.download_media(message.media_id) self.logger.debug('message.media_id:%s over' %(message.media_id)) #response = self.wechat.response_text(u'视频') elif message.type == 'voice': response = self.wechat.response_text(u'音频') elif message.type == 'location': response = self.wechat.response_text(u'位置') else: response = self.wechat.response_text(u'未知') return response except Exception,ex: self.logger.debug('error:%s' %(ex)) return "%s" %(ex)
class Wpichandler(BaseHandler): conf = '' wechat = '' def __init__(self): self.conf = Wconf.conf self.wechat = WechatBasic(conf=self.conf) def getfromwechat(self, media_ids, names): ''' Args: media_ids: 图片的media_id数组 names: 图片的名字数组 Returns: null ''' #media_ids = json.loads(media_ids) #names = json.loads(names) for media_id, name in zip(media_ids, names): print media_id response = self.wechat.download_media(media_id=media_id) with open('./{address}'.format(address=name), 'wb') as fd: for chunk in response.iter_content(1024): fd.write(chunk) def upload(self, names): ''' Args: names:图片的media数组 Returns:所有图片上传成功时,返回True,否则为False ''' auth = AuthKeyHandler() #names = json.loads(names) bucket_name = 'shacus' q = Auth(auth.access_key, auth.secret_key) for name in names: token = q.upload_token(bucket_name, name, 345600) localfile = './{address}'.format(address=name) ret, info = put_file(token, name, localfile) if info.status_code != 200: return False return True def pichandler(self, media_ids, names): ''' Args: media_ids: 图片的media_id数组 names: 图片的名字数组 Returns:所有图片上传成功时,返回True,否则为False ''' self.getfromwechat(media_ids=media_ids, names=names) if self.upload(names=names): #names = json.loads(names) for name in names: filename = '{mulu}/{address}'.format(address=name, mulu=sys.path[0]) if os.path.exists(filename): os.remove(filename) return True
def wechat_home(request): global confPath cp = ConfigParser.SafeConfigParser() #读取配置文件 cp.read('/home/pi/watchdog/Face/Face_Project/data/face.conf') time_switch = int(cp.get('settings', 'time')) temp_switch = int(cp.get('settings', 'temp')) ONF = int(cp.get('settings', 'onf')) Face = int(cp.get('settings', 'face')) sheel = int(cp.get('settings', 'sheel')) signature = request.GET.get('signature') timestamp = request.GET.get('timestamp') nonce = request.GET.get('nonce') global wechat_instance wechat_instance = WechatBasic(conf=conf) if not wechat_instance.check_signature( signature=signature, timestamp=timestamp, nonce=nonce): return HttpResponseBadRequest('Verify Failed') else: if request.method == 'GET': response = request.GET.get('echostr', 'error') else: try: wechat_instance.parse_data(request.body) message = wechat_instance.get_message() #自定义菜单 menu = { 'button': [{ 'name': 'PI', 'sub_button': [{ 'type': 'click', 'name': '时间', 'key': 'PI_TIME' }, { 'type': 'click', 'name': '温度', 'key': 'PI_TEMP' }, { 'type': 'click', 'name': '关闭警报', 'key': 'RED' }, { 'type': 'click', 'name': '帮助', 'key': 'PI_HELP' }, { 'type': 'view', 'name': 'Github', 'url': 'http://github.com' }] }, { 'name': 'Face', 'sub_button': [{ 'type': 'click', 'name': '导入人脸', 'key': 'Face_import' }, { 'type': 'click', 'name': '添加信息', 'key': 'Face_data' }, { 'type': 'click', 'name': '显示细节', 'key': 'Face_small' }, { 'type': 'click', 'name': '拍照', 'key': 'Face_camera' }] }, { 'name': 'settings', 'sub_button': [{ 'type': 'click', 'name': '开关', 'key': 'OFF' }, { 'type': 'click', 'name': '严格模式', 'key': 'SSS' }, { 'type': 'click', 'name': '普通模式', 'key': 'S' }, { 'type': 'click', 'name': '查看日志', 'key': 'LOG' }, { 'type': 'click', 'name': '开启sheel', 'key': 'Sheel' }] }] } wechat_instance.create_menu(menu) if isinstance(message, TextMessage): countent = message.content.strip() if countent == '全灭': new_botton.restart() reply_text = 'OK' elif countent == 'ip' or countent == 'IP': reply_text = IP elif countent == 'test': img = open( '/home/pi/watchdog/Face/Face_Project/data/unknow/q.jpg' ) data = wechat_instance.upload_media( 'image', img, 'jpg') img.close() img_id = data['media_id'] elif 'name:' in countent: name = countent.split(':') name = name[1] data = open( '/home/pi/watchdog/Face/Face_Project/data/face_data.log', 'w') data.write(name) data.close() reply_text = '信息导入成功' else: if sheel == 1: if countent == 'vim' or 'rm' in countent: reply_text == '警告!,禁止执行!' else: (status, output) = commands.getstatusoutput( '{cmd}'.format(cmd=countent)) reply_text = output else: reply_text = countent elif isinstance(message, VoiceMessage): reply_text = 'voice' elif isinstance(message, ImageMessage): picurl = message.picurl media_id = message.media_id if Face == 0: f = open( '/home/pi/watchdog/Face/Face_Project/data/face_data.log' ) result = f.readlines() f.close() if result == []: reply_text = '还没有导入人脸信息' else: response = wechat_instance.download_media(media_id) ra = random.randint(2, 99) if ra % 100 < 10: img_path = '/home/pi/watchdog/Face/Face_Project/data/image/' + '10000000000' + str( ra) + '.' + str(result[0]) + '.' + 'jpg' elif ra % 100 > 10: img_path = '/home/pi/watchdog/Face/Face_Project/data/image/' + '1000000000' + str( ra) + '.' + str(result[0]) + '.' + 'jpg' with open(img_path, 'wb') as fd: for chunk in response.iter_content(1024): fd.write(chunk) os.remove( '/home/pi/watchdog/Face/Face_Project/data/face_data.log' ) os.mknod( '/home/pi/watchdog/Face/Face_Project/data/face_data.log' ) importFace.main() reply_text = '导入成功' elif Face == 1: response = wechat_instance.download_media(media_id) img_path = '/home/pi/watchdog/Face/Face_Project/data/details/img.jpg' with open(img_path, 'wb') as fd: for chunk in response.iter_content(1024): fd.write(chunk) pi_face_landmark(img_path) img = open(img_path) data = wechat_instance.upload_media( 'image', img, 'jpg') img.close() media_id = data['media_id'] user_id = 'opL4ZwSzQPdCcefPKYo_LR0ImjhI' wechat_instance.send_image_message(user_id, media_id) elif isinstance(message, LinkMessage): reply_text = 'link' elif isinstance(message, LocationMessage): reply_text = 'location' elif isinstance(message, VideoMessage): reply_text = 'video' elif isinstance(message, ShortVideoMessage): reply_text = 'shortvideo' elif isinstance(message, EventMessage): if message.type == 'click': if message.key == 'PI_TIME': localtime = time.asctime( time.localtime(time.time())) reply_text = '时间:' + str(localtime) cp.set('settings', 'time', '1') cp.set('settings', 'temp', '0') fh = open(confPath, 'w') cp.write(fh) fh.close() elif message.key == 'RED': SAKS.ledrow.set_row([ None, None, None, None, None, None, False, False ]) cp.set('settings', 'red', '0') fh = open(confPath, 'w') cp.write(fh) fh.close() elif message.key == 'PI_TEMP': cpu_temp = new_botton.get_cpu_temp() gpu_temp = new_botton.get_gpu_temp() t = SAKS.ds18b20.temperature if str(t) == '-128.0': reply_text = 'cpu温度:' + str(cpu_temp) + '\n' + \ 'gpu温度:' + str(gpu_temp) + '\n' + \ '室温:' + '获取失败,请稍后再试' else: reply_text = 'cpu温度:' + str(cpu_temp) + '\n' + \ 'gpu温度:' + str(gpu_temp) + '\n' + \ '室温:' + str(t) cp.set('settings', 'temp', '1') cp.set('settings', 'time', '0') fh = open(confPath, 'w') cp.write(fh) fh.close() elif message.key == 'Face_camera': result = ScreenFetch() if result == True: screen_img = open( '/home/pi/watchdog/Face/Face_Project/data/screenfetch/screenfetch.jpg' ) data = wechat_instance.upload_media( 'image', screen_img, 'jpg') screen_img.close() img_id = data['media_id'] else: reply_text = '拍照失败' elif message.key == 'Face_import': cp.set('settings', 'face', '0') fh = open(confPath, 'w') cp.write(fh) fh.close() reply_text = '已设置导入人脸模式' elif message.key == 'Face_data': reply_text = '请输入名称:(格式如name:test)' elif message.key == 'Face_small': reply_text = '已设置显示人脸细节' cp.set('settings', 'face', '1') fh = open(confPath, 'w') cp.write(fh) fh.close() elif message.key == 'S': reply_text = '普通模式已开启' cp.set('settings', 'mode', 'normal') fh = open(confPath, 'w') cp.write(fh) fh.close() elif message.key == 'SSS': reply_text = '严格模式已开启' cp.set('settings', 'mode', 'strict') fh = open(confPath, 'w') cp.write(fh) fh.close() elif message.key == 'OFF': if ONF == 1: reply_text = '正在关闭' cp.set('settings', 'ONF', '0') fh = open(confPath, 'w') cp.write(fh) fh.close() elif ONF == 0: reply_text = '正在开启' cp.set('settings', 'ONF', '1') fh = open(confPath, 'w') cp.write(fh) fh.close() elif message.key == 'LOG': log = open( '/home/pi/watchdog/Face/Face_Project/data/log/out.log' ) txt = log.readlines() log.close() reply_text = txt elif message.key == 'Sheel': if sheel == 1: reply_text = '已关闭sheel' cp.set('settings', 'sheel', '0') s = open(confPath, 'w') cp.write(s) s.close() if sheel == 0: reply_text = '已开启sheel' cp.set('settings', 'sheel', '1') s = open(confPath, 'w') cp.write(s) s.close() else: reply_text = 'other' try: response = wechat_instance.response_text( content=reply_text) except UnboundLocalError: pass try: response = wechat_instance.response_image(img_id) except UnboundLocalError: pass except ParseError: return HttpResponseBadRequest('Invalid XML Data') return HttpResponse(response, content_type="application/xml")