def _dopost(self, urikey, postdata = '', usecookie = True, setcookie = True, extraheader = {'Cookie2': '$Version=1'}, xmlresp = True, noencrypt = False, savetraffic = False, no2ndkey=False ): resp, _dec = self.poster.post(urikey, postdata, usecookie, setcookie, extraheader, noencrypt, savetraffic, no2ndkey) self.lastposttime = time.time() if int(resp['status']) >= 400: return resp, _dec resp.update({'error':False, 'errno':0, 'errmsg':''}) if not xmlresp: dec = _dec else: try: dec = XML2Dict.fromstring(_dec).response except: dec = XML2Dict.fromstring(re.compile('&(?!#)').sub('&',_dec)).response try: err = dec.header.error except: pass else: if err.code != '0': resp['errmsg'] = err.message # 1050木有BC 1010卖了卡或妖精已被消灭 8000基友点或卡满了 1020维护 1030有新版本 if not err.code in ['1050', '1010', '1030'] and not (err.code == '1000' and self.loc == 'jp'): # ,'8000']: self.logger.error('code:%s msg:%s' % (err.code, err.message)) resp.update({'error':True, 'errno':int(err.code)}) else: if not self.player_initiated: if self.player.update_all(dec)[1]: self.logger.debug(update_dt[0]) open(self.playerfile, 'w').write(_dec) self.logger.debug('post:master cards saved.') return resp, dec
def do(*args): if plugin_vals['loc'] == 'jp': get=lambda x, y:XML2Dict.fromstring(x).response.body.roundtable_edit.deck[y - 1].deck_cards else: get=lambda x, y:XML2Dict.fromstring(x).response.body.roundtable_edit.deck_cards poster=plugin_vals['poster'] pcard=plugin_vals['player'].card cf=plugin_vals['cf'] def write_config(sec, key, val): if not cf.has_section(sec): cf.add_section(sec) cf.set(sec, key, val) f = open(plugin_vals['configfile'], "w") cf.write(f) f.flush() list_option=cf.options _jp_cache = None for i in (plugin_vals['loc'] == 'jp' and range(1,5,1) or range(1,4,1)): if i == 4: print(du8('推荐卡组:')) else: print(du8('卡组%d:' % i)) if plugin_vals['loc'] == 'jp': if not _jp_cache: _jp_cache = poster.post('roundtable/edit', postdata = 'move=1')[1] _data = _jp_cache else: _data = poster.post('roundtable/edit', postdata = 'move=1%s'%(i>1 and '&deck_id=%s'%i or ''))[1] try: C=get(_data, i).rstrip(',empty').split(',') assert(C != ['']) except AssertionError: print(du8('卡组为空,跳过ww')) continue # except: # print(du8('读取卡组失败,请输入rl重新登录')) # return CL=tolist(C) try: print(du8('\n'.join(['|'.join(map( lambda x:' %-12s' % pcard.db[pcard.sid(x).master_card_id][0], C[i:min(i + 3, len(CL))] )) for i in range(0, len(CL), 3)]))) except ValueError: continue decks = list_option('carddeck') print(du8('\n选择卡组,输入卡组名以添加新卡组,按回车跳过')) print(iter_printer(decks)) inp = raw_input("> ") if inp == "": continue elif inp in [str(i) for i in range(1, len(decks) + 1)]: name = decks[int(inp) - 1] else: name = inp write_config('carddeck', name, ','.join(C)) print(du8('保存到了%s' % name))
def _do_update(silent = False): update_file = opath.join(_get_temp(), '.MAClient.update') try: _m = open(update_file).read() except IOError: return False if time.time() - os.path.getmtime(update_file) > 259200:#3天 os.remove(opath.join(_get_temp(), '.MAClient.update')) _check_update(silent) return _do_update(silent) _top = XML2Dict.fromstring(_m).maclient _done = False update_item = 'update_item' in _top and _top.update_item or None new_item = 'new_item' in _top and _top.new_item or None _updated_count = [] for (_prompt, _meta) in [('√ 已更新 %s ↑ v%s', update_item), ('√ 新增 %s v%s', new_item)]: for k in tolist(_meta): if not k: continue if k.name == 'maclient.py': if not silent: if EXEBUNDLE: print(du8('√ 主程序有新版本 v%s 请至以下链接查看\n' 'github: https://github.com/fffonion/MAClient/\n' '百度盘: http://pan.baidu.com/s/19qI4m' % k.version)) else: update_self({})('') continue elif k.name == 'maclient_smart.py' and EXEBUNDLE: new = _http_get('update/maclient_smart.bin', silent) try: assert(new and len(new)>28000) if opath.exists(opath.join(getPATH0, 'maclient_smart.py_')): os.remove(opath.join(getPATH0, 'maclient_smart.py_')) os.rename(opath.join(getPATH0, 'maclient_smart.pyd'),opath.join(getPATH0, 'maclient_smart.py_')) open(opath.join(getPATH0, 'maclient_smart.pyd'),'wb').write(new) _updated_count.append(k.name) except (TypeError, WindowsError, AssertionError): if not silent: print(du8('× maclient_smart有新版本但更新失败 v%s 请至以下链接下载完整包\n' 'http://pan.baidu.com/s/19qI4m' % k.version)) else: print(du8('√ 已更新 maclient_smart ↑ v%s' % k.version)) continue new = _http_get((GET_DEV_UPDATE and 'dev/' or 'master/') + (k.dir or '') + '/' + k.name, silent) if not new: if not silent: print(du8('× %s 更新失败' % k.name)) continue open(opath.join(getPATH0, k.dir or '', k.name),'w').write(new.replace('\r\n', '\n')) _updated_count.append(k.name) if not silent: print(du8(_prompt % (k.name, k.version))) _done = True if not EXEBUNDLE and not silent: print(du8('你可以通过us命令来更新本体到最新版')) os.remove(update_file) if _done and not silent: print(du8('重新启动maclient以应用更新')) return _updated_count
def offers_parse(self, content): try: r = XML2Dict().fromstring(content)['response']['resource'] except: return None return r
def getAnnos(file_name="", prefix=''): xml = XML2Dict() root = xml.parse(file_name) # get a dict object anno = root.annotation image_name = anno.filename item = { 'filename': prefix + image_name, 'class': 'image', 'annotations': [] } for obj in anno.object: cls = {'positive': 'C1', 'negative': 'C3'}[obj.name] box = obj.bndbox x, y, width, height = int(box.xmin), int(box.ymin), int( box.xmax) - int(box.xmin), int(box.ymax) - int(box.ymin) item['annotations'] += [{ "class": cls, "height": height, "width": width, "x": x, "y": y }] return item
def test_parsing_XML_from_file_with_parse_method(self): xml = self.xml + '<a foo="bar" hello="word" />' f = tempfile.NamedTemporaryFile(mode="w+t") f.write(xml) f.seek(0) expected_output = {'a': {'foo': 'bar', 'hello': 'word'}} self.assertEquals(XML2Dict().parse(f.name), expected_output)
def gen_list(loc): playdata = (glob.glob('.%s-*.playerdata' % loc) + glob.glob('z:/temp/.%s-*.playerdata' % loc))[-1] print(playdata) p = maclient_player.player( XML2Dict().fromstring(open(playdata).read()).response, loc) cardlist = [i for i in p.card.db] random.shuffle(cardlist) return cardlist, p.card.db
def _dopost(self, urikey, postdata='', usecookie=True, setcookie=True, extraheader={'Cookie2': '$Version=1'}, xmlresp=True, noencrypt=False, savetraffic=False, no2ndkey=False): resp, _dec = self.poster.post(urikey, postdata, usecookie, setcookie, extraheader, noencrypt, savetraffic, no2ndkey) self.lastposttime = time.time() if int(resp['status']) >= 400: return resp, _dec resp.update({'error': False, 'errno': 0, 'errmsg': ''}) if not xmlresp: dec = _dec else: try: dec = XML2Dict.fromstring(_dec).response except: dec = XML2Dict.fromstring(re.compile('&(?!#)').sub('&', _dec)).response try: err = dec.header.error except: pass else: if err.code != '0': resp['errmsg'] = err.message # 1050木有BC 1010卖了卡或妖精已被消灭 8000基友点或卡满了 1020维护 1030有新版本 if not err.code in ['1050', '1010', '1030'] and not ( err.code == '1000' and self.loc == 'jp'): # ,'8000']: self.logger.error('code:%s msg:%s' % (err.code, err.message)) resp.update({'error': True, 'errno': int(err.code)}) else: if not self.player_initiated: if self.player.update_all(dec)[1]: self.logger.debug(update_dt[0]) open(self.playerfile, 'w').write(_dec) self.logger.debug('post:master cards saved.') return resp, dec
def readernautsyncr(self): """ First checking to know how many pages exist for a readernaut user. Append each pagenumber as an argument to 'syncbooks' which actually does the syncing. """ url = "http://readernaut.com/api/v1/xml/" + settings.READERNAUT_USERNAME + "/books/" data = urllib.urlopen(url).read() x = XML2Dict() r = x.fromstring(data) page_range = int(r['reader_books']['total_pages']['value']) for a in range(page_range): syncbooks(a + 1)
def XmlTodict(xmlFilePath): xml = XML2Dict() r = xml.parse(xmlFilePath) dic = dict() for item in r.annotation.object: dic.setdefault(item.name, []).append(int(item.bndbox.xmin)) dic.setdefault(item.name, []).append(int(item.bndbox.ymin)) dic.setdefault(item.name, []).append(int(item.bndbox.xmax) - int(item.bndbox.xmin)) dic.setdefault(item.name, []).append(int(item.bndbox.ymax) - int(item.bndbox.ymin)) # print(dic) return dic
def syncbooks(pagenum): """ Phrases the url to fetch from and them parse the XML data using xml2dict (http://code.google.com/p/xml2dict/) Apparently I am lazy to parse XML. Feel free to use your own way. For each book I check if it has one or more authors and then append it into one single string. Again feel free to make a model for author and add a foreign key based on your requirement. I am using dateutil to parse the date in string format into a python datetime object. Check if the book exists if it does n't add it to Book model. """ url1 = "http://readernaut.com/api/v1/xml/" + settings.READERNAUT_USERNAME + "/books/?page=" + str( pagenum) data1 = urllib.urlopen(url1).read() x1 = XML2Dict() r1 = x1.fromstring(data1) for book in r1["reader_books"]["reader_book"]: authors = [] if len(book['book_edition']['authors']['author']) > 1: for auth in book['book_edition']['authors']['author']: authors.append(auth["value"]) author = ', '.join(authors) else: author = book['book_edition']['authors']['author']['value'] pub_time = dateutil.parser.parse(book['created']['value']) if pub_time.tzinfo: pub_time = pub_time.astimezone( dateutil.tz.tzlocal()).replace(tzinfo=None) modified = dateutil.parser.parse(book['modified']['value']) if modified.tzinfo: modified = modified.astimezone( dateutil.tz.tzlocal()).replace(tzinfo=None) try: r_book = Book.objects.get(book_id=book["reader_book_id"]["value"]) except Book.DoesNotExist: new_book = Book( book_id=int(book["reader_book_id"]["value"]), author=author, title=book['book_edition']['title']["value"], isbn=book['book_edition']['isbn']["value"], cover_small=book['book_edition']['covers']['cover_small'] ["value"], cover_medium=book['book_edition']['covers']['cover_medium'] ["value"], cover_large=book['book_edition']['covers']['cover_large'] ["value"], permalink=book['book_edition']['permalink']["value"], modified=modified, created=pub_time) new_book.save()
def do(*args): po = plugin_vals['poster'] carddb = plugin_vals['carddb'] r, d = po.post('battle/area') resp = XML2Dict.fromstring(d).response if(resp.header.error.code != '0'): print(du8(resp.header.error.message)) return lakes = resp.body.competition_parts.lake if not args[0]:#mf print(du8('湖id 湖名称 合成卡片\n' + '-' * 30)) lakes = sorted(lakes, key = lambda x : int(x.lake_id if 'lake_id' in x else x.event_id)) for l in lakes: if 'lake_id' not in l: l['lake_id'] = l.event_id if l.lake_id == '0': continue n = l.title.encode('utf-8') l1 = len(n) # ascii length n = raw_du8(n) l2 = len(n) # char count print(safestr('%-2s%s %s%s%-4s%s' %( l.lake_id, '/活动' if l.event_id != '0' else ' ', n, ' ' * int(13 - l2 - (l1 - l2) / 2), l.master_card_id if 'master_card_id' in l else '', carddb[int(l.master_card_id)][0] if 'master_card_id' in l else '' ))) else:#mf 20 lake = [lakes[i] for i in range(len(lakes)) if lakes[i].lake_id == args[0].strip()] if not lake: print(du8('所选湖尚未开启XD')) return lake = lake[0] print(du8('%s %s%s' % (lake.title, lake.lake_id, lake.complete == '1' and ' 图鉴已开' or ''))) print('-' * 30) for p in lake.parts_list.parts: print('%s ' % p.parts_have, end = '') if not int(p.parts_num) % 3: print('\n')
def syncposts(self, url): data = urllib.urlopen(url).read() x = XML2Dict() r1 = x.fromstring(data) if url == "http://username.tumblr.com/api/read": site = 1 else: site = 2 for post in r1['tumblr']['posts']['post']: if post['type']['value'] == 'photo': syncphoto(post, site) elif post['type']['value'] == 'link': synclink(post, site) elif post['type']['value'] == 'conversation': syncconversation(post, site) elif post['type']['value'] == 'quote': syncquote(post, site) elif post['type']['value'] == 'video': syncvideo(post, site) elif post['type']['value'] == 'audio': syncaudio(post, site) else: syncregular(post, site)
loc = 'cn' mac = maclient.maClient( configfile=r'D:\Dev\Python\Workspace\maClient\_mine\config_cn.ini') mac.login() a, b = mac._dopost('masterdata/card/update', postdata='%s&revision=0' % mac.poster.cookie, noencrypt=True) open(r'z:\card.%s.xml' % loc, 'w').write(b) a, b = mac._dopost('masterdata/item/update', postdata='%s&revision=0' % mac.poster.cookie, noencrypt=True) open(r'z:\item.%s.xml' % loc, 'w').write(b) xml = open(r'z:\card.%s.xml' % loc, 'r').read().replace('&', '--').replace('--#', '&#') print XML2Dict().fromstring(xml).response.header.revision.card_rev body = XML2Dict().fromstring(xml).response.body cards = body.master_data.master_card_data.card strs = [] for c in cards: strs.append('%s,%s,%s,%s,%s,%s,%s,%s' % (c.master_card_id, c.name, c.rarity, c.cost, str(c.char_description).strip('\n').strip(' ').replace( '\n', '\\n'), c.skill_kana, c.skill_name, str(c.skill_description).replace('\n', '\\n'))) open(r'z:\card.%s.txt' % loc, 'w').write('\n'.join(strs)) xml = open(r'z:\item.%s.xml' % loc, 'r').read().replace('&', '--').replace('--#', '&#') body = XML2Dict().fromstring(xml).response.body itmes = body.master_data.master_item_data.item_info strs = []
def _check_update(silent = False): check_file = opath.join(_get_temp(), '.MAClient.noupdate') if opath.exists(check_file): if time.time() - os.path.getmtime(check_file) < 86400:#1天内只检查一次 return os.remove(check_file) if not silent: print('Retrieving meta info ...') body = _http_get('update/meta.xml', silent) if not body: print('Error fetching meta') return meta = XML2Dict.fromstring(body).maclient xml = '<?xml version="1.0" encoding="UTF-8"?><maclient><time>%d</time>' % int(time.time()) s_update = '<update_item><name>%s</name><version>%s</version><dir>%s</dir></update_item>' s_new = '<new_item><name>%s</name><version>%s</version><dir>%s</dir></new_item>' new = False for k in meta.plugin + meta.script: script = opath.join(getPATH0, k.dir or '', k.name) # reserved for exe bundle if k.name == 'maclient.py': mainitm = k elif k.name == 'maclient_smart.py': smtitm = k if EXEBUNDLE: if k.name == 'maclient_cli.py': continue elif k.name == 'maclient.py': import maclient if ('%.2f' % maclient.__version__) < k.version: xml += s_update % (k.name, k.version, k.dir or '') new = True continue elif k.name == 'maclient_smart.py': import maclient_smart if str(maclient_smart.__version__) < k.version: xml += s_update % ('maclient_smart.py', k.version, k.dir or '') new = True continue if opath.exists(script): _s = open(script).read() ver = re.findall('__version__[\s=\']*([^\'\s]+)[\']*', _s) if ver and ver[0] < k.version: xml += s_update % (k.name, k.version, k.dir or '') new = True else: #new item xml += s_new % (k.name, k.version, k.dir or '') new = True # if EXEBUNDLE: # import maclient # import maclient_smart # if str(maclient.__version__) < mainitm.version: # xml += s_update % (mainitm.name, mainitm.version, '') # new = True # if str(maclient_smart.__version__) < smtitm.version: # xml += s_update % (smtitm.name, smtitm.version, '') # new = True if new: open(opath.join(_get_temp(), '.MAClient.update'), 'w').write(xml+'</maclient>') return True else: open(opath.join(_get_temp(), '.MAClient.noupdate'), 'w').write('') return False
def do(*args): logger = plugin_vals['logger'] cf = plugin_vals['cf'] cfg_file = args[0] if (args[0] and opath.exists(args[0])) else None cfg_file = opath.join(getPATH0, 'config.xml') \ if (opath.exists(opath.join(getPATH0, 'config.xml'))) \ else cfg_file while not cfg_file: cfg_file = raw_inputd('输入配置文件的路径 > ') if not cfg_file: return if opath.exists(cfg_file): break if opath.exists(opath.join(cfg_file, 'config.xml')): cfg_file = opath.join(cfg_file, 'config.xml') break logger.error('输入的路径"%s"不存在配置文件www' % cfg_file) cfg_file = None try: _t = XML2Dict.fromstring(open(cfg_file).read()).config.card decks = _t.battle_fairy except: logger.error('所选"%s"可能不是maw配置文件,或者格式扭曲了TAT' % cfg_file) return wake_decks = [] norm_decks = [] guild_decks = [] guild_wake_decks = [] for d in decks: if d.wake == '0': d_name = norm_decks pref = 'norm' elif d.wake == '1': d_name = wake_decks pref = 'wake' elif d.wake == '2': d_name = guild_decks pref = 'guild' else: d_name = guild_wake_decks pref = 'guild_w' d_name.append(('%s and $.hp%%>=%s and BC>=%s' % ('<=$.lv<='.join( d.fairy_lv.split('-')), d.fairy_hp, d.battle_cost), '%s%s' % (pref, d.fairy_lv))) _set_cfg_val(cf, 'carddeck', '%s%s' % (pref, d.fairy_lv), d.battle_card.rstrip(',empty')) def _gen_cond(decks): ret = "" for d in decks: ret += "((%s) and '%s' or " % (d[0], d[1]) ret += "'min'" ret += ')' * len(decks) return ret cond = '$.IS_WAKE and %s or %s' % (_gen_cond(wake_decks), _gen_cond(norm_decks)) if guild_decks and guild_wake_decks: cond = '$.IS_GUILD and ($.IS_WAKE and %s or %s) or (%s)' % ( _gen_cond(guild_wake_decks), _gen_cond(guild_decks), cond) _set_cfg_val(cf, 'condition', 'fairy_select_carddeck', cond) _set_cfg_val(cf, 'carddeck', 'min', _t.lick_fairy.card) if _t.pvp.pvp_card: _set_cfg_val(cf, 'carddeck', 'factor', _t.pvp.pvp_card) _write_cfg(cf, plugin_vals['configfile']) print(du8('已保存%d条卡组条件,以及因子战及舔刀卡组\n你可以通过输入cmi命令清除导入的卡组和条件' % len(decks)))
def get_xmlfile_dict(xml_file): xml = XML2Dict() return xml.parse(xml_file)
def get_xmlstring_dict(xml_string): xml = XML2Dict() return xml.fromstring(xml_string)
def Normalize(string): #格式化查询词 #result = RemoveAccents(string) result = string.replace(".", " ") result = result.replace("-", " ") # trim extra blank result = " ".join(result.split()) # upper chars to lower result = result.lower() #字符串变成小写 return result #0726上一句改:没有被nickname 中的词替换 from xml2dict import XML2Dict xml = XML2Dict() r = xml.parse("tac_2011_kbp_english_evaluation_entity_linking_queries.xml") f = open("query_info_0727", 'w') f.write('#id\tname\tdocid\tname(格式化)\n') for q in r.kbpentlink.query: progress = Normalize(q.name) f.write(q.id + '\t' + q.name + '\t' + q.docid + '\t' + progress + '\n') f.close()
def do(*args): loc = plugin_vals['loc'] po = plugin_vals['poster'] logger = plugin_vals['logger'] if 'player' not in plugin_vals: logger.error('玩家信息还没有初始化') return invid = hex(int(plugin_vals['player'].id))[2:] cnt = 0 logger.warning('如果连续注册遇到code 500\n请明天再试\n或者使用VPN或代理连接(MAClient会在启动时自动读取IE代理)') print(du8('招待码 = %s' % invid)) while True: po.cookie = '' po.post('check_inspection') if loc not in ['jp', 'my']: po.post('notification/post_devicetoken', postdata = 'S=nosessionid&login_id=&password=&app=and&token=') # s=raw_input('session: ').lstrip('S=').strip() # print po.cookie while True: uname, pwd = '', '' while len(uname) < 4 or len(uname) > 14: uname = raw_input('user-name: ') while len(pwd) < 8 or len(pwd) > 14: pwd = raw_input('password: '******'sg': p = 'email=%s@%s&invitation_id=%s&login_id=%s¶m=&password=%s&password_confirm=%s&platform=1¶m=%s' % ( uname, random.choice(['google.com', 'yahoo.com', 'live.com']), invid, uname, pwd, pwd, '35' + (''.join([str(random.randint(0, 9)) for i in range(10)])) ) else: p = 'invitation_id=%s&login_id=%s&password=%s¶m=%s' % (invid, uname, pwd, '35' + (''.join([str(random.randint(0, 9)) for i in range(10)]))) # print maclient_network.encode_param(p) r, d = po.post('regist', postdata = p) if(XML2Dict.fromstring(d).response.header.error.code != '0'): print(XML2Dict.fromstring(d).response.header.error.message) continue break GET_header = po.header GET_header.update({'Cookie':po.cookie}) # httplib2.Http().request(maclient_network.serv[loc]+'tutorial/next?step=100&resume_flg=1',headers=GET_header) # my server add scenario_id=0 time.sleep(2.328374) po.post('tutorial/save_character', postdata = 'country=%s&name=%s' % (random.choice('123'), uname)) time.sleep(2.123123) po.post('tutorial/next', postdata = 'S=%s&step=%s' % (po.cookie, 1000)) time.sleep(2.123123) po.post('tutorial/next', postdata = 'S=%s&step=%s' % (po.cookie, 7025)) time.sleep(3.123123) resp, ct = po.post('tutorial/next', postdata = 'S=%s&step=%s' % (po.cookie, 8000)) if loc in ['kr', 'sg']: # httplib2 doesn't follow redirection in POSTs resp, ct = httplib2.Http().request(maclient_network.serv[loc] + 'mainmenu?fl=1', headers = GET_header) if len(ct) > 8000: cnt += 1 print('Success. (%d done)' % cnt) else: print('Error occured.') time.sleep(2.232131) if raw_input('exit?(y/n)') == 'y': print(du8("请重新登录 relogin(rl) 来刷新玩家信息!")) break
def do(*args): loc = plugin_vals['loc'] po = plugin_vals['poster'] logger = plugin_vals['logger'] if 'player' not in plugin_vals: logger.error('玩家信息还没有初始化') return if args[0].strip().lstrip('-').isdigit(): reg_cnt = int(args[0].strip()) # >0 => auto_mode else: reg_cnt = -1 if reg_cnt == -0xe9:#ubw mode invid = hex(random.randrange(100000, 2333333))[2:] else: invid = hex(int(plugin_vals['player'].id))[2:] cnt = 0 _prt = lambda x: print(du8(x)) if reg_cnt != -0xe9 else None #logger.warning('如果连续注册遇到code 500\n请明天再试\n或者使用VPN或代理连接(MAClient会在启动时自动读取IE代理)') _prt('招待码 = %s' % invid) while True: po.cookie = '' po.post('check_inspection') if loc not in ['jp', 'my']: po.post('notification/post_devicetoken', postdata = 'S=nosessionid&login_id=&password=&app=and&token=') # s=raw_input('session: ').lstrip('S=').strip() # print po.cookie while True: uname, pwd = '', '' if reg_cnt > 0 or reg_cnt == -0xe9:#auto_mode or ubw mode uname = ''.join([random.choice(string.letters + string.digits) for i in range(random.randrange(4,14))]) pwd = ''.join([random.choice(string.letters + string.digits) for i in range(random.randrange(8,14))]) while len(uname) < 4 or len(uname) > 14: uname = raw_input('user-name: ') while len(pwd) < 8 or len(pwd) > 14: pwd = raw_input('password: '******'sg': p = 'email=%s@%s&invitation_id=%s&login_id=%s¶m=&password=%s&password_confirm=%s&platform=1¶m=%s' % ( uname, random.choice(['google.com', 'yahoo.com', 'live.com']), invid, uname, pwd, pwd, '35' + (''.join([str(random.randint(0, 9)) for i in range(10)])) ) else: p = 'invitation_id=%s&login_id=%s&password=%s¶m=%s' % (invid, uname, pwd, '35' + (''.join([str(random.randint(0, 9)) for i in range(10)]))) # print maclient_network.encode_param(p) print(p) r, d = po.post('regist', postdata = p, extraheader = {'X-Forwarded-For':'.'.join([str(random.randrange(0,256)) for i in range(4)])}) if(XML2Dict.fromstring(d).response.header.error.code != '0'): print(XML2Dict.fromstring(d).response.header.error.message) continue break GET_header = po.header GET_header.update({'Cookie':po.cookie}) # httplib2.Http().request(maclient_network.serv[loc]+'tutorial/next?step=100&resume_flg=1',headers=GET_header) # my server add scenario_id=0 time.sleep(2.328374) po.post('tutorial/save_character', postdata = 'country=%s&name=%s' % (random.choice('123'), uname)) time.sleep(2.123123) po.post('tutorial/next', postdata = 'S=%s&step=%s' % (po.cookie, 1000)) time.sleep(2.123123) po.post('tutorial/next', postdata = 'S=%s&step=%s' % (po.cookie, 7025)) time.sleep(3.123123) resp, ct = po.post('tutorial/next', postdata = 'S=%s&step=%s' % (po.cookie, 8000)) if loc in ['kr', 'sg']: # httplib2 doesn't follow redirection in POSTs _prt(maclient_network.serv[loc]) resp, ct = httplib2.Http().request('http://%s/%s' % (maclient_network.serv[loc][0], 'mainmenu?fl=1'), headers = GET_header) if len(ct) > 8000: cnt += 1 _prt('Success. (%d done)' % cnt) else: _prt('Error occured.') time.sleep(2.232131) reg_cnt -= 1 if reg_cnt > 0:#auto continue elif reg_cnt == -0xe9:#ubw mode open('.ubw.account.new.txt', 'w').write(' '.join((uname, pwd))) return if raw_input('exit?(y/n)') == 'y': _prt(du8("请重新登录 relogin(rl) 来刷新玩家信息!")) break
def do(*args): loc = plugin_vals['loc'] po = plugin_vals['poster'] logger = plugin_vals['logger'] if 'player' not in plugin_vals: logger.error('玩家信息还没有初始化') return if args[0].strip().lstrip('-').isdigit(): reg_cnt = int(args[0].strip()) # >0 => auto_mode else: reg_cnt = -1 if reg_cnt == -0xe9: #ubw mode invid = hex(random.randrange(100000, 2333333))[2:] else: invid = hex(int(plugin_vals['player'].id))[2:] cnt = 0 _prt = lambda x: print(du8(x)) if reg_cnt != -0xe9 else None #logger.warning('如果连续注册遇到code 500\n请明天再试\n或者使用VPN或代理连接(MAClient会在启动时自动读取IE代理)') _prt('招待码 = %s' % invid) while True: po.cookie = '' po.post('check_inspection') if loc not in ['jp', 'my']: po.post( 'notification/post_devicetoken', postdata='S=nosessionid&login_id=&password=&app=and&token=' ) # s=raw_input('session: ').lstrip('S=').strip() # print po.cookie while True: uname, pwd = '', '' if reg_cnt > 0 or reg_cnt == -0xe9: #auto_mode or ubw mode uname = ''.join([ random.choice(string.letters + string.digits) for i in range(random.randrange(4, 14)) ]) pwd = ''.join([ random.choice(string.letters + string.digits) for i in range(random.randrange(8, 14)) ]) while len(uname) < 4 or len(uname) > 14: uname = raw_input('user-name: ') while len(pwd) < 8 or len(pwd) > 14: pwd = raw_input('password: '******'sg': p = 'email=%s@%s&invitation_id=%s&login_id=%s¶m=&password=%s&password_confirm=%s&platform=1¶m=%s' % ( uname, random.choice(['google.com', 'yahoo.com', 'live.com']), invid, uname, pwd, pwd, '35' + (''.join( [str(random.randint(0, 9)) for i in range(10)]))) else: p = 'invitation_id=%s&login_id=%s&password=%s¶m=%s' % ( invid, uname, pwd, '35' + (''.join( [str(random.randint(0, 9)) for i in range(10)]))) # print maclient_network.encode_param(p) print(p) r, d = po.post('regist', postdata=p, extraheader={ 'X-Forwarded-For': '.'.join([ str(random.randrange(0, 256)) for i in range(4) ]) }) if (XML2Dict.fromstring(d).response.header.error.code != '0'): print(XML2Dict.fromstring(d).response.header.error.message) continue break GET_header = po.header GET_header.update({'Cookie': po.cookie}) # httplib2.Http().request(maclient_network.serv[loc]+'tutorial/next?step=100&resume_flg=1',headers=GET_header) # my server add scenario_id=0 time.sleep(2.328374) po.post('tutorial/save_character', postdata='country=%s&name=%s' % (random.choice('123'), uname)) time.sleep(2.123123) po.post('tutorial/next', postdata='S=%s&step=%s' % (po.cookie, 1000)) time.sleep(2.123123) po.post('tutorial/next', postdata='S=%s&step=%s' % (po.cookie, 7025)) time.sleep(3.123123) resp, ct = po.post('tutorial/next', postdata='S=%s&step=%s' % (po.cookie, 8000)) if loc in ['kr', 'sg']: # httplib2 doesn't follow redirection in POSTs _prt(maclient_network.serv[loc]) resp, ct = httplib2.Http().request( 'http://%s/%s' % (maclient_network.serv[loc][0], 'mainmenu?fl=1'), headers=GET_header) if len(ct) > 8000: cnt += 1 _prt('Success. (%d done)' % cnt) else: _prt('Error occured.') time.sleep(2.232131) reg_cnt -= 1 if reg_cnt > 0: #auto continue elif reg_cnt == -0xe9: #ubw mode open('.ubw.account.new.txt', 'w').write(' '.join((uname, pwd))) return if raw_input('exit?(y/n)') == 'y': _prt(du8("请重新登录 relogin(rl) 来刷新玩家信息!")) break
def _check_update(silent=False): check_file = opath.join(_get_temp(), '.MAClient.noupdate') if opath.exists(check_file): if time.time() - os.path.getmtime(check_file) < 10800: #3小时内只检查一次 return os.remove(check_file) if not silent: print('Retrieving meta info ...') body = _http_get('update/meta.xml', silent) if not body: print('Error fetching meta') return meta = XML2Dict.fromstring(body).maclient xml = '<?xml version="1.0" encoding="UTF-8"?><maclient><time>%d</time>' % int( time.time()) s_update = '<update_item><name>%s</name><version>%s</version><dir>%s</dir></update_item>' s_new = '<new_item><name>%s</name><version>%s</version><dir>%s</dir></new_item>' new = False for k in meta.plugin + meta.script: script = opath.join(getPATH0, k.dir or '', k.name) # reserved for exe bundle if k.name == 'maclient.py': mainitm = k elif k.name == 'maclient_smart.py': smtitm = k if EXEBUNDLE: if k.name == 'maclient_cli.py': continue elif k.name == 'maclient.py': import maclient if ('%.2f' % maclient.__version__) < k.version: xml += s_update % (k.name, k.version, k.dir or '') new = True continue elif k.name == 'maclient_smart.py': import maclient_smart if str(maclient_smart.__version__) < k.version: xml += s_update % ('maclient_smart.py', k.version, k.dir or '') new = True continue if opath.exists(script): _s = open(script).read() ver = re.findall('__version__[\s=\']*([^\'\s]+)[\']*', _s) if ver and ver[0] < k.version: xml += s_update % (k.name, k.version, k.dir or '') new = True else: #new item xml += s_new % (k.name, k.version, k.dir or '') new = True # if EXEBUNDLE: # import maclient # import maclient_smart # if str(maclient.__version__) < mainitm.version: # xml += s_update % (mainitm.name, mainitm.version, '') # new = True # if str(maclient_smart.__version__) < smtitm.version: # xml += s_update % (smtitm.name, smtitm.version, '') # new = True if new: open(opath.join(_get_temp(), '.MAClient.update'), 'w').write(xml + '</maclient>') return True else: open(opath.join(_get_temp(), '.MAClient.noupdate'), 'w').write('') return False
def _do_update(silent=False): update_file = opath.join(_get_temp(), '.MAClient.update') try: _m = open(update_file).read() except IOError: return False if time.time() - os.path.getmtime(update_file) > 259200: #3天 os.remove(opath.join(_get_temp(), '.MAClient.update')) _check_update(silent) return _do_update(silent) _top = XML2Dict.fromstring(_m).maclient _done = False update_item = 'update_item' in _top and _top.update_item or None new_item = 'new_item' in _top and _top.new_item or None _updated_count = [] for (_prompt, _meta) in [('√ 已更新 %s ↑ v%s', update_item), ('√ 新增 %s v%s', new_item)]: for k in tolist(_meta): if not k: continue if k.name == 'maclient.py': if not silent: if EXEBUNDLE: print( du8('√ 主程序有新版本 v%s 请至以下链接查看\n' 'github: https://github.com/fffonion/MAClient/\n' '百度盘: http://pan.baidu.com/s/19qI4m' % k.version)) else: update_self({})('') continue elif k.name == 'maclient_smart.py' and EXEBUNDLE: new = _http_get('update/maclient_smart.bin', silent) try: assert (new and len(new) > 28000) if opath.exists(opath.join(getPATH0, 'maclient_smart.py_')): os.remove(opath.join(getPATH0, 'maclient_smart.py_')) os.rename(opath.join(getPATH0, 'maclient_smart.pyd'), opath.join(getPATH0, 'maclient_smart.py_')) open(opath.join(getPATH0, 'maclient_smart.pyd'), 'wb').write(new) _updated_count.append(k.name) except (TypeError, WindowsError, AssertionError): if not silent: print( du8('× maclient_smart有新版本但更新失败 v%s 请至以下链接下载完整包\n' 'http://pan.baidu.com/s/19qI4m' % k.version)) else: print(du8('√ 已更新 maclient_smart ↑ v%s' % k.version)) continue new = _http_get((GET_DEV_UPDATE and 'dev/' or 'master/') + (k.dir or '') + '/' + k.name, silent) if not new: if not silent: print(du8('× %s 更新失败' % k.name)) continue open(opath.join(getPATH0, k.dir or '', k.name), 'w').write(new.replace('\r\n', '\n')) _updated_count.append(k.name) if not silent: print(du8(_prompt % (k.name, k.version))) _done = True if not EXEBUNDLE and not silent: print(du8('你可以通过us命令来更新本体到最新版')) os.remove(update_file) if _done and not silent: print(du8('重新启动maclient以应用更新')) return _updated_count
def update_master(loc, need_update, poster): replace_AND = re.compile('&(?!#)') #no CDATA, sad #card, item, boss, combo new_rev = [None, None, None, None] for s in poster.ht.connections: #cleanup socket pool poster.ht.connections[s].close() poster.ht.connections = {} poster.set_timeout(240) if loc == 'jp': postdata = '' else: postdata = '%s&revision=0' % poster.cookie if need_update[0]: a, b = poster.post('masterdata/card/update', postdata=postdata) resp = XML2Dict().fromstring(replace_AND.sub('&', b)).response # 不替换会解析出错摔 cards = resp.body.master_data.master_card_data.card strs = [('%s,%s,%s,%s,%s,%s,%s,%s' % (c.master_card_id, c.name, c.rarity, c.cost, str(c.char_description).strip('\n').strip(' '), c.skill_kana, c.skill_name, str(c.skill_description))).replace( '\n', '\\n') for c in cards] + [''] if PYTHON3: f = open(opath.join(getPATH0, 'db/card.%s.txt' % loc), 'w', encoding='utf-8').write('\n'.join(strs)) else: f = open(opath.join(getPATH0, 'db/card.%s.txt' % loc), 'w').write('\n'.join(strs)) new_rev[0] = resp.header.revision.card_rev save_revision(loc, cardrev=new_rev[0]) if need_update[1]: a, b = poster.post('masterdata/item/update', postdata=postdata) resp = XML2Dict().fromstring(replace_AND.sub('&', b)).response items = resp.body.master_data.master_item_data.item_info strs = [ '%s,%s,%s' % (c.item_id, c.name, c.explanation.replace('\n', '\\n')) for c in items ] + [''] if PYTHON3: open(opath.join(getPATH0, 'db/item.%s.txt' % loc), 'w', encoding='utf-8').write('\n'.join(strs)) else: open(opath.join(getPATH0, 'db/item.%s.txt' % loc), 'w').write('\n'.join(strs)) new_rev[1] = resp.header.revision.item_rev save_revision(loc, itemrev=new_rev[1]) if need_update[2]: a, b = poster.post('masterdata/boss/update', postdata=postdata) resp = XML2Dict().fromstring(replace_AND.sub('&', b)).response boss = resp.body.master_data.master_boss_data.boss strs = ['%s,%s,%s' % (c.master_boss_id, c.name, c.hp) for c in boss] + [''] if PYTHON3: open(opath.join(getPATH0, 'db/boss.%s.txt' % loc), 'w', encoding='utf-8').write('\n'.join(strs)) else: open(opath.join(getPATH0, 'db/boss.%s.txt' % loc), 'w').write('\n'.join(strs)) new_rev[2] = resp.header.revision.boss_rev save_revision(loc, bossrev=new_rev[2]) if need_update[3]: a, b = poster.post('masterdata/combo/update', postdata=postdata) resp = XML2Dict().fromstring(replace_AND.sub('&', b)).response cbo = resp.body.master_data.master_combo_data.combo strs = [ '%s,%s,%s,%s,%s' % (c.id, c.name, c.effect_id, c.effect, 'req_cards' in c and ('[%s]' % c.req_cards) or ('req_num_card' in c and ('%s(%s)' % (c.req_num_card, ('req_form_type' in c and c.req_form_type or ''))) or '')) for c in cbo ] + [''] if PYTHON3: open(opath.join(getPATH0, 'db/combo.%s.txt' % loc), 'w', encoding='utf-8').write('\n'.join(strs)) else: open(opath.join(getPATH0, 'db/combo.%s.txt' % loc), 'w').write('\n'.join(strs)) new_rev[3] = resp.header.revision.combo_rev save_revision(loc, cborev=new_rev[3]) for s in poster.ht.connections: #cleanup socket pool poster.ht.connections[s].close() poster.ht.connections = {} poster.set_timeout(20) #rollback return new_rev
def post(self): user = users.get_current_user() if user: data = self.request.get("data") if not data: self.response.out.write('No data received!') return if data[0:5] == '<?xml': logging.info('upload file type: gpx') obj = XML2Dict() rs = obj.fromstring(data) section_count = len(rs.gpx.trk) logging.info(100000+section_count) #self.response.out.write(rs) for trk in rs.gpx.trk: point_count = len(trk.trkseg.trkpt) #logging.info(2000+point_count) begin_dt = trk.trkseg.trkpt[0]['time'].value tmp = begin_dt[0:-1].split('T') begin_time = tmp[0]+tmp[1] end_dt = trk.trkseg.trkpt[-1]['time'].value tmp = end_dt[0:-1].split('T') end_time = tmp[0]+tmp[1] tt = Track.all().filter('user', user).filter('begin_time',datetime.datetime.strptime(begin_time,'%Y-%m-%d%H:%M:%S')).filter('end_time',datetime.datetime.strptime(end_time,'%Y-%m-%d%H:%M:%S')) if tt and tt.count()>0: continue t = Track() t.upload_time += datetime.timedelta(hours=+8) t.begin_time = datetime.datetime.strptime(begin_time,'%Y-%m-%d%H:%M:%S') t.end_time = datetime.datetime.strptime(end_time,'%Y-%m-%d%H:%M:%S') t.description = '' t.put() key = t.key() i = 0 step = int(math.ceil(point_count/618.0)) logging.info('point_count:'+str(point_count)) logging.info('step:'+str(step)) for trkpt in trk.trkseg.trkpt: i += 1 if i!= point_count and (i+step-1)%step != 0: continue dt = trkpt['time'].value tmp = dt[0:-1].split('T') time = tmp[0]+tmp[1] ele = trkpt['ele'].value lon = trkpt['lon'].value lat = trkpt['lat'].value pdop = trkpt['pdop'].value tp = TrackPoint() tp.trackid = key tp.time = datetime.datetime.strptime(time,'%Y-%m-%d%H:%M:%S') tp.point = db.GeoPt(lat, lon) if ele=='NaN': ele = 0 tp.elevation = float(ele) tp.speed = 0.0 tp.pdop = float(pdop) tp.put() else: logging.info('upload file type: csv') sections = data.split('-') for section in sections[1:]: lines = section.splitlines() first = lines[1].split(',') begin_time = first[0]+first[1] last = lines[-1].split(',') end_time = last[0]+last[1] tt = Track.all().filter('user', user).filter('begin_time',datetime.datetime.strptime(begin_time,'%Y%m%d%H%M%S')).filter('end_time',datetime.datetime.strptime(end_time,'%Y%m%d%H%M%S')) if tt and tt.count()>0: continue t = Track() t.upload_time += datetime.timedelta(hours=+8) t.begin_time = datetime.datetime.strptime(begin_time,'%Y%m%d%H%M%S') t.end_time = datetime.datetime.strptime(end_time,'%Y%m%d%H%M%S') t.description = '' t.put() key = t.key() i = 0 step = int(math.ceil((len(lines)-1)/400.0)) logging.info('point_count:'+str(len(lines))) logging.info('step:'+str(step)) tp_list = [] for line in lines[1:]: i += 1 if (i+1)!= len(lines) and (i+step-1)%step != 0: continue #logging.info(line) fields = line.split(',') tp = TrackPoint() tp.trackid = key tp.time = datetime.datetime.strptime(fields[0]+fields[1],'%Y%m%d%H%M%S') tp.point = db.GeoPt(fields[2], fields[3]) if fields[4]=='NaN': ele = 0 else: ele = fields[4] tp.elevation = float(ele) speed = fields[7] if speed == 'NaN': speed = 0.0 else: speed = float(fields[7]) tp.speed = speed tp.pdop = float(fields[9]) tp_list.append(tp) db.put(tp_list) self.response.out.write('1') else: self.response.out.write('Not Login')
def do(*args): if plugin_vals['loc'] == 'jp': get = lambda x, y: XML2Dict.fromstring( x).response.body.roundtable_edit.deck[y - 1].deck_cards else: get = lambda x, y: XML2Dict.fromstring( x).response.body.roundtable_edit.deck_cards poster = plugin_vals['poster'] pcard = plugin_vals['player'].card cf = plugin_vals['cf'] def write_config(sec, key, val): if not cf.has_section(sec): cf.add_section(sec) cf.set(sec, key, val) f = open(plugin_vals['configfile'], "w") cf.write(f) f.flush() list_option = cf.options _jp_cache = None for i in (plugin_vals['loc'] == 'jp' and range(1, 5, 1) or range(1, 4, 1)): if i == 4: print(du8('推荐卡组:')) else: print(du8('卡组%d:' % i)) if plugin_vals['loc'] == 'jp': if not _jp_cache: _jp_cache = poster.post('roundtable/edit', postdata='move=1')[1] _data = _jp_cache else: _data = poster.post('roundtable/edit', postdata='move=1%s' % (i > 1 and '&deck_id=%s' % i or ''))[1] try: C = get(_data, i).rstrip(',empty').split(',') assert (C != ['']) except AssertionError: print(du8('卡组为空,跳过ww')) continue # except: # print(du8('读取卡组失败,请输入rl重新登录')) # return CL = tolist(C) try: print( du8('\n'.join([ '|'.join( map( lambda x: ' %-12s' % pcard.db[pcard.sid( x).master_card_id][0], C[i:min(i + 3, len(CL))])) for i in range(0, len(CL), 3) ]))) except ValueError: continue decks = list_option('carddeck') print(du8('\n选择卡组,输入卡组名以添加新卡组,按回车跳过')) print(iter_printer(decks)) inp = raw_input("> ") if inp == "": continue elif inp in [str(i) for i in range(1, len(decks) + 1)]: name = decks[int(inp) - 1] else: name = inp write_config('carddeck', name, ','.join(C)) print(du8('保存到了%s' % name))
def do(*args): logger = plugin_vals['logger'] loc = plugin_vals['loc'] if loc[:2] not in ['cn','tw']: logger.error('排位查询不支持日服和韩服') return if loc == 'tw': import _query_rank_tw_lib as _lib import re import urllib if PYTHON3: import urllib.request as urllib2 opener = urllib2.build_opener(urllib2.ProxyHandler(urllib.request.getproxies())) else: import urllib2 opener = urllib2.build_opener(urllib2.ProxyHandler(urllib.getproxies())) def show_it(content): strl = '\n%s\n%s\n' %(_lib.query_title(content),'-'*20) for (k, v) in _lib.query_regex[_guild_mode + _coll_mode if not _country_mode else -1]: try: strl += '%s %s\n' % (k, v(content)) except IndexError: pass logger.info(strl) _header = _lib.broswer_headers _header['cookie'] = plugin_vals['cookie'] _header['User-Agent'] = plugin_vals['poster'].header['User-Agent'] _guild_mode = 2 if raw_inputd('查询个人排名(s)(默认)还是公会排名(g)> ') == 'g' else 0 _country_mode = 0 if not _guild_mode and _lib.query_country_id:#build country selection ctotal = len(_lib.query_country_id) while True: print(du8('\n'.join(['%d.%s' % (i + 1, _lib.query_country_id[i][0]) for i in range(ctotal)]))) _sel = raw_input('> ') if _sel.isdigit() and 0 < int(_sel) <= ctotal: _country_mode = _lib.query_country_id[int(_sel) - 1][1] break while True: _goto = raw_inputd('输入要查询的排名开始数,按回车显示自己所在区域> ') if not _goto or ( _goto.isdigit() and \ ((0<int(_goto)<=20000 and not _guild_mode) or (0<int(_goto)<=2000 and _guild_mode))): break logger.error('请输入%d以内0以上的数字' % (2000 if _guild_mode else 20000)) #automatically judge if not _country_mode and ((_guild_mode and _lib.query_rev[2] and _lib.query_rev[3]) or \ (not _guild_mode and _lib.query_rev[0] and _lib.query_rev[1]) or _goto): _coll_mode = 1 if raw_inputd('查询收集品排名(c)(默认)还是妖精加权排名(f)> ') != 'f' else 0 else: _coll_mode = (1 if _lib.query_rev[3] else 0) if _guild_mode else \ (1 if _lib.query_rev[1] else 0) #request if _country_mode: if _goto: _gurl = _lib.query_goto[-1] x = opener.open(urllib2.Request(_gurl % (_goto, _country_mode),headers = _header)).read() else: _gurl = _lib.query_country x = opener.open(urllib2.Request(_gurl % _country_mode,headers = _header)).read() elif _goto: _gurl = _lib.query_goto[_guild_mode + _coll_mode] x = opener.open(urllib2.Request(_gurl % _goto,headers = _header)).read() # if True: # x = open(r'z:/test.htm').read() else: _rev = _lib.query_rev[_guild_mode + _coll_mode] if not _rev: logger.error('版本不存在,可能是当前活动没有该排名\n请尝试升级_query_rank_lib,或指定排名区域查询') return if _lib.now >= _lib.query_lifetime: logger.error('查询库已过期,请升级_query_rank_lib为新版本\n或指定排名区域查询') return _url = _lib.query_base % _rev x = opener.open(urllib2.Request(_url, headers = _header)).read() try: show_it(_lib.pre(x)) except IndexError: logger.warning('匹配失败,请重新登录;如果问题仍然存在,请更新插件') else:#cn from xml2dict import XML2Dict po = plugin_vals['poster'] po.post('menu/menulist') sel_rankid = 0 to_top = False while True: resp, ct = po.post('ranking/ranking', postdata='move=%d&ranktype_id=%d&top=%d' % ( 1 if sel_rankid == 0 else 0, sel_rankid, 1 if to_top else 0)) ct = XML2Dict.fromstring(ct).response.body.ranking ranktype_id = int(ct.ranktype_id) allranks = ct.ranktype_list.ranktype rank_name = allranks[ranktype_id - 1].title try: _user = ct.user_list.user except KeyError: logger.warning('暂未列入排行榜,请继续努力ww') return if not to_top: me = [_i for _i in _user if _i.id == plugin_vals['player'].id][0] logger.info(rank_name + (not to_top and '\n排名:%s 点数:%s\n' % (me.rank, me.battle_event_point) or '\n') + '可见区域内 Up:%s/%s Down:%s/%s' % ( _user[0].rank, _user[0].battle_event_point, _user[-1].rank, _user[-1].battle_event_point) ) while True: _inp = raw_inputd('\n输入序号查询其他排行:(9.排名至顶 0.退出)\n%s\n> ' % ('\n'.join(map(lambda x : '%s.%s' % (x.id, x.title), allranks))) ) or '0' if not _inp.isdigit(): continue else: if _inp == '0': return if _inp == '9': to_top = True else: sel_rankid = int(_inp) to_top = False break
def _get_xml(self): if self._xml == None: self._xml = XML2Dict() return self._xml
def do(*args): logger = plugin_vals['logger'] cf = plugin_vals['cf'] cfg_file = args[0] if (args[0] and opath.exists(args[0])) else None cfg_file = opath.join(getPATH0, 'config.xml') \ if (opath.exists(opath.join(getPATH0, 'config.xml'))) \ else cfg_file while not cfg_file: cfg_file = raw_inputd('输入配置文件的路径 > ') if not cfg_file: return if opath.exists(cfg_file): break if opath.exists(opath.join(cfg_file, 'config.xml')): cfg_file = opath.join(cfg_file, 'config.xml') break logger.error('输入的路径"%s"不存在配置文件www' % cfg_file) cfg_file = None try: _t = XML2Dict.fromstring(open(cfg_file).read()).config.card decks = _t.battle_fairy except: logger.error('所选"%s"可能不是maw配置文件,或者格式扭曲了TAT' % cfg_file) return wake_decks = [] norm_decks = [] guild_decks = [] guild_wake_decks = [] for d in decks: if d.wake == '0': d_name = norm_decks pref = 'norm' elif d.wake == '1': d_name = wake_decks pref = 'wake' elif d.wake == '2': d_name = guild_decks pref = 'guild' else: d_name = guild_wake_decks pref = 'guild_w' d_name.append( ( '%s and $.hp%%>=%s and BC>=%s' % ( '<=$.lv<='.join(d.fairy_lv.split('-')), d.fairy_hp, d.battle_cost ), '%s%s' % (pref, d.fairy_lv) ) ) _set_cfg_val(cf, 'carddeck', '%s%s' % (pref, d.fairy_lv), d.battle_card.rstrip(',empty')) def _gen_cond(decks): ret = "" for d in decks: ret += "((%s) and '%s' or " % (d[0], d[1]) ret += "'min'" ret += ')' * len(decks) return ret cond = '$.IS_WAKE and %s or %s' % (_gen_cond(wake_decks), _gen_cond(norm_decks)) if guild_decks and guild_wake_decks: cond = '$.IS_GUILD and ($.IS_WAKE and %s or %s) or (%s)' % (_gen_cond(guild_wake_decks), _gen_cond(guild_decks), cond) _set_cfg_val(cf, 'condition', 'fairy_select_carddeck', cond) _set_cfg_val(cf, 'carddeck', 'min', _t.lick_fairy.card) if _t.pvp.pvp_card: _set_cfg_val(cf, 'carddeck', 'factor', _t.pvp.pvp_card) _write_cfg(cf, plugin_vals['configfile']) print(du8('已保存%d条卡组条件,以及因子战及舔刀卡组\n你可以通过输入cmi命令清除导入的卡组和条件' % len(decks)))