def _prepare(self, id_or_name):
     """
     Get's the Teams from a live game by Summoner Name or from an old Match by Match ID
     :param id_or_name: either a Summoner Name or a Match ID
     :return: iterator of the prepared teams; if not exits None
     """
     # Setting the Api key for Cassiopeia and the default region
     cass.set_riot_api_key(self.key)
     cass.set_default_region('EUW')
     if type(id_or_name) is str:
         summoner = cass.get_summoner(name=id_or_name, region='EUW')
         try:
             current_game = summoner.current_match()
         except Exception as e:
             print(str(e))
             return None
     else:
         try:
             current_game = cass.get_match(id_or_name, region='EUW')
         except Exception as e:
             print(str(e))
             return None
     if current_game.mode == cass.data.GameMode.aram:
         print('there are no lanes in Aram')
         return None
     # Preparing the participants per team
     for team in current_game.teams:
         yield self._prepare_team(team), team
Beispiel #2
0
def aggregate_batched_matches(batch, region, summoner_id):
    try:
        # init
        cass.get_realms(region=region).load()

        #old = time.time() * 1000

        matchlist = []
        for m_id in batch:
            match_id = int(m_id)
            matchlist.append(cass.get_match(id=match_id, region=region))

        pool = Pool(len(matchlist))
        pool.map(load_match, matchlist)
        pool.close()
        pool.join()
        #print("fetch:", time.time()*1000 - old)

        #old = time.time() * 1000
        aggregate_user_matches(matchlist, summoner_id, region)
        #print("total:", time.time()*1000 - old)

    except Exception as e:
        if pool is not None:
            pool.close()
        log.warn("Failed to aggregate batched matches", e, stack_info=True)
        aggregate_batched_matches.retry(exc=e)
Beispiel #3
0
def collectMatches():
    summoner = Summoner(name="Ung5r",
                        region="NA")  # A default summoner to pull matches from
    patchNo = Patch.from_str('8.2', region="NA")

    # Create some sorted lists to store the IDs of players and matches being analyzed.
    # Match info can only be pulled on a player basis so we'll have to pull each player
    # from a match to then get further match info.
    unpulledSummonerIDS = SortedList([summoner.id])
    pulledSummonerIDS = SortedList()
    unpulledMatchIDS = SortedList()
    pulledMatchIDS = SortedList()

    matchesList = []

    while unpulledSummonerIDS and len(pulledMatchIDS) < 5000:
        newSummonerID = random.choice(unpulledSummonerIDS)
        try:
            newSummoner = Summoner(id=newSummonerID, region="NA")
        except:
            print("Unable to retrieve new summoner, retrying in 10s")
            time.sleep(10)
            newSummoner = Summoner(id=newSummonerID, region="NA")
        matches = filterHistory(newSummoner, patchNo)
        try:
            unpulledMatchIDS.update([
                match.id for match in matches
                if match.id not in unpulledMatchIDS
            ])
        except:
            print("Unable to add to unpulled matches, retrying in 10s")
            time.sleep(10)
            unpulledMatchIDS.update([
                match.id for match in matches
                if match.id not in unpulledMatchIDS
            ])
        unpulledSummonerIDS.remove(newSummonerID)
        pulledSummonerIDS.add(newSummonerID)

        while unpulledMatchIDS:
            newMatchID = random.choice(unpulledMatchIDS)
            try:
                newMatch = Match(id=newMatchID, region="NA")
            except:
                print("Unable to retrieve new match, retrying in 10s")
                time.sleep(10)
                newMatch = Match(id=newMatchID, region="NA")
            for participant in newMatch.participants:
                if participant.summoner.id not in pulledSummonerIDS and participant.summoner.id not in unpulledSummonerIDS:
                    unpulledSummonerIDS.add(participant.summoner.id)
            unpulledMatchIDS.remove(newMatchID)
            if newMatchID not in pulledMatchIDS:
                pulledMatchIDS.add(newMatchID)

    # Populate the list of matches by match ID
    for entry in pulledMatchIDS:
        matchesList.append(kass.get_match(id=entry, region="NA"))

    return matchesList
Beispiel #4
0
def test_match_correct_return():
    match_history = cassiopeia.get_match_history(summoner=SUMMONER_NAME, region="NA")
    first_match = match_history[0]

    match_from_id = cassiopeia.get_match(id=first_match.id, region="NA")

    assert isinstance(match_from_id, cassiopeia.Match)
    assert first_match.id == match_from_id.id
    assert first_match == match_from_id
