def router_getins(): ''' 路由器轮询获取指令 ''' form = request.form if not 'token' in form or not 'routerid' in form or not 'routerkey' in form: return 'errror' token = form['token'] routerid = form['routerid'] routerkey = form['routerkey'] if token != 'djqoidjqoq12e941nqdqnfhoho-==': return 'error' from model.redisdb import RedisDB con = RedisDB().con if con.get('routerid2key:%s'%routerid) != routerkey: return 'error' try: f = open('tmp/router/%s/ins.json'%routerid,'r') data = f.read() f.close() except: data = '{"ins":[]}' f = open('tmp/router/%s/ins.json'%routerid,'w') f.write('{"ins":[]}') f.close() return data
def cancelbind(): args = request.args openid = args['openid'] from model.redisdb import RedisDB con = RedisDB().con con.delete('WECHAT_BIND:'+openid) return jsonify(res="ok")
def router_register(): ''' 路由器注册 ''' form = request.form if not 'token' in form: return 'error' token = form['token'] if token != 'djqoidjqoq12e941nqdqnfhoho-==': return 'error' from lib.tools import generate_code routerid = generate_code() from model.redisdb import RedisDB con = RedisDB().con while con.exists('routerid2key:%s'%routerid): routerid = generate_code() routerkey = generate_code() con.set('routerid2key:%s'%routerid, routerkey) import os os.system("mkdir tmp/router/%s"%routerid) os.system("touch tmp/router/%s/ins.json"%routerid) return jsonify(routerid=routerid,routerkey=routerkey)
def setbind(): form = request.form openid = form['openid'] routerid = form['routerid'] from model.redisdb import RedisDB con = RedisDB().con con.set('WECHAT_BIND:'+openid, routerid) return jsonify(res="ok")
def get_status(fromUser): from model.redisdb import RedisDB con = RedisDB().con if con.exists('WECHAT_STATUS:'+fromUser) == False: con.set('WECHAT_STATUS:'+fromUser, 0) return con.get('WECHAT_STATUS:'+fromUser)
def getbind(): args = request.args openid = args['openid'] from model.redisdb import RedisDB con = RedisDB().con if con.exists('WECHAT_BIND:'+openid) == False: return jsonify(num=1, routerid=con.get('WECHAT_BIND:'+openid)) return jsonify(num=0)
def remove_session(session): ''' 删除session ''' from model.redisdb import RedisDB con = RedisDB().con key = 'session2username:'+session con.delete(key)
def generate_session(): import os from model.redisdb import RedisDB con = RedisDB().con code = ''.join(map(lambda xx:(hex(ord(xx))[2:]),os.urandom(16))) while True: if con.sismember('session',code) == False: con.sadd('session',code) break code = ''.join(map(lambda xx:(hex(ord(xx))[2:]),os.urandom(16))) return code
def createcall(): cookies = request.cookies weopenid = cookies["weopenid"] print weopenid form = request.form target = form["target"].encode("utf-8") print target from config import BAIDU_AK para = {"address": target, "output": "json", "ak": BAIDU_AK} import urllib url = "http://api.map.baidu.com/geocoder/v2/?" + urllib.urlencode(para) import requests res = requests.get(url) import json data = json.loads(res.text) location = data["result"]["location"] end_wei = location["lat"] # weidu end_jing = location["lng"] # jingdu from model.redisdb import RedisDB con = RedisDB().con geo = con.get("openid2geo:%s" % weopenid).split(":") start_wei = geo[0] start_jing = geo[1] access_token = con.get("weopenid2uber:%s" % weopenid) url = "https://sandbox-api.uber.com.cn/v1/requests" headers = {"Authorization": "Bearer " + access_token, "Content-Type": "application/json"} para = { "start_latitude": float(start_wei), "start_longitude": float(start_jing), "end_latitude": float(end_wei), "end_longitude": float(end_jing), } import json res = requests.post(url, data=json.dumps(para), headers=headers) data = json.loads(res.text) request_id = data["request_id"] driver = data["driver"] eta = data["eta"] surge_multiplier = data["surge_multiplier"] print request_id, driver, eta, surge_multiplier con.set("openid2requestid:%s" % weopenid, request_id) return jsonify(res="00000")
def get_username_by_session(session): ''' 根据session获得用户名 ''' from model.redisdb import RedisDB con = RedisDB().con key = 'session2username:'+session value = con.get(key) if value != None: con.expire(key, 3600) return value
def add_pinid(pinid, code): from wechat.tools import get_accesstoken_by_code access_token, openid = get_accesstoken_by_code(code) from model.redisdb import RedisDB con = RedisDB().con openidlist = con.get("pinid2openid:%s" % pinid) openidlist = openidlist + ";" + openid con.set("pinid2openid:%s" % pinid, openidlist) return jsonify(res="00000")
def index(pin_id): args = request.args if not "code" in args: return "error" code = args["code"] from model.redisdb import RedisDB con = RedisDB().con target = con.get("pinid2target:%s" % pin_id) time = con.get("pinid2time:%s" % pin_id) num = int(con.get("pinid2num:%s" % pin_id)) return render_template("index.html", target=target, time=time, num=num, pinid=pin_id, code=code)
def save_image(fromUser, picurl, mediaid): status = get_status(fromUser) from model.redisdb import RedisDB con = RedisDB().con routerid = con.get('WECHAT_BIND:'+fromUser) import time now_time = time.time() now_time = time.localtime(now_time) now_time = time.strftime('%Y-%m-%d-%H:%M:%S',now_time) if status == '1': filename = now_time + '.jpg' import os path = os.path.realpath(__file__) path = '/'.join(path.split('/')[:-2]) os.system('wget -O %s/tmp/user/%s/recent/%s "%s" &'%(path, fromUser, filename, picurl)) from model.redisdb import RedisDB con = RedisDB().con num = int(con.get('WECHAT_IMG_NUM:'+fromUser)) con.set('WECHAT_IMG_NUM:'+fromUser, num+1) routerid = con.get('WECHAT_BIND:'+fromUser) if routerid != None: f = open('%s/tmp/router/%s/ins.json'%(path,routerid),'r') text = f.read() if text == '': text = '{"ins":[]}' import json data = json.loads(text) f.close() f = open('%s/tmp/router/%s/ins.json'%(path,routerid),'w') data['ins'].append({'type':'image','wechatid':fromUser,'url':'http://wull.me/user/%s/recent/%s'%(fromUser,filename)}) f.write(json.dumps(data)) f.close() return '' elif status == '201': import os path = os.path.realpath(__file__) path = '/'.join(path.split('/')[:-2]) os.system("mkdir %s/tmp/user/%s"%(path,fromUser)) os.system("mkdir %s/tmp/user/%s/sanguosha"%(path,fromUser)) # os.system("mkdir /root/workplace/TI/tiplayer/image/%s/recent"%fromUser) os.system('wget -O %s/tmp/user/%s/sanguosha/pic.jpg "%s" &'%(path, fromUser, picurl)) from model.redisdb import RedisDB con = RedisDB().con con.set('WECHAT_STATUS:'+fromUser, '202') return u'【step 1/6】发一下姓名过来,如“张三”,支持2~4个字'
def get_accesstoken(): try: from model.redisdb import RedisDB con = RedisDB().con except: from redis import Redis con = Redis('localhost') access_token = con.get('WECHAT_ACCESS_TOKEN') if access_token != None: return access_token from config import APP_KEY, APP_SECRET import requests import urllib, json url = "https://api.weixin.qq.com/cgi-bin/token?" data = { 'grant_type':'client_credential', 'appid':APP_KEY, 'secret':APP_SECRET } res = requests.get(url + urllib.urlencode(data)) res_data = json.loads(res.text) access_token = res_data['access_token'] con.set('WECHAT_ACCESS_TOKEN', access_token) con.expire('WECHAT_ACCESS_TOKEN', 3600) return access_token
def user_login(username, password, session): from model.mysql import MySQL sql = MySQL() cur = sql.cur cur.execute('select id from user where username="******" and password="******"'%(username, password)) res = [] if cur.rowcount == 0: sql.close() return False for item in cur: res.append(item[0]) sql.close() from model.redisdb import RedisDB con = RedisDB().con con.set('session2username:%s'%session, res[0]) return True
def router_admin(): ''' 路由管理 ''' #https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc4d580c3d948f21a&redirect_uri=http%3A%2F%2Fwull.me/router/admin&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect args = request.args if not 'code' in args: return '请用微信打开网页' code = args['code'] from wechat.tool import get_accesstoken_by_code access_token, openid = get_accesstoken_by_code(code) from model.redisdb import RedisDB con = RedisDB().con routerid = con.get('WECHAT_BIND:'+openid) if routerid == None: return render_template("admin_error.html") else: return redirect("http://192.168.1.1:5000")
def user_auth(session, username, password, remember): ''' 验证username和password是否匹配,若是则将sessoin与username关联 若remember为1,则将session放入redis中的记住登录表中 ''' from model.mongodb import MongoDB db = MongoDB().db user = db.user one = user.find_one({'username':username,'password':password}) if one == None: return False from model.redisdb import RedisDB con = RedisDB().con key = 'session2username:'+session con.set(key, username) con.expire(key, 3600) return True
def pininfo(pinid): from model.redisdb import RedisDB con = RedisDB().con openidlist = con.get("pinid2openid:%s" % pinid) target = con.get("pinid2target:%s" % pinid) time = con.get("pinid2time:%s" % pinid) num = int(con.get("pinid2num:%s" % pinid)) idlist = openidlist.split(";") from wechat.tools import get_info_by_openid leader_nickname, leader_headimgurl = get_info_by_openid(idlist[0]) userlist = [{"name": leader_nickname, "headimgurl": leader_headimgurl}] print userlist for item in idlist[1:]: nickname, headimgurl = get_info_by_openid(item) userlist.append({"name": nickname, "headimgurl": headimgurl}) return jsonify(res="00000", leader=leader_nickname, member=userlist)
def bind_success(): args = request.args if not "code" in args: return "error" code = args["code"] cookies = request.cookies if not "wecode" in cookies: return "error" wecode = cookies["wecode"] from wechat.tools import get_accesstoken_by_code we_access_token, openid = get_accesstoken_by_code(wecode) import requests from config import UBER_ID, UBER_SECRET url = "https://login.uber.com.cn/oauth/v2/token" para = { "client_secret": UBER_SECRET, "client_id": UBER_ID, "grant_type": "authorization_code", "redirect_uri": "https://wull.me/bind", "code": code, } res = requests.post(url, data=para) import json data = json.loads(res.text) access_token = data["access_token"] print wecode, access_token from model.redisdb import RedisDB con = RedisDB().con con.set("weopenid2uber:%s" % openid, access_token) con.expire("weopenid2uber:%s" % openid, 3600) return render_template("bind_success.html")
def random_choose_music(): import requests, urllib, json from model.redisdb import RedisDB con = RedisDB().con if con.exists("WECHAT_HOST_SONG") == False: url = "http://tingapi.ting.baidu.com/v1/restserver/ting?" data = { 'from':'qianqian', 'version':'2.1.0', 'method':'baidu.ting.billboard.billList', 'format':'json', 'type':'2', 'offset':'0', 'size':'50' } res = requests.get(url + urllib.urlencode(data)) data = json.loads(res.text) song_list = data['song_list'] song_id_list = [] for item in song_list: song_id = item['song_id'] song_id_list.append(song_id) song_url = 'http://ting.baidu.com/data/music/links?' song_id_str = ','.join(song_id_list) res = requests.get(song_url + urllib.urlencode({'songIds':song_id_str})) data = json.loads(res.text) data = data['data'] songList = data['songList'] result = [] for item in songList: songName = item['songName'] artistName = item['artistName'] showLink = item['showLink'] if 'yinyueshiting.baidu.com' in showLink: result.append(json.dumps({ 'songName':songName, 'artistName':artistName, 'showLink':showLink })) for item in result: con.rpush('WECHAT_HOST_SONG', item) con.expire('WECHAT_HOST_SONG', 7200) from random import randint hotsong = con.lrange("WECHAT_HOST_SONG", 0, -1) length = len(hotsong) num = randint(0, length-1) return json.loads(hotsong[num])
def createpin(): cookies = request.cookies weopenid = cookies["weopenid"] form = request.form target = form["target"] time = form["time"] num = int(form["num"]) from random import randint pin_id = randint(0, 100000) from model.redisdb import RedisDB con = RedisDB().con con.set("pinid2openid:%5d" % pin_id, weopenid) con.set("pinid2target:%5d" % pin_id, target) con.set("pinid2time:%5d" % pin_id, time) con.set("pinid2num:%5d" % pin_id, num) return jsonify(res="00000", pinid=pin_id)
def unbind_user(code): from redisdb import RedisDB con = RedisDB().con con.delete('WECHAT_BIND:'+openid) return userinfo
def w_index(): if request.method == 'GET': try: args = request.args signature = args.get('signature','') timestamp = args.get('timestamp','') nonce = args.get('nonce','') echostr = args.get('echostr') token = 'zengzhaoyang' list = [token,timestamp,nonce] list.sort() sha1 = hashlib.sha1() map(sha1.update,list) hashcode = sha1.hexdigest() if hashcode == signature: return echostr return 'wrong' except: return 'wrong' else: data = request.data re_touser = re.compile('<ToUserName><!\\[CDATA\\[(.*?)\\]\\]></ToUserName>') re_fromuser = re.compile('<FromUserName><!\\[CDATA\\[(.*?)\\]\\]></FromUserName>') re_msgType = re.compile('<MsgType><!\\[CDATA\\[(.*?)\\]\\]></MsgType>') re_content = re.compile('<Content><!\\[CDATA\\[(.*?)\\]\\]></Content>') re_event = re.compile('<Event><!\\[CDATA\\[(.*?)\\]\\]></Event>') re_eventkey = re.compile('<EventKey><!\\[CDATA\\[(.*?)\\]\\]></EventKey>') re_recognition = re.compile('<Recognition><!\\[CDATA\\[(.*?)\\]\\]></Recognition>') re_picurl = re.compile('<PicUrl><!\\[CDATA\\[(.*?)\\]\\]></PicUrl>') re_mediaid = re.compile('<MediaId><!\\[CDATA\\[(.*?)\\]\\]></MediaId>') re_scantype = re.compile('<ScanType><!\\[CDATA\\[(.*?)\\]\\]></ScanType>') re_scanresult = re.compile('<ScanResult><!\\[CDATA\\[(.*?)\\]\\]></ScanResult>') toUser = re_touser.findall(data)[0] fromUser = re_fromuser.findall(data)[0] msgType = re_msgType.findall(data)[0] if msgType == 'event': event = re_event.findall(data)[0] if event == 'subscribe': return reply_text%(fromUser, toUser, int(time.time()), 'hello') elif event == 'unsubscribe': return reply_text%(fromUser, toUser, int(time.time()), 'bye') elif event == 'CLICK': eventKey = re_eventkey.findall(data)[0] if eventKey == 'BUTTON1': from tool import random_choose_music res = random_choose_music() return reply_music%(fromUser, toUser, int(time.time()), res['songName'], res['artistName'], res['showLink'], res['showLink']) elif eventKey == 'BUTTON2': from tool import check_bind if check_bind(fromUser) == False: return reply_text%(fromUser, toUser, int(time.time()), '不好意思,你还没有绑定设备,扫描二维码进行绑定吧') from tool import set_status res = set_status(fromUser, 1) if res == -1: return reply_text%(fromUser, toUser, int(time.time()), '您已进入云备胎状态,现在您发送的图片都会直接同步到小t哦\n再次点击“云备胎”按钮可以退出状态\n三十分钟内没有发送图片的话也会自动退出状态哦') else: if res != 0: import os os.system("python /root/workplace/TI/tiplayer/wechat/w.py %s &"%fromUser) return reply_text%(fromUser, toUser, int(time.time()), '本次您总共同步了%d张照片,谢谢您的使用'%res) elif eventKey == 'BUTTON3': from tool import set_status res = set_status(fromUser, 2) return reply_text%(fromUser, toUser, int(time.time()), '发一张图片过来吧,有惊喜哦') elif event == 'VIEW': eventKey = re_eventkey.findall(data)[0] return '' elif msgType == 'image': picurl = re_picurl.findall(data)[0] mediaid = re_mediaid.findall(data)[0] from tool import save_image res = save_image(fromUser, picurl, mediaid) if res == '': return '' else : return reply_text%(fromUser, toUser, int(time.time()), res) elif msgType == 'text': content = re_content.findall(data)[0] if content == '取消': from tool import set_status set_status(fromUser, 0) return reply_text%(fromUser, toUser, int(time.time()), '回到正常状态') if content == '取消绑定': from tool import cancel_bind cancel_bind(fromUser) return reply_text%(fromUser, toUser, int(time.time()), '取消绑定成功') from tool import check_status status, res = check_status(fromUser, content) if status == 0: return reply_text%(fromUser, toUser, int(time.time()), res) temp = content.split() if temp[0] == '音乐': query = ' '.join(temp[1:]) from tool import get_music showLink = get_music(query) return reply_music%(fromUser, toUser, int(time.time()), query.decode('utf-8'), ' ', showLink, showLink) elif temp[0] == '下载': if len(temp) != 3: return reply_text%(fromUser, toUser, int(time.time()), '请以"下载 文件名 下载地址"的格式输入') filename = temp[1] url = temp[2] # from tool import download_url # download_url(fromUser, filename, url) from model.redisdb import RedisDB con = RedisDB().con routerid = con.get('WECHAT_BIND:'+fromUser) if routerid == None: return reply_text%(fromUser, toUser, int(time.time()), '不好意思,你还没有绑定设备,扫描二维码进行绑定吧') import os path = os.path.realpath(__name__) path = '/'.join(path.split('/')[:-1]) f = open(path + '/tmp/router/%s/ins.json'%routerid,'w') w_dict = { 'ins':[ { "type":"download", "url":url, "filename":filename, "wechatid":fromUser } ] } import json f.write(json.dumps(w_dict)) f.close() return reply_text%(fromUser, toUser, int(time.time()), '您的任务已提交至下载队列,下载完成后我们将会提醒您') #return reply_text%(fromUser, toUser, int(time.time()), content) return "" elif msgType == 'voice': recognition = re_recognition.findall(data)[0] if recognition == '停': from model.redisdb import RedisDB con = RedisDB().con routerid = con.get('WECHAT_BIND:'+fromUser) if routerid != None: import os path = os.path.realpath(__file__) path = '/'.join(path.split('/')[:-2]) f = open('%s/tmp/router/%s/ins.json'%(path,routerid),'r') text = f.read() if text == '': text = '{"ins":[]}' import json data = json.loads(text) f.close() f = open('%s/tmp/router/%s/ins.json'%(path,routerid),'w') data['ins'].append({'type':'stop'}) f.write(json.dumps(data)) f.close() from tool import voice res = voice(recognition) if res[0] == 'text': return reply_text%(fromUser, toUser, int(time.time()), recognition) elif res[0] == 'music': from model.redisdb import RedisDB con = RedisDB().con routerid = con.get('WECHAT_BIND:'+fromUser) if routerid != None: import os path = os.path.realpath(__file__) path = '/'.join(path.split('/')[:-2]) f = open('%s/tmp/router/%s/ins.json'%(path,routerid),'r') text = f.read() if text == '': text = '{"ins":[]}' import json data = json.loads(text) f.close() f = open('%s/tmp/router/%s/ins.json'%(path,routerid),'w') data['ins'].append({'type':'play','showlink':res[3]}) f.write(json.dumps(data)) f.close() return reply_music%(fromUser, toUser, int(time.time()), res[1], res[2], res[3], res[3]) elif res[0] == 'video': return reply_news%(fromUser, toUser, int(time.time()), res[1], '', 'http://wull.me/static/img/getheadimg.jpg', res[2]) elif res[0] == 'set': from model.redisdb import RedisDB con = RedisDB().con routerid = con.get('WECHAT_BIND:'+fromUser) if routerid != None: import os path = os.path.realpath(__file__) f = open('%s/tmp/router/%s/ins.json'%(path,routerid),'r') text = f.read() if text == '': text = '{"ins":[]}' import json data = json.loads(text) f.close() f = open('%s/tmp/router/%s/ins.json'%(path,routerid),'w') data['ins'].append({'type':'set','obj':res[1],'op':res[2]}) f.write(json.dumps(data)) f.close() return ''
def wechat_index(): if request.method == 'GET': try: args = request.args signature = args.get('signature','') timestamp = args.get('timestamp','') nonce = args.get('nonce','') echostr = args.get('echostr') token = 'zengzhaoyang' list = [token,timestamp,nonce] list.sort() sha1 = hashlib.sha1() map(sha1.update,list) hashcode = sha1.hexdigest() if hashcode == signature: return echostr return 'wrong' except: return 'wrong' else: data = request.data re_touser = re.compile('<ToUserName><!\\[CDATA\\[(.*?)\\]\\]></ToUserName>') re_fromuser = re.compile('<FromUserName><!\\[CDATA\\[(.*?)\\]\\]></FromUserName>') re_msgType = re.compile('<MsgType><!\\[CDATA\\[(.*?)\\]\\]></MsgType>') re_content = re.compile('<Content><!\\[CDATA\\[(.*?)\\]\\]></Content>') re_event = re.compile('<Event><!\\[CDATA\\[(.*?)\\]\\]></Event>') re_eventkey = re.compile('<EventKey><!\\[CDATA\\[(.*?)\\]\\]></EventKey>') re_recognition = re.compile('<Recognition><!\\[CDATA\\[(.*?)\\]\\]></Recognition>') re_picurl = re.compile('<PicUrl><!\\[CDATA\\[(.*?)\\]\\]></PicUrl>') re_mediaid = re.compile('<MediaId><!\\[CDATA\\[(.*?)\\]\\]></MediaId>') re_scantype = re.compile('<ScanType><!\\[CDATA\\[(.*?)\\]\\]></ScanType>') re_scanresult = re.compile('<ScanResult><!\\[CDATA\\[(.*?)\\]\\]></ScanResult>') re_latitude = re.compile('<Latitude>(.*?)</Latitude>') re_longitude = re.compile('<Longitude>(.*?)</Longitude>') toUser = re_touser.findall(data)[0] fromUser = re_fromuser.findall(data)[0] msgType = re_msgType.findall(data)[0] if msgType == 'event': event = re_event.findall(data)[0] if event == 'CLICK': eventKey = re_eventkey.findall(data)[0] if eventKey == 'QUERY': from model.redisdb import RedisDB con = RedisDB().con access_token = con.get('weopenid2uber:%s'%fromUser) request_id = con.get('openid2requestid:%s'%fromUser) url = 'https://sandbox-api.uber.com.cn/v1/requests/%s'%request_id headers = {'Authorization':'Bearer '+access_token}#,'Content-Type': 'application/json'} import json import requests res = requests.get(url, headers=headers) print res.text data = json.loads(res.text) driver_name = 'null' driver_phone = '' driver_rating = '' eta = '' license_plate = '' try: driver = data['driver'] driver_phone = driver['phone_number'] driver_rating = driver['rating'] driver_name = driver['name'] eta = data['eta'] license_plate = data['vehicle']['license_plate'] except: pass word = '司机:%s\n手机号:%s\n星际:%s\n车牌:%s\n剩余时间:%s分钟\n'%(driver_name, driver_phone, driver_rating, license_plate, eta) return reply_text%(fromUser, toUser, int(time.time()), word) if event == 'LOCATION': print 'hahaha' lat = re_latitude.findall(data)[0] # weidu lng = re_longitude.findall(data)[0] # jingdu print lat,lng from model.redisdb import RedisDB con = RedisDB().con con.set('openid2geo:%s'%fromUser,lat+':'+lng) return '' elif msgType == 'text': content = re_content.findall(data)[0] return reply_text%(fromUser, toUser, int(time.time()), content) elif msgType == 'voice': recognition = re_recognition.findall(data)[0] pass
def set_status(fromUser, choice): from model.redisdb import RedisDB con = RedisDB().con if con.exists('WECHAT_STATUS:'+fromUser) == False: con.set('WECHAT_STATUS:'+fromUser, 0) if choice == 0: con.set('WECHAT_STATUS:'+fromUser, 0) elif choice == 1: if con.get('WECHAT_STATUS:'+fromUser) == '1': num = con.get('WECHAT_IMG_NUM:'+fromUser) con.set('WECHAT_STATUS:'+fromUser, 0) return int(num) else: con.set('WECHAT_STATUS:'+fromUser, 1) con.set('WECHAT_IMG_NUM:'+fromUser, 0) con.expire('WECHAT_STATUS:'+fromUser, 1800) import os path = os.path.realpath(__file__) path = '/'.join(path.split('/')[:-2]) os.system("mkdir %s/tmp/user/%s"%(path,fromUser)) os.system("mkdir %s/tmp/user/%s/recent"%(path,fromUser)) os.system("mkdir %s/tmp/user/%s/sanguosha"%(path,fromUser)) return -1 elif choice == 2: con.set('WECHAT_STATUS:'+fromUser, '201')
def check_status(fromUser, content): status = get_status(fromUser) import os path = os.path.realpath(__file__) path = '/'.join(path.split('/')[:-2]) from model.redisdb import RedisDB con = RedisDB().con print status if status == '202': length = len(content.decode('utf-8')) if length >= 2 and length <= 4: os.system("echo %s > %s/tmp/user/%s/sanguosha/config.txt"%(content, path, fromUser)) con.set('WECHAT_STATUS:'+fromUser, '203') return 0, u'【step 2/6】发一下称号过来,如“大傻逼”,支持2~5个字' elif length > 4: return 0, u'。。哪有这么长的名字,重发一个吧' elif length < 2: return 0, u'。。哪有一个字的名字,重发一个吧' elif status == '203': length = len(content.decode('utf-8')) if length >= 2 and length <= 5: os.system("echo %s >> %s/tmp/user/%s/sanguosha/config.txt"%(content, path, fromUser)) con.set('WECHAT_STATUS:'+fromUser, '204') return 0, u'【step 3/6】发一下血量,支持1~8' elif length > 5: return 0, u'哎称号太长了放不下,重发一个吧' elif length < 2: return 0, u'一个字的称号果断没有气势啊,重发一个吧' elif status == '204': try: num = int(content) res = '' if num > 8: num = 8 res = u'血太多会撑死的,就给你8滴血啦' elif num < 1: num = 1 res = u'0血就死了,勉强给你1滴血吧' os.system("echo %d >> %s/tmp/user/%s/sanguosha/config.txt"%(num, path, fromUser)) con.set('WECHAT_STATUS:'+fromUser, '205') return 0, res + u'【step 4/6】发一下属性,如“神”,只支持单个文字' except: return 0, u'求发数字,,不然我识别不出来' elif status == '205': length = len(content.decode('utf-8')) if length == 1: os.system("echo %s >> %s/tmp/user/%s/sanguosha/config.txt"%(content, path, fromUser)) con.set('WECHAT_STATUS:'+fromUser, '206') return 0, u'【step 5/6】发一下技能1的名字和描述吧,用空格隔开,如“天才 你在场上的时候所有人都会变成傻逼”,技能名字必须是两个字的,技能描述最多可支持60个汉字,且不能带有空格' else: return 0, u'属性只支持单个文字啦' elif status == '206': temp = content.decode('utf-8').split() if len(temp) != 2: return 0, u'技能名字和描述要用空格分开啦' if len(temp[0]) != 2: return 0, u'技能名字只支持两个字哦' if len(temp[1]) > 60: return 0, u'技能描述太长了啦,放不下了' os.system("echo %s >> %s/tmp/user/%s/sanguosha/config.txt"%(content, path, fromUser)) con.set('WECHAT_STATUS:'+fromUser, '207') return 0, u'【step 6/6】发一下技能2的名字和描述吧,要求同技能1,此处回复“无”可只显示一个技能' elif status == '207': if content == '无': os.system("echo %s >> %s/tmp/user/%s/sanguosha/config.txt"%(content, path, fromUser)) con.set('WECHAT_STATUS:'+fromUser, 0) os.system("python %s/wechat/s.py %s %s&"%(path,fromUser,get_accesstoken())) return 0, u'【pending......】静静等候10秒钟吧' temp = content.decode('utf-8').split() if len(temp) != 2: return 0, u'技能名字和描述要用空格分开啦' if len(temp[0]) != 2: return 0, u'技能名字只支持两个字哦' if len(temp[1]) > 60: return 0, u'技能描述太长了啦,放不下了' os.system("echo %s >> %s/tmp/user/%s/sanguosha/config.txt"%(content, path, fromUser)) con.set('WECHAT_STATUS:'+fromUser, 0) os.system("python %s/wechat/s.py %s %s&"%(path,fromUser,get_accesstoken())) return 0, u'【pending......】静静等候10秒钟吧' return -1, 0
def bind_user(openid, routeid): from redisdb import RedisDB con = RedisDB().con con.set('WECHAT_BIND:'+openid, routeid) return userinfo
def get_userid_by_session(session): from model.redisdb import RedisDB con = RedisDB().con userid = con.get('session2username:%s'%session) print userid return userid