def test_tournament_error(): """Tests a bad API call""" with pytest.raises(Exception): client.query( ''' query TournamentInfo ($slug: String!) { tournament(slug: $slug) { id name } } ''', {})
def get_sets_per_event(eventId): results = client.query( ''' query EventSets($eventId: ID!, $page: Int!, $perPage: Int!){ event(id: $eventId){ id name sets(page: $page, perPage: $perPage, sortType:STANDARD){ pageInfo{ total } nodes{ id slots{ id entrant{ id name } } } } } }''', { "eventId": eventId, "page": 1, "perPage": 1 }) #eventId = 347685 return results['data']['event']['sets']['pageInfo']['total']
def get_page_of_sets(eventSlug, page, perPage): results = client.query( ''' query EventSets($eventSlug: String!, $page:Int!, $perPage:Int!){ event(slug:$eventSlug){ id slug name startAt sets( page: $page perPage: $perPage sortType: STANDARD ){ pageInfo{ total } nodes{ id fullRoundText games{ id setId winnerId selections{ id selectionType selectionValue entrantId } } slots{ standing{ entrant{ id name } placement stats{ score{ label value displayValue } } } } } } } }''', { "eventSlug": eventSlug, "page": page, "perPage": perPage }) #return results['data']['event']['sets']['nodes'] return results['data']['event']
def get_user_details(user_slug): """Uses smash.gg API to get and return user details given a user slug.""" # Get player id and gamertag from user slug: user_player_query = ''' query GetUserDetails($slug: String) { user(slug: $slug) { id player { id gamerTag } } }''' user_details = sgg_client.query(user_player_query, '{"slug": "' + user_slug + '"}')['data']['user'] return user_details
def test_tournament_info(): """Tests an API call to get a Tournament's info""" result = client.query( ''' query TournamentInfo ($slug: String!) { tournament(slug: $slug) { id name } } ''', {"slug": "genesis-6"}) assert isinstance(result, dict) assert result['data']['tournament'][ 'name'] == "Genesis 6", "The name should be in the response"
def recent_placements_async(request): """Get recent tournament placements of given player using the smashgg API. Called by Ajax.""" if not request.is_ajax() or not request.method == 'POST': return HttpResponseNotAllowed(['POST']) game = get_object_or_404(Game, pk=request.POST['game_id']) user_slug = request.POST['user_slug'] user_gamertag = request.POST['user_gamertag'] # Hardcoded list of videogame IDS: videogame_ids = {'Super Smash Bros. Ultimate': 1386, 'Super Smash Bros. Melee': 1} # Get player's placements of 10 most recent tournaments: recent_placements_query = '''query GetPlayerPlacements($slug: String, $gamertag: String, $videogameId: ID!) { user(slug: $slug) { events(query: { page: 1, perPage: 15, filter: { videogameId: [$videogameId] } }) { nodes { name slug videogame { name } tournament { name } numEntrants standings(query: { filter: { search: { fieldsToSearch: "gamerTag" searchString: $gamertag } } }) { nodes { placement } } } } } }''' recent_placements_vars = '{"slug": "' + user_slug + '", "gamertag": "' + user_gamertag + '", "videogameId": "' + str(videogame_ids[game.title]) + '"}' recent_placements = sgg_client.query(recent_placements_query, recent_placements_vars)['data']['user']['events']['nodes'] # print(json.dumps(recent_placements, indent=4)) del_inds = [] # Calculate top percentage based on tournament placements, and add to dict: for i, placement in enumerate(recent_placements): # Identify indices of placements of wrong videogame: # if placement['videogame']['name'] != game.title: # print(placement['tournament']['name'], 'is not', game.title, ', it is', placement['videogame']['name']) # del_inds.append(i) # continue print(placement, '\n\n') # Deal with tournaments where standings are null: if not placement['standings']: print('Null alert!') placement['topPerc'] = 'null' continue # del_inds.append(i) # If the standings is not null but the nodes is, then the player dropped out and didn't compete: elif not placement['standings']['nodes']: print('Did not compete!') placement['topPerc'] = 'did not compete' else: placement['topPerc'] = round((placement['standings']['nodes'][0]['placement'] / placement['numEntrants']) * 100) # Filter out placements not for this videogame: # recent_placements = [elem for i, elem in enumerate(recent_placements) if i not in del_inds] # recent_placements = recent_placements[:10] # Cap number of placements displayed response = {'placements': recent_placements} return HttpResponse(json.dumps(response))
def recent_sets_async(request): """Get recent sets of given player using the smashgg API. Called by Ajax.""" if not request.is_ajax() or not request.method == 'POST': return HttpResponseNotAllowed(['POST']) game = get_object_or_404(Game, pk=request.POST['game_id']) user_slug = request.POST['user_slug'] print("Recent sets async") print(request.POST) # Get slug of opponent if not blank: if ('slug2' in request.POST) and request.POST['slug2']: opponent_slug = request.POST['slug2'] set_num = 100 else: opponent_slug = '' set_num = 80 # Query for finding results of last 10 tournament sets of user, given user slug: recent_sets_query = ''' query SetHistoryQuery($slug: String, $setNum: Int) { user(slug: $slug) { player { gamerTag sets(page: 1, perPage: $setNum, filters: { hideEmpty: true }) { pageInfo { total } nodes { completedAt displayScore event { name videogame { name } tournament { name } } fullRoundText lPlacement winnerId slots(includeByes: false) { entrant{ id name } } } } } } }''' recent_sets_query_vars = '{"slug": "' + user_slug + '", "setNum": "' + str(set_num) + '"}' # Get recent sets of given player: recent_sets = sgg_client.query(recent_sets_query, recent_sets_query_vars)['data']['user'] # If user key points to null, then player slug doesn't exist; return blank data: if recent_sets is None: print('User is null!') return HttpResponse(json.dumps({'recent_sets': 'null'})) recent_sets = recent_sets['player'] user_gamertag = recent_sets['gamerTag'] i = 0 del_inds = [] win_count = 0 # Find out whether given player was the winner in each set, and add 'win' key to each set entry: for i, p_set in enumerate(recent_sets['sets']['nodes']): # Collate indices of sets not for this game: if p_set['event']['videogame']['name'] != game.title: print(p_set['event']['tournament']['name'], 'is not', game.title, ', it is', p_set['event']['videogame']['name']) del_inds.append(i) continue # If set is a DQ (disqualification), then mark this index for deletion: if p_set['displayScore'] == 'DQ': print('Set', i, 'is a DQ') del_inds.append(i) continue # If entrant id of first entrant == winnerId, AND user gamertag is substring of first entrant, then they won # Note: Checking that user_gamertag is in entrant name is to avoid discrepancies between gamertags from user # not containing sponsors, e.g. 'Hungrybox' and 'Liquid | Hungrybox. This could cause issues if one player's # gamertag was a substring of their opponent's... # TODO: Come up with more robust way of identifying winner if (p_set['winnerId'] == p_set['slots'][0]['entrant']['id']) & ( user_gamertag in p_set['slots'][0]['entrant']['name']): p_set['win'] = 'true' win_count += 1 # Same as above but in the event of the winner being the second listed entrant: elif (p_set['winnerId'] == p_set['slots'][1]['entrant']['id']) & ( user_gamertag in p_set['slots'][1]['entrant']['name']): p_set['win'] = 'true' win_count += 1 else: p_set['win'] = 'false' # Add win count to dictionary: recent_sets['winCount'] = win_count # Filter out sets not for this videogame: recent_sets['sets']['nodes'] = \ [elem for i, elem in enumerate(recent_sets['sets']['nodes']) if i not in del_inds] # recent_sets['sets']['nodes'] = recent_sets['sets']['nodes'][:15] # Cap displayed sets to 15 # print(json.dumps(recent_sets, indent=4)) response = {'recent_sets': recent_sets} return HttpResponse(json.dumps(response))