def get_match_data(gameId: str, region: str, gameDuration):
    match = cass.get_match(gameId, region)
    match_object = Match
    match_object.properties["gameId"] = gameId
    match_object.properties["blueWins"] = match.blue_team.win

    #Get data for blue team
    get_team_data(match_object, match.blue_team, gameDuration, "blue", region)
    get_team_data(match_object, match.red_team, gameDuration, "red", region)

    return match_object
Beispiel #6
0
def test_match_correct_return():
    match_history = cassiopeia.get_match_history(SUMMONER_NAME)
    first_match = match_history[0]
    first_match_data = first_match._data[cassiopeia.core.match.MatchData]._dto

    match_from_id = cassiopeia.get_match(first_match.id)
    match_from_id_data = match_from_id._data[cassiopeia.core.match.MatchData]._dto

    assert isinstance(match_from_id, cassiopeia.Match)
    #assert first_match_data == match_from_id_data
    assert first_match.id == match_from_id.id
Beispiel #7
0
def aggregate_batched_matches(batch, region, summoner_id):
    # init
    cass.get_realms(region=region).load()

    matchlist = []
    for m_id in batch:
        match_id = int(m_id)
        matchlist.append(cass.get_match(id=match_id, region=region))

    #pool.map(load_match, matchlist)

    loop = asyncio.get_event_loop()
    tasks = [asyncio.ensure_future(fetch(m)) for m in matchlist]
    loop.run_until_complete(asyncio.wait(tasks))
def main():
    print("Pulling data...")
    champion_roles = pull_data()
    print("Finished pulling data.")
    print()

    # Pull a summoner's most recent match using Cassiopeia
    match = cass.get_match(id=3344134840, region="NA")
    team = match.blue_team
    # Get the roles
    roles = get_team_roles(team, champion_roles)

    # Print the results
    print({role.name: champion.name for role, champion in roles.items()})
Beispiel #9
0
def get_match(match_id):
    match = cass.get_match(id=int(match_id))
    red_team = match.red_team
    blue_team = match.blue_team
    red_team_stats = [
        sum(map(lambda participant: participant.stats.kills, red_team.participants)),
        sum(map(lambda participant: participant.stats.deaths, red_team.participants)),
        sum(map(lambda participant: participant.stats.assists, red_team.participants)),
        sum(map(lambda participant: participant.stats.gold_spent, red_team.participants)),
        sum(map(lambda participant: participant.stats.total_minions_killed, red_team.participants)),
        sum(map(lambda participant: participant.stats.gold_spent // match.duration.seconds * 60,
                red_team.participants)),
        sum(map(lambda participant: participant.stats.total_damage_dealt, red_team.participants)),
        sum(map(lambda participant: participant.stats.total_heal, red_team.participants)),
        sum(map(lambda participant: participant.stats.damage_dealt_to_turrets, red_team.participants))
    ]
    blue_team_stats = [
        sum(map(lambda participant: participant.stats.kills, blue_team.participants)),
        sum(map(lambda participant: participant.stats.deaths, blue_team.participants)),
        sum(map(lambda participant: participant.stats.assists, blue_team.participants)),
        sum(map(lambda participant: participant.stats.gold_spent, blue_team.participants)),
        sum(map(lambda participant: participant.stats.total_minions_killed, blue_team.participants)),
        sum(map(lambda participant: participant.stats.gold_spent // match.duration.seconds * 60,
                blue_team.participants)),
        sum(map(lambda participant: participant.stats.total_damage_dealt, blue_team.participants)),
        sum(map(lambda participant: participant.stats.total_heal, blue_team.participants)),
        sum(map(lambda participant: participant.stats.damage_dealt_to_turrets, blue_team.participants))
    ]

    duration = match.duration
    return render_template(
        'match.html',
        red_team={
            'name': 'Красная команда',
            'participants': red_team.participants,
            'stats': red_team_stats
        },
        blue_team={
            'name': 'Синяя команда',
            'participants': blue_team.participants,
            'stats': blue_team_stats
        },
        match_duration=duration,
        str=str,
        round=round,
        sorted=sorted,
        filter=filter,
        sort_key=lambda item: item.name,
        filter_key=lambda item: item is not None
    )
