def execute_command(self, cmd, *args, **kwargs): callback = kwargs.get('callback', None) del kwargs['callback'] cmd_line = CmdLine(cmd, *args, **kwargs) if self.subscribed and cmd not in PUB_SUB_COMMANDS: callback( RequestError( 'Calling not pub/sub command during subscribed state', cmd_line)) return if not self.connection.connected(): self.connection.connect() if not self.connection.ready() and not self.subscribed: yield gen.Task(self.connection.wait_until_ready) try: # Split the command, and add them to the front # of the arguments, so they get formatted like the other # parts. This is to handle SCRIPT LOAD commands. bits = cmd.split(' ') bits.reverse() args = list(args) args.reverse() args.extend(bits) args.reverse() self.connection.write(self.format_command(*args, **kwargs)) except Exception, e: self.connection.disconnect() raise e
def get_players_in_ladder(region_code: str, ladder: Ladder, params: dict) -> """List of players""": players = [] r = requests.get( "https://{}.api.battle.net/data/sc2/ladder/{}".format( region_code, ladder.id), params) if r.status_code != 200: raise RequestError( r, "{} returned error code {}, skipping...".format( r.url, r.status_code)) json = r.json() for player in json["team"]: try: bnet = player["member"][0]["character_link"]["battle_tag"] mmr = player["rating"] games_played = player["member"][0]["played_race_count"][0][ "count"] race = player["member"][0]["played_race_count"][0]["race"] found_player = False for p_obj in players: if p_obj.battletag == bnet: p_obj.add_race(race, ladder.league_id, ladder.division, games_played, mmr) found_player = True if not found_player: obj = Player(bnet, region_code) # ladder.division + 1 is due to API having d1 be 0, d2 be 1, etc. obj.add_race(race, ladder.league_id, ladder.division, games_played, mmr) players.append(obj) except KeyError: continue return players
def execute_command(self, cmd, *args, **kwargs): if cmd in ('AUTH', 'SELECT'): super(Pipeline, self).execute_command(cmd, *args, **kwargs) elif cmd in PUB_SUB_COMMANDS: raise RequestError( 'Client is not supposed to issue command %s in pipeline' % cmd) self.command_stack.append(CmdLine(cmd, *args, **kwargs))
def get_all_ladders(region_code: str, max_league_id: int, season_id: int, params: dict) -> """List of ladders""": ladders = [] for league_id in range(max_league_id + 1): try: r = requests.get( "https://{}.api.battle.net/data/sc2/league/{}/201/0/{}". format(region_code, season_id, league_id), params) if r.status_code != 200: raise RequestError( r, "{} returned error code {}, skipping...".format( r.url, r.status_code)) Log.write_log_message("League {} Status: {}".format( league_id, r.status_code)) json = r.json() for tier in json["tier"]: division = tier["id"] + 1 min_mmr = tier["min_rating"] max_mmr = tier["max_rating"] for ladder in tier["division"]: ladder_id = ladder["ladder_id"] obj = Ladder(region_code, ladder_id, league_id, division, min_mmr, max_mmr) ladders.append(obj) except RequestError as e: Log.write_log_message(e.__str__(), True) return ladders
def get_current_season_id(params: dict) -> int: r = requests.get("https://us.api.battle.net/data/sc2/season/current", params) if r.status_code != 200: raise RequestError( r, "{} returned error code {}, exiting...".format( r.url, r.status_code)) return r.json()["id"]
def update(self, parsed_req): """ Update the score of a specific user ,if exists otherwise rise RequestError """ if not self.leaderboard.has_user(parsed_req['user']): raise RequestError( 404, "User {} does not exist".format(parsed_req['user'])) self.leaderboard.update_user_score(parsed_req) return JSONResponse(200, self.kStatus_ok)
def get_top(self, path): """ Retrieve top XX of the leaderboard """ top_number = path.rsplit('/', 1).pop() try: sorted_list = self.leaderboard.get_top(int(top_number)) return JSONResponse(200, sorted_list) except ValueError: raise RequestError( 400, "Wrong parameter type expected int got {}".format(top_number))
def get_partial(self, path): """ Retrieve relative ranking around a position """ splitted = path.rsplit('/', 2) try: sorted_list = self.leaderboard.get_partial(int(splitted[1]), int(splitted[2])) return JSONResponse(200, sorted_list) except ValueError: raise RequestError( 400, "Wrong parameter type expected int got {}".format(splitted))
def get_yima_account_info(): """ 易码平台账户信息,关键字段 (余额, "Balance") :return: dict """ params = {'action': 'getaccountinfo', 'token': YIMA_TOKEN, 'format': 1} url = 'http://api.fxhyd.cn/UserInterface.aspx' resp = requests.get(url, params=params).text status, data = resp.split('|') if status == 'success': data = json.loads(data) return {'account_type': '易码', 'Balance': data['Balance']} else: raise RequestError('request Failed')
def identify_code_from_url(url): """ 给定验证码图片的地址,返回验证码 :param url: 验证码地址 :return: str 验码识别结果 """ cj = ChaojiyingClient() resp = requests.get(url) if resp.ok: if len(resp.content) < 500: raise Exception('未成功获取验证码图片:类型错误') return cj.parse(resp.content) else: raise RequestError('未成功获取验证码图片:请求错误')
def execute_command(self, cmd, *args, **kwargs): callback = kwargs.get('callback', None) del kwargs['callback'] cmd_line = CmdLine(cmd, *args, **kwargs) if self.subscribed and cmd not in PUB_SUB_COMMANDS: callback(RequestError( 'Calling not pub/sub command during subscribed state', cmd_line)) return try: self.connection.write(self.format_command(cmd, *args, **kwargs)) except Exception, e: self.connection.disconnect() raise e