Beispiel #10
0
def matches():
    if request.method == 'GET':
        return render_template(
            'matches.html'
        )
    elif request.method == 'POST':
        match_id = request.form.get('match_id')
        try:
            if cass.get_match(id=int(match_id)):
                return redirect(f'match/{match_id}')
        except:
            return render_template(
                'matches.html',
                message="Неверный id матча!"
            )
Beispiel #11
0
def get_match_timeline(request):
    region = normalize_region(request.GET['region'])
    match_id = int(request.GET['match_id'])

    try:
        match = cass.get_match(id=match_id, region=region)
        pool = Pool(2)
        pool.map(load_cass_obj, [match, match.timeline])
        pool.close()
        pool.join()
    except:
        pool.close()
        return HttpResponse("Match does not exist", status=404)

    response = {}
    response['timeline'] = ujson.loads(match.timeline.to_json())
    response['match'] = ujson.loads(match.to_json())

    return JsonResponse(response)
Beispiel #12
0
def write_matches(summoner_name, n):
    """
    writes n matches as csv files containing events or frames
    :param summoner_name: str of summoner name
    :param n: number of matches you want
    :return: void
    """
    participant_frames_df = pd.DataFrame()
    events_df = pd.DataFrame()

    summoner = cass.get_summoner(name="Faker")
    match_history = cass.get_match_history(summoner=summoner)

    i = 0
    for match in match_history:
        match_id = match.id
        match = cass.get_match(id=match_id)

        p_wins = get_participant_wins(match)

        pf_df, e_df = unpack_timeline(match.timeline, p_wins)
        pf_df['summoner'] = summoner_name
        e_df['summoner'] = summoner_name
        pf_df['match_id'] = match_id
        e_df['match_id'] = match_id

        participant_frames_df = pd.concat([participant_frames_df, pf_df])
        events_df = pd.concat([events_df, e_df])

        i += 1
        if i >= n:
            break

    participant_frames_df.to_csv("participant_frames.csv",
                                 header=True,
                                 index=False)
    events_df.to_csv("events.csv", header=True, index=False)
Beispiel #13
0
print("{accountId}: {name} is a level {level} summoner on the {region} server."\
      .format(accountId=summoner.id,
              name=summoner.name,
              level=summoner.level,
              region=summoner.region)
     )

#
# get Faker's match history his last match

# faker_match_history = summoner.match_history
# print("His match history is length: {}".format(len(faker_match_history)))

# faker_last_match_id = faker_match_history[0].id
faker_last_match_id = 2842707542
faker_last_match = cass.get_match(faker_last_match_id)

last_match_timeline = faker_last_match.timeline
print("last match frames: {}".format(len(last_match_timeline.frames)))
print("match length: {}".format(faker_last_match.duration))

last_match_frames = last_match_timeline.frames

# make a data folder
from os import path, getcwd, mkdir
data_folder_name = "data"
pwd = getcwd()
full_path = path.join(pwd, data_folder_name)
if not path.isdir(full_path):
    mkdir(full_path)
Beispiel #14
0
# Check if matchFile already exists, if so, error out
try:
    f = open(matchFileName)
except:
    print("matchFile named \"" + str(matchFileName) + "\" will be created")
else:
    sys.exit("ERROR: matchFile named \"" + str(matchFileName) +
             "\" already existed. Exiting...")

#Load Matches into a file denoted by matchFileName. that can be loaded later on
matchCount = 0
curr_match_id = starting_match_id
while matchCount < maxMatchCount:
    time.sleep(sleepTime)
    match = cass.get_match(curr_match_id)
    #If a match exists
    if match.exists:
        #If the match is a 5x5 soloque ranked mode game, add the match to the list
        if match.mode == cass.data.GameMode.classic and match.queue == cass.data.Queue.ranked_solo_fives:
            print("(" + str(matchCount + 1) + " Matches saved) Match id#" +
                  str(match.id) + " being added...")
            #Load Existing Matches List from matchFile
            try:
                matchFile = open(matchFileName, 'rb')
                matches = pickle.load(matchFile)
                matchFile.close()
            except:
                matchFile = open(matchFileName, 'wb')
                matchFile.close()
                matches = []
Beispiel #15
0
def get_match_data(match_id, region="NA"):
    """Return LoL match data from the API. At random chooses red or blue team to prevent any autocorrelation of data.

    Keyword arguments:
    match_id -- the league api match data
    region -- the region to draw from (default NA)

    Returns:
    A dictionary of:

    match_id -- same as argument

    side -- red or blue side
    top_id -- the account id of the top laner on this side
    jun_id -- jungler
    mid_id -- mid laner
    adc_id -- bot carry
    sup_id -- support

    top_champ -- the champion id played top
    etc

    top_vs -- the vision score top
    etc

    top_cs_10 -- top cs difference at 10
    top_cs_20 -- same at 20
    top_xp_10 -- xp diff at 10
    top_cs_20 -- same at 20

    etc for other roles

    first_brick -- boolean for first tower
    first_blood -- first blood
    etc for herald, dragon, baron, inhib

    num_dragons -- number of dragons
    etc for barons, towers, inhibs

    result -- 1 for win 0 for loss
    """

    entry = dict()
    entry["id"] = [match_id]

    match = cass.get_match(id = match_id, region="NA")
    
    side = np.random.choice(["red","blue"])
    
    entry["side"] = side
    
    if side == "red":
        team = match.red_team

    if side == "blue":
        team = match.blue_team

    players = team.participants

    for num, player in enumerate(players):
        entry["player"+str(num)+"_id"] = [player.summoner.account_id]
        entry["player"+str(num)+"_role"] = [str(player.lane)+" "+str(player.role)]
        entry["player"+str(num)+"_champ"] = [player.champion.id]
        entry["player"+str(num)+"_vs"] = [player.stats.vision_score]

    entry["first_brick"] = [team.first_tower]
    entry["first_blood"] = [team.first_blood]
    entry["first_herald"] = [team.first_rift_herald]
    entry["first_dragon"] = [team.first_dragon]
    entry["first_baron"] = [team.first_baron]
    entry["first_inhib"] = [team.first_inhibitor]

    entry["num_dragons"] = [team.dragon_kills]
    entry["num_barons"] = [team.baron_kills]
    entry["num_towers"] = [team.tower_kills]
    entry["num_inhibs"] = [team.inhibitor_kills]

    entry["result"] = [team.win]

    return entry
Beispiel #16
0
async def summoner(ctx, name: str = None):
    await ctx.message.delete()
    key = os.environ.get('RIOT')
    cass.set_riot_api_key(key)
    lvl = ''
    rank = 'Нет ранга'
    mainer = ''
    win1 = ''
    win2 = ''
    win3 = ''
    win4 = ''
    ch1 = ''
    ch2 = ''
    ch3 = ''
    ch4 = ''
    wins = ''
    if name == None:
        await ctx.send('Введите ник призывателя')
    else:
        summoner = cass.get_summoner(region='RU', name=name)
        lvl = str(summoner.level)
        try:
            rank = str(summoner.league_entries[0].tier) + ' ' + str(
                summoner.league_entries[0].division)
        except:
            pass
        mainer = str(summoner.champion_masteries[0].champion.name)
        for x in cass.get_match(summoner.match_history[0].id,
                                region='RU').red_team.participants:
            if x.summoner.name == summoner.name:
                ch1 = '(' + x.champion.name + ')'
                if cass.get_match(summoner.match_history[0].id,
                                  region='RU').red_team.win == False:
                    win1 = ch1 + "Поражение:red_circle:"
                else:
                    win1 = ch1 + 'Победа:green_circle:'
        for x in cass.get_match(summoner.match_history[0].id,
                                region='RU').blue_team.participants:
            if x.summoner.name == summoner.name:
                ch1 = '(' + x.champion.name + ')'
                if cass.get_match(summoner.match_history[0].id,
                                  region='RU').blue_team.win == False:
                    win1 = ch1 + "Поражение:red_circle:"
                else:
                    win1 = ch1 + 'Победа:green_circle:'
        for x in cass.get_match(summoner.match_history[1].id,
                                region='RU').red_team.participants:
            if x.summoner.name == summoner.name:
                ch2 = '(' + x.champion.name + ')'
                if cass.get_match(summoner.match_history[1].id,
                                  region='RU').red_team.win == False:
                    win2 = ch2 + "Поражение:red_circle:"
                else:
                    win2 = ch2 + 'Победа:green_circle:'
        for x in cass.get_match(summoner.match_history[1].id,
                                region='RU').blue_team.participants:
            if x.summoner.name == summoner.name:
                ch2 = '(' + x.champion.name + ')'
                if cass.get_match(summoner.match_history[1].id,
                                  region='RU').blue_team.win == False:
                    win2 = ch2 + "Поражение:red_circle:"
                else:
                    win2 = ch2 + 'Победа:green_circle:'
        for x in cass.get_match(summoner.match_history[2].id,
                                region='RU').red_team.participants:
            if x.summoner.name == summoner.name:
                ch3 = '(' + x.champion.name + ')'
                if cass.get_match(summoner.match_history[2].id,
                                  region='RU').red_team.win == False:
                    win3 = ch3 + "Поражение:red_circle:"
                else:
                    win3 = ch3 + 'Победа:green_circle:'
        for x in cass.get_match(summoner.match_history[2].id,
                                region='RU').blue_team.participants:
            if x.summoner.name == summoner.name:
                ch3 = '(' + x.champion.name + ')'
                if cass.get_match(summoner.match_history[2].id,
                                  region='RU').blue_team.win == False:
                    win3 = ch3 + "Поражение:red_circle:"
                else:
                    win3 = ch3 + 'Победа:green_circle:'
        for x in cass.get_match(summoner.match_history[3].id,
                                region='RU').red_team.participants:
            if x.summoner.name == summoner.name:
                ch4 = '(' + x.champion.name + ')'
                if cass.get_match(summoner.match_history[3].id,
                                  region='RU').red_team.win == False:
                    win3 = ch4 + "Поражение:red_circle:"
                else:
                    win3 = ch4 + 'Победа:green_circle:'
        for x in cass.get_match(summoner.match_history[3].id,
                                region='RU').blue_team.participants:
            if x.summoner.name == summoner.name:
                ch4 = '(' + x.champion.name + ')'
                if cass.get_match(summoner.match_history[3].id,
                                  region='RU').blue_team.win == False:
                    win4 = ch4 + "Поражение:red_circle:"
                else:
                    win4 = ch4 + 'Победа:green_circle:'
    wins = win1 + '\n' + win2 + '\n' + win3 + '\n' + win4
    t = 'Информация о призывателе: ' + name
    embed = discord.Embed(title=t, color=0xf5f5f5)
    embed.add_field(name='**Ранг:**', value=rank, inline=True)
    embed.add_field(name='**Лвл:**', value=lvl, inline=True)
    embed.add_field(name='**Мейн:**', value=mainer, inline=True)
    embed.add_field(name='**Последние игры:**', value=wins, inline=True)
    embed.set_thumbnail(url=summoner.profile_icon.url)
    embed.set_footer(
        text='LeagueOfBots',
        icon_url=
        'https://cdn.discordapp.com/attachments/500621541546000388/709146278050922596/1568968178125834341.jpg'
    )
    await ctx.send(embed=embed)
Beispiel #17
0
    """
    riot_api_key = "RGAPI-2f774048-8d86-4c98-a317-5230f8b1b898"
    make_data_folder()
    cass.set_riot_api_key(riot_api_key)
    cass.set_default_region("NA")

    summoner = cass.get_summoner(name="Faker")

    match_history = summoner.match_history

    csv_handle = open("data/faker-stats.csv", "w+")
    csv_writer = csv.writer(csv_handle)
    csv_writer.writerow(["match_id", "rowlen"] + stats)

    for match in match_history:
        match = cass.get_match(match.id)
        match_json = json.loads(match.to_json())
        participants_list = match_json["participants"]
        if len(participants_list) < 2:
            continue
        faker_stats = [
            player for player in participants_list
            if player["summonerName"] == "Faker"
        ][0]
        row = []
        for stat in stats:
            row.append(faker_stats[stat])

        row = [str(match.id), str(len(row))] + row
        csv_writer.writerow(row)
Beispiel #18
0
    for player in team.participants:
        champion_names.append(player.champion.name)
        champion_keys.append(player.champion.id)
    return [champion_names, champion_keys]


# This is a completely arbitrary starting value
match_id = 3229026157

# Loop counter that only increments when a match exists
successful_matches = 0
# DATABASE INSERTIONS
while successful_matches < 10000:
    winning_champions = []
    losing_champions = []
    match = cass.get_match(match_id)

    # Check if match_id is valid
    # filter out bot matches
    if match.exists and match.mode.value == "CLASSIC" and match.map.id == 11 and (
            match.queue.id in (400, 420, 430, 440)):
        # Collect teams
        blue_team = get_champions(match.blue_team)

        red_team = get_champions(match.red_team)

        # For Blue Team wins
        if match.blue_team.win:
            winning_champions = blue_team
            losing_champions = red_team
        # For Red Team wins
Beispiel #19
0
 def getMatch(self, match_id):
     return cass.get_match(match_id)
Beispiel #20
0
import cassiopeia as cass
import requests
import ujson

#####################################################################################################################################################################
## Settings #########################################################################################################################################################
#####################################################################################################################################################################

settDefault = cass.get_default_config()
print(settDefault)

#####################################################################################################################################################################
## getMatchByID #####################################################################################################################################################
#####################################################################################################################################################################

cass.get_match()
Beispiel #21
0
def getRedSideByMatch(id):
    return cass.get_match(id).red_team.to_json()
Beispiel #22
0
        # Pickle data to disk
        print("Pickling...")
        print("Matches analyzed so far: " + str(i))
        print("Unique drafts analyzed: " + str(len(data)))
        # print("Rejected: " + str(rejected))
        with open('../input/data.pickle', 'wb') as handle:
            pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL)

    # Don't waste time accessing the match if we know it's old.
    if int(
            ids[i]
    ) < 2893574694:  # Smaller than this and the match is definitely old.
        continue

    # print(ids[i])
    match = cass.get_match(int(ids[i]))
    # print(match)
    # print(match.patch, match.is_remake, match.blue_team)
    # print(str(match.patch))

    if str(match.patch) not in ["8.24", "8.23", "8.22",
                                "8.21"]:  # Recent games only
        print(str(i) + " – BAD (old)")
        print(str(match.patch))
        continue
    if match.is_remake:  # No remakes
        print(str(i) + " – BAD (remake)")
        continue

    if match.blue_team.win:
        winning_team = match.blue_team
Beispiel #23
0
def getBlueSideByMatch(id):
    return cass.get_match(id).blue_team.to_json()
Beispiel #24
0
def getGameByMatchID(id):
    return cass.get_match(id).to_json()
Beispiel #25
0
def get_match_records(filename: str, start_id: int, max_records: int,
                      sleep_time: int) -> None:
    """Retrieves the first n match records that are valid and is also a '5v5 ranked solo queue' game mode
    from the Riot API.

    Args:
        filename: Name of the file to save the League of Legends match records
        start_id: Match ID to begin looking from (will decrement from said ID number)
        max_records: Total number of successful records to be retrieved
        sleep_time: Number of seconds to wait between each API call

    Returns:
        Does not return anything. However, the data will be written to the filename as specified.
    """
    # Remember to remove the API key when pushing commits to GitHub
    cassiopeia.set_riot_api_key('RGAPI-KEY-GOES-HERE')
    cassiopeia.set_default_region('NA')

    # Iterate matches by ID number and only store matches that are of the "5v5 solo queue ranked" game mode
    read_records = 0
    current_id = start_id
    while read_records < max_records:
        # Cassiopeia API wrapper handles rate-limiting, but apparently its not suited for a personal API key
        time.sleep(sleep_time)

        match = cassiopeia.get_match(current_id)
        if not match.exists:
            print(f"Match ID {match.id} does not exist.")
        elif match.mode != cassiopeia.data.GameMode.classic or match.queue != cassiopeia.data.Queue.ranked_solo_fives:
            print(
                f"Match ID {match.id} does not match criteria of '5v5 ranked solo queue'."
            )
        else:
            print(
                f"Match ID {match.id} added. ({read_records + 1} matches out of {max_records} saved to disk) "
            )

            # a+ is similar to r+ to read and write to a file, but a+ also creates the file if it is missing and
            # appends additional text to the end of the file
            with open(filename, 'a+', newline='', encoding='utf-8') as file:
                csv_writer = csv.writer(file)
                # Write header once at the beginning of the file
                if read_records == 0:
                    csv_writer.writerow([
                        "id", "version", "side", "win", "ban1", "ban2", "ban3",
                        "ban4", "ban5", "champion1", "champion2", "champion3",
                        "champion4", "champion5", "tower_kills",
                        "inhibitor_kills", "dragon_kills", "rift_herald_kills",
                        "baron_kills", "first_tower", "first_inhibitor",
                        "first_dragon", "first_rift_herald", "first_baron"
                    ])

                # Write blue team information into csv
                bteam_info = get_team_stats('blue', match)
                csv_writer.writerow(bteam_info)

                # Write red team information into csv
                rteam_info = get_team_stats('red', match)
                csv_writer.writerow(rteam_info)
            read_records += 1  # This should be in the else statement
        current_id -= 1  # This should not be within the else statement