def get_match(reference): """ Try to pull the referenced match from Riot's servers. If we can an error that we should retry, we will. If it fails a second time, we just skip it. """ try: return riotapi.get_match(reference) except APIError as error: # Try Again Once if error.error_code in [500]: try: return riotapi.get_match(reference) except APIError as another_error: if another_error.error_code in [500, 400, 404]: pass else: raise another_error # Skip elif error.error_code in [400, 404]: pass # Fatal else: raise error print(master.name) for index, master in enumerate(masters): print(index, master)
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(True) key = 'b7190b84-484d-4cc7-88ca-8e2b90fb7f56' # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) # Pull the data for one of Dyrus' matches. match = riotapi.get_match(2034758953) # Create a namedtuple called "Info" that is used to store some information about participants. # We use a namedtuple because it allows for a clear way to access this data later in the script. Info = namedtuple("Info", ["side", "role", "lane"]) # Loop through the participants in this match and record which side they played on (blue or red), # which role they played, and what lane they played in. mapping = {} for participant in match.participants: mapping[participant.champion.name] = Info(participant.side.name, participant.timeline.role.value, participant.timeline.lane.value) print() # Print out the information we just collected. for champion, info in sorted(mapping.items(), key=lambda tuple: (tuple[1].side, tuple[1].lane)): print("{0}: {1}".format(champion, info))
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(True) os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428" key = os.environ[ "DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) # Pull the data for one of Dyrus' matches. match = riotapi.get_match(2034758953) # Create a namedtuple called "Info" that is used to store some information about participants. # We use a namedtuple because it allows for a clear way to access this data later in the script. Info = namedtuple("Info", ["side", "role", "lane"]) # Loop through the participants in this match and record which side they played on (blue or red), # which role they played, and what lane they played in. mapping = {} for participant in match.participants: mapping[participant.champion.name] = Info( participant.side.name, participant.timeline.role.value, participant.timeline.lane.value) print() # Print out the information we just collected. for champion, info in sorted(mapping.items(), key=lambda tuple: (tuple[1].side, tuple[1].lane)): print("{0}: {1}".format(champion, info))
def amassSummoners(targetLeague, seedSummoner, returnDict, threshold=110): '''Will take a target league and a starting seed and use the seed to do a branching search for summoners that have reached the target league. If threshold not met, runs recursively on a random summoner already found. Returns a dict of summoner objects {Summoner name : Summoner object} ''' if (type(seedSummoner) == str): print "Searching for summoners related to %s..." % (seedSummoner) seed = riotapi.get_summoner_by_name(seedSummoner) else: print "Searching for summoners related to %s..." % (seedSummoner.name) seed = seedSummoner matchList = riotapi.get_match_list(seed, ranked_queues=QUEUES, seasons="SEASON2015") counter = 0 summonerDict = returnDict for i in range(len(matchList)): try: #Had issues with get_match request failing so wrapped in a try block currentMatch = riotapi.get_match(matchList[i]) for participant in currentMatch.participants: try: if (participant.previous_season_tier.name == targetLeague) & (participant.summoner_name not in summonerDict): summonerDict[participant.summoner_name] = participant.summoner counter += 1 print "##### Target found ######" except ValueError: continue if counter >= 10: break #Break after 10 summoners grabbed to increase spread except: print "Summoner pull failed." if len(summonerDict.keys()) < threshold: print "Current no. of summoners in %s: %d" % (targetLeague, len(summonerDict.keys())) summonList = summonerDict.values() summonerDict = amassSummoners(targetLeague, summonList[counter/2], summonerDict) return summonerDict
def collectMatches(targetLeague, summonerList): '''Given a list of summoner objects and a target league, will search through the match history of each summoner for games where the majority of participants are in the target league. If found, adds to the matchDict. Will only pull 10 games per summoner Returns a dict of Match objects { MatchID : Match Vector} ''' matchDict = {} deathDict = {} for i in range(len(summonerList)): print "--------------------------------" counter = 0 searched = 100 try: matchList = riotapi.get_match_list(summonerList[i], num_matches=100, ranked_queues=QUEUES, seasons="SEASON2015") except: continue print "Looking at %s's match history..." % (summonerList[i].name) for i in range(len(matchList)): try: currentMatch = riotapi.get_match(matchList[i]) majorityDict = { 'unranked': 0, 'bronze': 0, 'silver': 0, 'gold': 0, 'platinum': 0, 'diamond': 0, 'master': 0, 'challenger': 0 } for participant in currentMatch.participants: try: majorityDict[ participant.previous_season_tier.name] += 1 except ValueError: majorityDict['bronze'] += 1 if (majorityDict[targetLeague] > 3) & (currentMatch.id not in matchDict): matchDict[currentMatch.id] = parseMatch.processMatch( currentMatch) deathDict[currentMatch.id] = parseMatch.getDeaths( currentMatch) counter += 1 if counter == 10: #Break after 10 games retrieved searched = i + 1 break except: print "Match pull failed." print "%d found out of %d searched" % (counter, searched) print "Current no. of %s matches: %d" % (targetLeague, len(matchDict.values())) return matchDict, deathDict
def get_match(reference): try: riotapi.get_match(reference) except APIError as e: # Try Again Once if(e.error_code in [500]): try: riotapi.get_match(reference) except APIError as e2: if(e2.error_code in [500, 400, 404]): pass else: raise e2 # Skip elif(e.error_code in [400, 404]): pass # Fatal else: raise e
def get_match(reference): try: riotapi.get_match(reference) except APIError as e: # Try Again Once if (e.error_code in [500]): try: riotapi.get_match(reference) except APIError as e2: if (e2.error_code in [500, 400, 404]): pass else: raise e2 # Skip elif (e.error_code in [400, 404]): pass # Fatal else: raise e
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(False) os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428" key = os.environ["DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.eager) gigglepuss = riotapi.get_summoner_by_name("GigglePuss") match_list = riotapi.get_match_list(gigglepuss) sub_list = match_list[:10] matchid = [] versionpatch = [] maptype = [] queue = [] p1name = [] p1side = [] p1champ = [] p1lane = [] p1role = [] p1gold = [] p1win = [] for i in range(len(sub_list)): match = riotapi.get_match(match_list[i]) matchid.append(match.id) versionpatch.append(match.version) maptype.append(match.map) queue.append(match.queue) p1name.append(match.participants[0].summoner_name) p1side.append(match.participants[0].side) p1champ.append(match.participants[0].champion.name) p1lane.append(match.participants[0].timeline.lane) p1role.append(match.participants[0].timeline.role) p1gold.append(match.participants[0].stats.gold_earned) p1win.append(match.participants[0].stats.win) filename = "test_data.csv" columns = ['matchid', 'versionpatch', 'maptype', 'queue', 'p1name', 'p1side', 'p1champ', 'p1lane', 'p1role', 'p1gold', 'p1win'] df = pd.DataFrame([matchid, versionpatch, maptype, queue, p1name, p1side, p1champ, p1lane, p1role, p1gold, p1win], index = columns) df = df.T df.to_csv(filename) print(df)
def main(): # Setup riotapi riotapi.set_region(REGION) riotapi.print_calls(True) key = #redacted # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) # Load and connect to your database. (Comment this code to use local memory. Don't forget to comment db.close() below too.) db = SQLAlchemyDB("sqlite", host="", database=OUTFILE, username="", password="") riotapi.set_data_store(db) # We will seed with all the summoners in Master's tier unpulled_summoners = deque(entry.summoner for entry in riotapi.get_master()) print("Pulled Master tier for seeding. Got {0} summoners.".format(len(unpulled_summoners))) # We need this so that we don't get a recursive loop of summoners pulled_summoners = deque() gather_start = datetime(2015, 1, 1) # since we have data for all of 2015 times_crashed = 0 #store number of times we've had the NoneType error times_looped = 0 #store number of times we've made a call as a rough proxy for when to stop the script while len(unpulled_summoners) > 0: summoner = unpulled_summoners.popleft() for match_reference in summoner.match_list(begin_time=gather_start): # If you are connected to a database, the match will automatically be stored in it without you having to do anything. # Simply pull the match, and it's in your database for whenever you need it again! # If you pull a match twice, the second time it will be loaded from the database rather than pulled from Riot # and therefore will not count against your rate limit. This is true of all datatypes, include Summoner. match = riotapi.get_match(match_reference) if match is None: # If the match still fails to load, continue on to the next one continue print("Stored {0} in my database".format(match)) for participant in match.participants: try: if participant.summoner not in unpulled_summoners and participant.summoner not in pulled_summoners: unpulled_summoners.append(participant.summoner) except TypeError: times_crashed += 1 print("I've run into the NoneType error {} times so far!".format(times_crashed)) pass times_looped += 1 print("I have now looped {} times.".format(times_looped)) if times_looped > LOOPS: exit("I have looped {} times and am done now.".format(times_looped)) pulled_summoners.append(summoner) db.close()
def get_match(reference): """ Try to pull the referenced match from Riot's servers. If we can an error that we should retry, we will. If it fails a second time, we just skip it. """ try: return riotapi.get_match(reference) except APIError as error: # Try Again Once if error.error_code in [500]: try: return riotapi.get_match(reference) except APIError as another_error: if another_error.error_code in [500, 400, 404]: pass else: raise another_error # Skip elif error.error_code in [400, 404]: pass # Fatal else: raise error
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(False) os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428" key = os.environ["DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.eager) gigglepuss = riotapi.get_summoner_by_name("GigglePuss") match_list = riotapi.get_match_list(gigglepuss) match = riotapi.get_match(match_list[0]) print(" Match ID: {0}".format(match.id)) print(" Version/Patch: {0}".format(match.version)) print(" Map: {0}".format(match.map)) print(" Queue: {0}".format(match.queue)) print() # Print participant information (not summoner information) for participant in match.participants: print(" {0}".format(participant.summoner_name)) print(" {0}".format(participant.summoner_id)) print(" Champion: {0}".format(participant.champion.name)) print(" Won: {0}".format(participant.stats.win)) print(" Side: {0}".format(participant.side)) print(" Gold earned: {0}".format(participant.stats.gold_earned)) print(" Lane: {0}".format(participant.timeline.lane)) print(" Role: {0}".format(participant.timeline.role)) matchid = [] versionpatch = [] maptype = [] queue = [] p1name = []
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(False) key = os.environ["DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) match = riotapi.get_match(2034758953) print("Match start time: {0}".format(match.creation)) print("Match duration: {0}".format(match.duration)) # You can just add them together! print("Match end time: {0}".format(match.creation + match.duration)) print("Match version: {0}".format(match.version))
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(False) key = os.environ[ "DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) dyrus = riotapi.get_summoner_by_name("Dyrus") # SummonerID is 5908 # dyrus = riotapi.get_summoner_by_id(5908) # You could use this as well match_list = riotapi.get_match_list(dyrus) num_matches = 20 kills = 0 deaths = 0 assists = 0 print("Calculating K/D/A from the past {0} matches...".format(num_matches)) for i, match_reference in enumerate(match_list[0:num_matches]): match = riotapi.get_match(match_reference) for participant in match.participants: if participant.summoner_id == dyrus.id: kills += participant.stats.kills deaths += participant.stats.kills assists += participant.stats.assists kda = (kills + assists) / deaths print( "Rolling K/D/A for {0}: {1}/{2}/{3} == {4} over most recent {5} matches" .format(dyrus.name, kills, deaths, assists, round(kda, 3), i + 1)) print("Final average K/D/A: {0}/{1}/{2} == {3} over past {4} matches". format(kills, deaths, assists, round(kda, 3), num_matches)) print() print( "If we want K/D/A we really should be using the /stats/ endpoint, but it seems to be inaccurate or missing key information." ) stats = riotapi.get_stats(dyrus) stats = stats[StatSummaryType.ranked_fives].stats print("Total ranked K/D/A for {0}: {1}/{2}/{3} == {4}".format( dyrus.name, stats.kills, stats.deaths, stats.assists, round(stats.kda, 3)))
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(False) key = os.environ[ "DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) match = riotapi.get_match(2034758953) print("Match start time: {0}".format(match.creation)) print("Match duration: {0}".format(match.duration)) # You can just add them together! print("Match end time: {0}".format(match.creation + match.duration)) print("Match version: {0}".format(match.version))
def amassSummoners(targetLeague, seedSummoner, returnDict, threshold=1): '''Will take a target league and a starting seed and use the seed to do a branching search for summoners that have reached the target league. If threshold not met, runs recursively on a random summoner already found. Returns a dict of summoner objects {Summoner name : Summoner object} ''' if (type(seedSummoner) == str): print "Searching for summoners related to %s..." % (seedSummoner) seed = riotapi.get_summoner_by_name(seedSummoner) else: print "Searching for summoners related to %s..." % (seedSummoner.name) seed = seedSummoner matchList = riotapi.get_match_list(seed, ranked_queues=QUEUES, seasons="SEASON2015") counter = 0 summonerDict = returnDict for i in range(len(matchList)): try: #Had issues with get_match request failing so wrapped in a try block currentMatch = riotapi.get_match(matchList[i]) for participant in currentMatch.participants: try: if (participant.previous_season_tier.name == targetLeague) & (participant.summoner_name not in summonerDict): summonerDict[ participant.summoner_name] = participant.summoner counter += 1 print "##### Target found ######" except ValueError: continue if counter >= 10: break #Break after 10 summoners grabbed to increase spread except: print "Summoner pull failed." if len(summonerDict.keys()) < threshold: print "Current no. of summoners in %s: %d" % (targetLeague, len(summonerDict.keys())) summonList = summonerDict.values() summonerDict = amassSummoners(targetLeague, summonList[counter / 2], summonerDict) return summonerDict
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(True) key = os.environ[ "DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) # Load and connect to your database. (Comment this code to use local memory. Don't forget to comment db.close() below too.) db = SQLAlchemyDB("mysql+mysqlconnector", "databse_hostname", "database_name", "username", "password") riotapi.set_data_store(db) # We will seed with all the summoners in Master's tier unpulled_summoners = deque(entry.summoner for entry in riotapi.get_master()) print("Pulled Master tier for seeding. Got {0} summoners.".format( len(unpulled_summoners))) # We need this so that we don't get a recursive loop of summoners pulled_summoners = deque() gather_start = datetime(2015, 7, 23) # 1 day after patch 5.14 while len(unpulled_summoners) > 0: summoner = unpulled_summoners.popleft() for match_reference in summoner.match_list(begin_time=gather_start): # If you are connected to a database, the match will automatically be stored in it without you having to do anything. # Simply pull the match, and it's in your database for whenever you need it again! # If you pull a match twice, the second time it will be loaded from the database rather than pulled from Riot # and therefore will not count against your rate limit. This is true of all datatypes, include Summoner. match = riotapi.get_match(match_reference) if match is None: # If the match still fails to load, continue on to the next one continue print("Stored {0} in my database".format(match)) for participant in match.participants: if participant.summoner not in unpulled_summoners and participant.summoner not in pulled_summoners: unpulled_summoners.append(participant.summoner) pulled_summoners.append(summoner) db.close()
def main(): # Setup riotapi riotapi.set_region("KR") riotapi.print_calls(True) key = os.environ["DEV_KEY1"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) # Load and connect to your database. (Comment this code to use local memory. Don't forget to comment db.close() below too.) db = SQLAlchemyDB("mysql+mysqlconnector", "localhost", "lol", "root", "1234") riotapi.set_data_store(db) #riotapi.get_masteries() #riotapi.get_champions() #riotapi.get_runes() #riotapi.get_summoner_spells() # We will seed with all the summoners in Master's tier unpulled_summoners = deque(entry.summoner for entry in riotapi.get_master()) print("Pulled Master tier for seeding. Got {0} summoners.".format(len(unpulled_summoners))) # We need this so that we don't get a recursive loop of summoners pulled_summoners = deque() gather_start = datetime(2017, 1, 12) # 1 day after patch 7.1 while len(unpulled_summoners) > 0: summoner = unpulled_summoners.popleft() for match_reference in summoner.match_list(begin_time=gather_start): match = riotapi.get_match(match_reference) if match is None: # If the match still fails to load, continue on to the next one continue print("Stored {0} in my database".format(match)) for participant in match.participants: # cm = riotapi.get_champion_mastery(participant.summoner, participant.champion) if participant.summoner not in unpulled_summoners and participant.summoner not in pulled_summoners: unpulled_summoners.append(participant.summoner) pulled_summoners.append(summoner) db.close()
def GetBuildStatsforChamp(sumnames,cname,numgames=50,jungle=False): # Get Summoner Objects and summoner ids if len([sumnames])>1: summoners = cass.get_summoners_by_name(sumnames) sumids = list(map(lambda x: x.id,summoners)) else: summoners = cass.get_summoner_by_name(sumnames) sumids = [summoners.id] champ = cass.get_champion_by_name(cname) matchlist = [] itemlist = [] for s in sumids: # Get Match History for specific champion for Solo Ranked this season. We can update to expand to other queues or past seasons matches = base.get_match_list(s,num_matches=numgames,champion_ids = champ.id,ranked_queues='RANKED_SOLO_5x5',seasons='PRESEASON2016').matches matchlist = matchlist + matches # Put in check that summoner for participant id matches summoner id for m in matchlist: # For each match, find participant object matching the champion and get item set match = cass.get_match(m.matchId) c = list(map(lambda x: x.champion.id,match.participants)) player = match.participants[c.index(champ.id)] its = list(map(lambda x: x.id,filter(None,player.stats.items))) itemlist = itemlist + its # Format Item set and calculate percentages itcounts = pd.DataFrame(list(Counter(itemlist).items()),columns=['id','perc']) itcounts = pd.merge(itcounts,Loading.items[Loading.items['id'].isin(itemlist)],on=['id']) itcounts['perc'] = itcounts['perc']/itcounts['perc'].sum() print('numgames=' + str(len(matchlist))) return itcounts.sort(columns=['perc'])
def collectMatches(targetLeague, summonerList): '''Given a list of summoner objects and a target league, will search through the match history of each summoner for games where the majority of participants are in the target league. If found, adds to the matchDict. Will only pull 10 games per summoner Returns a dict of Match objects { MatchID : Match Vector} ''' matchDict = {} deathDict = {} for i in range(len(summonerList)): print "--------------------------------" counter = 0 searched = 100 try: #Removing season requirement: , seasons="SEASON2015" matchList = riotapi.get_match_list(summonerList[i], num_matches=100, ranked_queues=QUEUES) except: continue print "Looking at %s's match history..." % (summonerList[i].name) for i in range(len(matchList)): try: currentMatch = riotapi.get_match(matchList[i]) majorityDict = {'unranked':0, 'bronze':0, 'silver':0, 'gold':0, 'platinum':0, 'diamond':0, 'master':0, 'challenger':0} for participant in currentMatch.participants: try: majorityDict[participant.previous_season_tier.name] += 1 except ValueError: majorityDict['bronze'] += 1 if (majorityDict[targetLeague] > 3) & (currentMatch.id not in matchDict): matchDict[currentMatch.id] = parseMatch.processMatch(currentMatch) deathDict[currentMatch.id] = parseMatch.getDeaths(currentMatch) counter += 1 if counter == 10: #Break after 10 games retrieved searched = i+1 break except: print "Match pull failed." print "%d found out of %d searched" % (counter, searched) print "Current no. of %s matches: %d" % (targetLeague, len(matchDict.values())) return matchDict, deathDict
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(False) os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428" key = os.environ["DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) gigglepuss = riotapi.get_summoner_by_name("GigglePuss") # SummonerID is 5908 # dyrus = riotapi.get_summoner_by_id(5908) # You could use this as well match_list = riotapi.get_match_list(gigglepuss) num_matches = 20 kills = 0 deaths = 0 assists = 0 print("Calculating K/D/A from the past {0} matches...".format(num_matches)) for i, match_reference in enumerate(match_list[0:num_matches]): match = riotapi.get_match(match_reference) for participant in match.participants: if participant.summoner_id == gigglepuss.id: kills += participant.stats.kills deaths += participant.stats.kills assists += participant.stats.assists kda = (kills + assists) / deaths print("Rolling K/D/A for {0}: {1}/{2}/{3} == {4} over most recent {5} matches".format(gigglepuss.name, kills, deaths, assists, round(kda, 3), i + 1)) print("Final average K/D/A: {0}/{1}/{2} == {3} over past {4} matches".format(kills, deaths, assists, round(kda, 3), num_matches)) print() print("If we want K/D/A we really should be using the /stats/ endpoint, but it seems to be inaccurate or missing key information.") stats = riotapi.get_stats(gigglepuss) stats = stats[StatSummaryType.ranked_fives].stats print("Total ranked K/D/A for {0}: {1}/{2}/{3} == {4}".format(gigglepuss.name, stats.kills, stats.deaths, stats.assists, round(stats.kda, 3)))
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(False) os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428" key = os.environ["DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) gigglepuss = riotapi.get_summoner_by_name("GigglePuss") # SummonerID is 5908 match_list = riotapi.get_match_list(gigglepuss) match = riotapi.get_match(match_list[0]) print("Basic match information:") print(" Match ID: {0}".format(match.id)) print(" Version/Patch: {0}".format(match.version)) print(" Creation date: {0} (which was {1} ago)".format(match.creation, datetime.datetime.now() - match.creation)) print(" Duration: {0}".format(match.duration)) print(" Map: {0}".format(match.map)) print(" Mode: {0}".format(match.mode)) print(" Type: {0}".format(match.type)) print(" Platform: {0}".format(match.platform)) print(" Queue: {0}".format(match.queue)) print(" Region: {0}".format(match.region)) print(" Season: {0}".format(match.season)) print(" Red Team Bans: {0}".format([ban.champion.name for ban in match.red_team.bans])) print(" Blue Team Bans: {0}".format([ban.champion.name for ban in match.blue_team.bans])) print() champion = match.participants["GigglePuss"].champion print("You can use special key-words/key-objects to lookup the participants in the match.") print(" Lookup via Summoner: {0}".format(match.participants[gigglepuss])) print(" Lookup via summoner name: {0}".format(match.participants["GigglePuss"])) print(" Lookup via Champion played: {0}".format(match.participants[champion])) print(" Lookup via champion name: {0}".format(match.participants[champion.name]))
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(True) key = os.environ[ "DEV_KEY" ] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) # Load and connect to your database. (Comment this code to use local memory. Don't forget to comment db.close() below too.) db = SQLAlchemyDB("mysql+mysqlconnector", "databse_hostname", "database_name", "username", "password") riotapi.set_data_store(db) # We will seed with all the summoners in Master's tier unpulled_summoners = deque(entry.summoner for entry in riotapi.get_master()) print("Pulled Master tier for seeding. Got {0} summoners.".format(len(unpulled_summoners))) # We need this so that we don't get a recursive loop of summoners pulled_summoners = deque() gather_start = datetime(2015, 7, 23) # 1 day after patch 5.14 while len(unpulled_summoners) > 0: summoner = unpulled_summoners.popleft() for match_reference in summoner.match_list(begin_time=gather_start): # If you are connected to a database, the match will automatically be stored in it without you having to do anything. # Simply pull the match, and it's in your database for whenever you need it again! # If you pull a match twice, the second time it will be loaded from the database rather than pulled from Riot # and therefore will not count against your rate limit. This is true of all datatypes, include Summoner. match = riotapi.get_match(match_reference) print("Stored {0} in my database".format(match)) for participant in match.participants: if participant.summoner not in unpulled_summoners and participant.summoner not in pulled_summoners: unpulled_summoners.append(participant.summoner) pulled_summoners.append(summoner) db.close()
def get_matches(summoners): for summoner in summoners: for match_reference in summoner.match_list( begin_time=current_patch_start, ranked_queues=Queue.ranked_premade_threes): match = riotapi.get_match(match_reference)
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(False) os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428" key = os.environ["DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) gigglepuss = riotapi.get_summoner_by_name("GigglePuss") # SummonerID is 5908 match_list = riotapi.get_match_list(gigglepuss) match = riotapi.get_match(match_list[0]) print("Basic match information:") print(" Match ID: {0}".format(match.id)) print(" Version/Patch: {0}".format(match.version)) print(" Creation date: {0} (which was {1} ago)".format(match.creation, datetime.datetime.now() - match.creation)) print(" Duration: {0}".format(match.duration)) print(" Map: {0}".format(match.map)) print(" Mode: {0}".format(match.mode)) print(" Type: {0}".format(match.type)) print(" Platform: {0}".format(match.platform)) print(" Queue: {0}".format(match.queue)) print(" Region: {0}".format(match.region)) print(" Season: {0}".format(match.season)) print(" Red Team Bans: {0}".format([ban.champion.name for ban in match.red_team.bans])) print(" Blue Team Bans: {0}".format([ban.champion.name for ban in match.blue_team.bans])) print() champion = match.participants["GigglePuss"].champion print("You can use special key-words/key-objects to lookup the participants in the match.") print(" Lookup via Summoner: {0}".format(match.participants[gigglepuss])) print(" Lookup via summoner name: {0}".format(match.participants["GigglePuss"])) print(" Lookup via Champion played: {0}".format(match.participants[champion])) print(" Lookup via champion name: {0}".format(match.participants[champion.name])) print() # Print some basic information about the summoners in the game that doesn't require calls to the Summoner API. # If you ask for participant.summoner, Casseopeia will make a call to the Summoner API to get the full summoner information. print("Basic summoner information:") for participant in match.participants: print(" {0} ({1}) played {2}".format(participant.summoner_name, participant.summoner_id, participant.champion.name)) print() # Print participant information (not summoner information) print("Participant information for this match:") for participant in match.participants: print(" {0}".format(participant.summoner_name)) print(" Champion: {0}".format(participant.champion.name)) print(" Won: {0}".format(participant.stats.win)) print(" Side: {0}".format(participant.side)) print(" Kills: {0}".format(participant.stats.kills)) print(" Deaths: {0}".format(participant.stats.deaths)) print(" Assists: {0}".format(participant.stats.assists)) print(" KDA: {0}".format(participant.stats.kda)) print(" CS: {0}".format(participant.stats.cs)) print(" Summoner spells: {0} + {1}".format(participant.summoner_spell_d, participant.summoner_spell_f)) print(" Champion Level: {0}".format(participant.stats.champion_level)) print(" Got first blood: {0}".format(participant.stats.first_blood)) print(" Gold earned: {0}".format(participant.stats.gold_earned)) print(" Gold spent: {0}".format(participant.stats.gold_spent)) print(" Items: {0}".format([item.name if item is not None else None for item in participant.stats.items])) print(" Magic Damage Dealt: {0}".format(participant.stats.magic_damage_dealt)) print(" Physical Damage Dealt: {0}".format(participant.stats.physical_damage_dealt)) print(" Lane: {0}".format(participant.timeline.lane)) print(" Role: {0}".format(participant.timeline.role)) print() print("Timestamp of last frame: {0}".format(match.frames[-1].timestamp)) print("Number of events in last frame: {0}".format(len(match.frames[-1].events))) print("What's up with the bans?")
def begin_crawling(seed_summoner_id, seasons, ranked_queues): ''' Breadth first crawling interations, Summoner -> Match -> Summoner... ''' #seed intialization try: print('Seed initializing...') seed_summoner = riotapi.get_summoner_by_id(seed_summoner_id) conn = sqlite3.connect('lola.db') conn.execute("INSERT INTO Summoner VALUES('{}','{}',{})".format(seed_summoner.id, seed_summoner.name, 0)) #watch out "" / '' conn.commit() conn.close() print('\nInitialization completed.') except Exception as e: print('\nInitialization failed: ', e) # possibly because the seed is already in database pass # summoner queue interations total_summoner_processed = 0 total_match_processed = 0 total_match_cralwed = 0 total_match_duplicate = 0 total_match_none = 0 iteration = 0 try: conn = sqlite3.connect('lola.db') queue_summoner_ids = pd.read_sql("SELECT summoner_id FROM Summoner WHERE is_crawled=0", conn) except Exception as e: raise(e) finally: conn.close() while not queue_summoner_ids.empty: print('\nSummoner Queue Length:', len(queue_summoner_ids)) iteration += 1 # only a relative number because of crawling restrarts print ('Iteration', iteration, 'in the process...') queue_summoner_ids_list = list(queue_summoner_ids['summoner_id']) random.shuffle(queue_summoner_ids_list) for summoner_id in queue_summoner_ids_list[:]: # pd.dataframe to list of list(queue_summoner_ids['summoner_id']) conn = sqlite3.connect('lola.db') summoner = riotapi.get_summoner_by_id(summoner_id) match_reference_list = riotapi.get_match_list(summoner=summoner, seasons=seasons, ranked_queues=ranked_queues) if match_reference_list is None: # TODO: tag this summoner to be 400/404 status (or the loop may happen quite rarely) print("Summoner {} has None MatchList, skip..".format(summoner_id)) continue print('\nSummoner {} ({}) in {}, {}: '.format(summoner.name, summoner.id, ranked_queues, seasons)) print('Total Match Number of the summoner: {}'.format(len(match_reference_list))) match_no = 0 # crawled + duplicate + none crawled_match_no = 0 duplicate_match_no = 0 none_match_no = 0 for mf in match_reference_list[:]: if is_match_duplicate(mf, conn) == False: try: # TODO: urllib.error.URLError: <urlopen error [Errno 11001] getaddrinfo failed> match = riotapi.get_match(mf) # match reference -> match except Exception as e: raise(e) # may be None even if mf is not None, see https://github.com/meraki-analytics/cassiopeia/issues/57 # can not use != because of Match.__eq__ use Match.id if match is None: none_match_no += 1 continue # jump to the next interation match_to_sqlite(match, summoner, conn) # match is crawled conn.execute("UPDATE Match SET is_crawled = 1 WHERE match_id='{}'".format(mf.id)) crawled_match_no += 1 else : duplicate_match_no += 1 match_no += 1 if match_no % 10 == 0: print (match_no, 'matches in', len(match_reference_list), 'processed.') # summoner has been crawled conn.execute("UPDATE Summoner SET is_crawled = 1 WHERE summoner_id='{}'".format(summoner_id)) conn.commit() # commit after every summoner finished conn.close() # sums of different kinds of matches total_summoner_processed += 1 total_match_processed += match_no total_match_cralwed += crawled_match_no total_match_duplicate += duplicate_match_no total_match_none += none_match_no print('\ntotal processed summoner:', total_summoner_processed,'\ntotal processed match:', total_match_processed, \ '\ntotal crawled match', total_match_cralwed, '\ntotal duplicate match:', total_match_duplicate, \ '\ntotal none match:', total_match_none) # read new queue for next iteration try: conn = sqlite3.connect('lola.db') queue_summoner_ids = pd.read_sql("SELECT summoner_id FROM Summoner WHERE is_crawled=0", conn) #update queue except Exception as e: raise(e) finally: conn.close()
if a_match['teams'][0]['winner'] == True and a_match['teams'][1][ 'winner'] == False: winning_side = 0 if a_match['teams'][0]['winner'] == False and a_match['teams'][1][ 'winner'] == True: winning_side = 1 return winning_side # In[31]: starting_id = 159214821 for i in range(10000): try: a_match = riotapi.get_match(starting_id + i) except: print "ERROR. CONTINUE!" continue a_match = json.loads(a_match.to_json()) matchVersion = a_match['matchVersion'] #print a_match['queueType'] matchMap = a_match['mapId'] matchDuration = a_match['matchDuration'] / 60 matchWinningSide = GetWinningSide(a_match) #print a_match['participantIdentities'][0]['player']['summonerName'] #print a_match['participants'][0]['highestAchievedSeasonTier'] if matchVersion.startswith('6.24') == False: continue if matchDuration < 20:
- Events [Event] - Team ''' riotapi.set_region("NA") riotapi.set_api_key("") # set your key here summoner_id='22005573' seasons = 'PRESEASON2016' ranked_queues = 'RANKED_SOLO_5x5' summoner = riotapi.get_summoner_by_id(summoner_id) #match match_list = riotapi.get_match_list(summoner=summoner, seasons=seasons, ranked_queues=ranked_queues) match_reference = match_list[0] match = riotapi.get_match(match_reference) match_reference_1 = match_list[1] match_1 = riotapi.get_match(match_reference_1) version = match.version duration = math.ceil((match.duration).total_seconds() / 60) #minute data = match.data #team team = match.red_team team_participant = team[0] team_bans = team.bans team_win = team.win team_dragon_kills = team.dragon_kills team_baron_kills = team.baron_kills team_side = str(team.side)[5:] #participant
def test_match(): int_test_handler.test_result(riotapi.get_match(int_test_handler.match_id))
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(False) key = os.environ["DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) dyrus = riotapi.get_summoner_by_name("Dyrus") # SummonerID is 5908 match_list = riotapi.get_match_list(dyrus) match = riotapi.get_match(match_list[0]) print("Basic match information:") print(" Match ID: {0}".format(match.id)) print(" Version/Patch: {0}".format(match.version)) print(" Creation date: {0} (which was {1} ago)".format(match.creation, datetime.datetime.now() - match.creation)) print(" Duration: {0}".format(match.duration)) print(" Map: {0}".format(match.map)) print(" Mode: {0}".format(match.mode)) print(" Type: {0}".format(match.type)) print(" Platform: {0}".format(match.platform)) print(" Queue: {0}".format(match.queue)) print(" Region: {0}".format(match.region)) print(" Season: {0}".format(match.season)) print(" Red Team Bans: {0}".format([ban.champion.name for ban in match.red_team.bans])) print(" Blue Team Bans: {0}".format([ban.champion.name for ban in match.blue_team.bans])) print() champion = match.participants["Dyrus"].champion print("You can use special key-words/key-objects to lookup the participants in the match.") print(" Lookup via Summoner: {0}".format(match.participants[dyrus])) print(" Lookup via summoner name: {0}".format(match.participants["Dyrus"])) print(" Lookup via Champion played: {0}".format(match.participants[champion])) print(" Lookup via champion name: {0}".format(match.participants[champion.name])) print() # Print some basic information about the summoners in the game that doesn't require calls to the Summoner API. # If you ask for participant.summoner, Casseopeia will make a call to the Summoner API to get the full summoner information. print("Basic summoner information:") for participant in match.participants: print(" {0} ({1}) played {2}".format(participant.summoner_name, participant.summoner_id, participant.champion.name)) print() # Print participant information (not summoner information) print("Participant information for this match:") for participant in match.participants: print(" {0}".format(participant.summoner_name)) print(" Champion: {0}".format(participant.champion.name)) print(" Won: {0}".format(participant.stats.win)) print(" Side: {0}".format(participant.side)) print(" Kills: {0}".format(participant.stats.kills)) print(" Deaths: {0}".format(participant.stats.deaths)) print(" Assists: {0}".format(participant.stats.assists)) print(" KDA: {0}".format(participant.stats.kda)) print(" CS: {0}".format(participant.stats.cs)) print(" Summoner spells: {0} + {1}".format(participant.summoner_spell_d, participant.summoner_spell_f)) print(" Champion Level: {0}".format(participant.stats.champion_level)) print(" Got first blood: {0}".format(participant.stats.first_blood)) print(" Gold earned: {0}".format(participant.stats.gold_earned)) print(" Gold spent: {0}".format(participant.stats.gold_spent)) print(" Items: {0}".format([item.name if item is not None else None for item in participant.stats.items])) print(" Magic Damage Dealt: {0}".format(participant.stats.magic_damage_dealt)) print(" Physical Damage Dealt: {0}".format(participant.stats.physical_damage_dealt)) print(" Lane: {0}".format(participant.timeline.lane)) print(" Role: {0}".format(participant.timeline.role)) print() print("Timestamp of last frame: {0}".format(match.frames[-1].timestamp)) print("Number of events in last frame: {0}".format(len(match.frames[-1].events)))
def matchlistpage(zone, name): # Set region and after region is set, fetch latest API version, maybe move the version to a scheduled task if it uses a call. riotapi.set_region(zone) if zone in ['na', 'kr', 'euw', 'eune']: cassdb = SQLAlchemyDB(connector, host, dbnames[zone]+"?charset=utf8", user, passwd) riotapi.set_data_store(cassdb) print("======================") print(zone) print(name) print("======================") patch = riotapi.get_versions()[0] # Used to convert numerals to/from numbers romans = { 'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5 } print("========== DB MADE Trying to get summoner by name ===========") # Get summoner s = riotapi.get_summoner_by_name(name) print("Summoner object:") print(s) print("id:{} name:{} level:{}".format(s.id, s.name, s.level)) print("========== GOT S, trying to get league entries ===========") try: le = riotapi.get_league_entries_by_summoner(s)[0] entry = le.entries[0] print("Got league entries for ranked") except: print("Couldnt fetch le/entry. Perhaps unranked.") le = None entry = None print("========== Trying to get ranked stats ===========") try: stats = riotapi.get_ranked_stats(s, season=None)[None] except: print("Couldnt fetch ranked stats. Maybe not lv30/never did ranked.") stats = None print("========== Trying to get matches ===========") ml = riotapi.get_match_list(s, seasons=[x.value for x in Season][-1], num_matches=10) if ml is not None: matches = [][-10:] for x in ml: try: m_to_add = riotapi.get_match(x) matches.append(m_to_add) except exc.IntegrityError as ie: print("==SQL ERROR ---> {}".format(ie)) print("==Python traceback==") print(traceback.print_exc()) cassdb.session.rollback() else: matches = [] print("========== Trying to render template ===========") return render_template('matchlist.html', s = s, entry = entry, le = le, matches = matches, patch = patch, stats = stats, zone = zone, round = round, len = len, romans = romans)
def cards(request): if request.GET: riotapi.set_api_key("3ca655bb-959d-4ed3-ab2c-287da159aa59") riotapi.set_rate_limits((1500, 10), (90000, 600)) getted = request.GET summoner = getted.get('summ') region = getted.get('region') riotapi.set_region(region) riotapi.print_calls(True) try: summ = riotapi.get_summoner_by_name(summoner) except APIError: return HttpResponseRedirect('/dorans/') masteries = riotapi.get_champion_masteries(summ) trophyChampions = {} count = 0 #this sets up so that champions with lvl 4 or higher mastery but if less than 4 are found add more from lower lvls for champion, mastery in masteries.items(): if mastery.level >= 4 : trophyChampions[champion] = mastery count = count + 1 if count < 4: for champion, mastery in masteries.items(): if mastery.level == 3 : trophyChampions[champion] = mastery displayChampions = [] summid = riotapi.get_summoner_by_name(summoner).id for c in trophyChampions: print(c) topKDA = 0 kills = 0 deaths = 0 assists = 0 wins = 0 losses = 0 MVP = 0 try: matches = riotapi.get_match_list(summ,champions = c, seasons="SEASON2016") except APIError: matches = riotapi.get_match_list(summ,champions = c, seasons="SEASON2016") if not matches: continue for m in matches: try: data = riotapi.get_match(m, include_timeline = False) except APIError: continue teamtotal = 0 tgold = 0 tdamagedlt = 0 tdamagetkn = 0 twards = 0 twardkls = 0 for player in data.participants: if player.summoner_id == summid: #Build stats from this players participant object i = 0 if player.side.name == 'blue': for p in data.participants: i +=1 if i < 5: teamtotal += p.stats.kills tgold += p.stats.gold_earned tdamagedlt += p.stats.damage_dealt_to_champions tdamagetkn += p.stats.damage_taken twards += p.stats.wards_placed else: for p in data.participants: i += 1 if i >= 5: teamtotal += p.stats.kills tgold += p.stats.gold_earned tdamagedlt += p.stats.damage_dealt_to_champions tdamagetkn += p.stats.damage_taken twards += p.stats.wards_placed if teamtotal == 0 : teamtotal = 1; if twards == 0: twards == 1; topKDA = player.stats.kda if player.stats.kda > topKDA else topKDA kills += player.stats.kills deaths += player.stats.deaths assists += player.stats.assists trip = player.stats.triple_kills quad = player.stats.quadra_kills penta = player.stats.penta_kills kp = player.stats.kills/teamtotal g = player.stats.gold_earned/tgold cs = player.stats.cs/data.duration.seconds dmgdlt = player.stats.damage_dealt_to_champions/tdamagedlt dmgtkn = player.stats.damage_taken/tdamagetkn wards = player.stats.wards_placed/twards kda = player.stats.kda if kda == 1: kda = 1.1 if kda == 0: try: kda = .01/p.stats.deaths except ZeroDivisionError: kda = .1 if p.timeline.role.name == 'solo': if p.timeline.lane.name == 'mid_lane': #mid MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 12) + (dmgtkn * -1) + (wards *4) ) + trip * .25 + quad * .5 + penta * 1 else: #print(math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 7) + (dmgtkn * 7) + (wards *4) )) MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 7) + (dmgtkn * 7) + (wards *4) ) + trip * .25 + quad * .5 + penta * 1 elif p.timeline.role.name == 'carry':# carry #print(math.log(kda)/math.log(6) * ((kp * 10)+(g * 6)+(cs * .7)+ (dmgdlt * 12) + (dmgtkn * 1) + (wards *1) )) MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 12) + (dmgtkn * -1) + (wards *4) )+ trip * .25 + quad * .5 + penta * 1 elif p.timeline.role.name == 'support': #supp #print(math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 7) + (dmgtkn * 7) + (wards *6) )) MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * 1.0)+ (dmgdlt * 6) + (dmgtkn * 7) + (wards *5) )+ trip * .25 + quad * .5 + penta * 1 elif p.timeline.role.name == 'none': #jungle #print(math.log(kda)/math.log(6)) MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 7) + (dmgtkn * 7) + (wards *4) )+ trip * .25 + quad * .5 + penta * 1 else: #unknown duo setup #print(math.log(kda)/math.log(6)) MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 10) + (dmgtkn * 2) + (wards *4) ) + trip * .25 + quad * .5 + penta * 1 if player.stats.win: wins = wins + 1 else: losses = losses + 1 championStats = {} championStats['level'] = masteries[c].level championStats['topGrade'] = masteries[c].highest_grade championStats['points'] = masteries[c].points championStats['topKDA'] = round(topKDA, 2) if deaths == 0: deaths = 1 championStats['KDA'] = round((kills + assists) / deaths , 2) championStats['avgkills'] = round(kills / (wins+ losses), 2) championStats['avgdeaths'] = round(deaths / (wins+ losses), 2) championStats['avgassists'] = round(assists / (wins+ losses), 2) championStats['avgMVP'] = round(MVP / (wins + losses), 2) championStats['wins'] = wins championStats['losses'] = losses imagep = c.image.link imagep = imagep.split('.') image = 'http://ddragon.leagueoflegends.com/cdn/img/champion/loading/' + imagep[0] + '_0.jpg' displayChampions.append({'name':str(c), 'stats':championStats, 'mastery': masteries[c], 'masterypoint':masteries[c].points, 'image': image }) displayChampions = sorted(displayChampions, key=itemgetter('masterypoint'), reverse=True) return HttpResponse(render(request, 'doranscards.html', {'champions' : displayChampions})) else: return HttpResponseRedirect('/dorans/')
def addMatch(request): if request.POST: newgame = Game() posted = request.POST print(posted.get('team1name')) newgame.team1 = Team.objects.get(teamName__iexact=posted.get('team1name')).teamID newgame.team2 = Team.objects.get(teamName__iexact=posted.get('team2name')).teamID newgame.winner = Team.objects.get(teamName__iexact=posted.get('winner')).teamID print (Game.objects.all().aggregate(Max('Number'))) try: newgame.Number = Game.objects.all().aggregate(Max('Number'))['Number__max'] + 1 except TypeError: newgame.Number = 0 riotapi.set_region("NA") m = riotapi.get_match(posted.get('match')) if newgame.team2 == newgame.winner: loser = Team.objects.get(teamName__iexact=posted.get('team1name')) position = 2 else: loser = Team.objects.get(teamName__iexact=posted.get('team2name')) position = 1 addPoints(Team.objects.get(teamName__iexact=posted.get('winner')), loser, position) print(posted.get('P2')) namelist= [] namelist.append(posted.get('P1')) namelist.append(posted.get('P2')) namelist.append(posted.get('P3')) namelist.append(posted.get('P4')) namelist.append(posted.get('P5')) namelist.append(posted.get('2P1')) namelist.append(posted.get('2P2')) namelist.append(posted.get('2P3')) namelist.append(posted.get('2P4')) namelist.append(posted.get('2P5')) summoners = riotapi.get_summoners_by_name(namelist) print(dir(summoners[0])) print(summoners[0].id) newgame.team1Player1 = summoners[0].id newgame.team1Player2 = summoners[1].id newgame.team1Player3 = summoners[2].id newgame.team1Player4 = summoners[3].id newgame.team1Player5 = summoners[4].id newgame.team2Player1 = summoners[5].id newgame.team2Player2 = summoners[6].id newgame.team2Player3 = summoners[7].id newgame.team2Player4 = summoners[8].id newgame.team2Player5 = summoners[9].id newgame.matchID = posted.get('match') i = 0 for player in m.participants: try: st = Stats.objects.get(PlayerID=summoners[i].id) except: st = Stats() st.PlayerID = summoners[i].id i= i+ 1 st.Kills = st.Kills + player.stats.kills st.Deaths = st.Deaths + player.stats.deaths st.Assists = st.Assists + player.stats.assists st.GoldTotal = st.GoldTotal + player.stats.gold_earned st.GamesPlayed = st.GamesPlayed + 1 if player.stats.largest_critical_strike > st.LargestCrit: st.LargestCrit = player.stats.largest_critical_strike st.Creeps = st.Creeps + player.stats.minion_kills + player.stats.monster_kills st.SecondsPlayed = st.SecondsPlayed + m.duration.total_seconds() st.DamageDealt = st.DamageDealt + player.stats.damage_dealt_to_champions st.DamageReceived = st.DamageReceived + player.stats.damage_taken if i <= 5: st.TeamKillTotal = st.TeamKillTotal + m.participants[0].stats.kills + m.participants[1].stats.kills + m.participants[2].stats.kills + m.participants[3].stats.kills + m.participants[4].stats.kills else: st.TeamKillTotal = st.TeamKillTotal + m.participants[5].stats.kills + m.participants[6].stats.kills + m.participants[7].stats.kills + m.participants[8].stats.kills + m.participants[9].stats.kills st.DoubleKills = st.DoubleKills + player.stats.double_kills st.TripleKills = st.TripleKills + player.stats.triple_kills st.QuadraKills = st.QuadraKills + player.stats.quadra_kills st.PentaKills = st.PentaKills + player.stats.penta_kills st.save() with open('olsrunner/matches/' + str(newgame.Number) + '.pk', 'wb') as outfile: pickle.dump( m , outfile) newgame.filename = 'olsrunner/matches/' + str(newgame.Number) + '.pk' newgame.save() return HttpResponse("match added") else: teamNames = [] teams = Team.objects.all().values('teamName') for t in teams: teamNames.append(t['teamName']) return HttpResponse(render(request, 'addMatch.html', {'teams' :teamNames}))
def callback(request): print("received request") posted = request.body.decode('utf-8') #print(dir(posted)) print(posted) #with open('olsrunner/tests/gabetest.pk', 'wb') as outfile: # pickle.dump( posted , outfile) gameparse = json.loads(posted) riotapi.set_region("NA") #print(gameparse['shortCode']) try: m = riotapi.get_match(gameparse['gameId'], tournament_code=gameparse['shortCode']) except APIError: return HttpResponseServerError("match was not yet published") #print(gameparse) newgame = Game() code = TourneyCode.objects.get(code = gameparse['shortCode']) newgame.team1 = code.team1 #CAH team1obj = Team.objects.get(teamID = newgame.team1) newgame.team2 = code.team2 #MAG team2obj = Team.objects.get(teamID = newgame.team2) j = 0 for p in gameparse['winningTeam']: print(p) if p['summonerId'] == team1obj.CaptainID: newgame.winner = newgame.team1 break if p['summonerId'] == team1obj.Player1ID: newgame.winner = newgame.team1 break if p['summonerId'] == team1obj.Player2ID: newgame.winner = newgame.team1 break if p['summonerId'] == team1obj.Player3ID: newgame.winner = newgame.team1 break if p['summonerId'] == team1obj.Player4ID: newgame.winner = newgame.team1 break if p['summonerId'] == team2obj.CaptainID: newgame.winner = newgame.team2 break if p['summonerId'] == team2obj.Player1ID: newgame.winner = newgame.team2 break if p['summonerId'] == team2obj.Player2ID: newgame.winner = newgame.team2 break if p['summonerId'] == team2obj.Player3ID: newgame.winner = newgame.team2 break if p['summonerId'] == team2obj.Player4ID: newgame.winner = newgame.team2 break j = j+1 try: newgame.Number = Game.objects.all().aggregate(Max('Number'))['Number__max'] + 1 except KeyError: newgame.Number = 0 if newgame.team2 == newgame.winner: loser = team1obj winner = team2obj position = 2 else: winner = team1obj loser = team2obj position = 1 addPoints(winner, loser, position) if position == 1: newgame.team1Player1 = gameparse['winningTeam'][0]['summonerId'] newgame.team1Player2 = gameparse['winningTeam'][1]['summonerId'] newgame.team1Player3 = gameparse['winningTeam'][2]['summonerId'] newgame.team1Player4 = gameparse['winningTeam'][3]['summonerId'] newgame.team1Player5 = gameparse['winningTeam'][4]['summonerId'] newgame.team2Player1 = gameparse['losingTeam'][0]['summonerId'] newgame.team2Player2 = gameparse['losingTeam'][1]['summonerId'] newgame.team2Player3 = gameparse['losingTeam'][2]['summonerId'] newgame.team2Player4 = gameparse['losingTeam'][3]['summonerId'] newgame.team2Player5 = gameparse['losingTeam'][4]['summonerId'] else: newgame.team1Player1 = gameparse['losingTeam'][0]['summonerId'] newgame.team1Player2 = gameparse['losingTeam'][1]['summonerId'] newgame.team1Player3 = gameparse['losingTeam'][2]['summonerId'] newgame.team1Player4 = gameparse['losingTeam'][3]['summonerId'] newgame.team1Player5 = gameparse['losingTeam'][4]['summonerId'] newgame.team2Player1 = gameparse['winningTeam'][0]['summonerId'] newgame.team2Player2 = gameparse['winningTeam'][1]['summonerId'] newgame.team2Player3 = gameparse['winningTeam'][2]['summonerId'] newgame.team2Player4 = gameparse['winningTeam'][3]['summonerId'] newgame.team2Player5 = gameparse['winningTeam'][4]['summonerId'] newgame.matchID = gameparse['gameId'] i = 0 for player in m.participants: try: if i==0: st = Stats.objects.get(PlayerID=newgame.team1Player1) if i==1: st = Stats.objects.get(PlayerID=newgame.team1Player2) if i==2: st = Stats.objects.get(PlayerID=newgame.team1Player3) if i==3: st = Stats.objects.get(PlayerID=newgame.team1Player4) if i==4: st = Stats.objects.get(PlayerID=newgame.team1Player5) if i==5: st = Stats.objects.get(PlayerID=newgame.team2Player1) if i==6: st = Stats.objects.get(PlayerID=newgame.team2Player2) if i==7: st = Stats.objects.get(PlayerID=newgame.team2Player3) if i==8: st = Stats.objects.get(PlayerID=newgame.team2Player4) if i==9: st = Stats.objects.get(PlayerID=newgame.team2Player5) except: st = Stats() st.PlayerID = riotapi.get_summoner_by_name(player.summoner_name).id i= i+ 1 st.Kills = st.Kills + player.stats.kills st.Deaths = st.Deaths + player.stats.deaths st.Assists = st.Assists + player.stats.assists st.GoldTotal = st.GoldTotal + player.stats.gold_earned st.GamesPlayed = st.GamesPlayed + 1 if player.stats.largest_critical_strike > st.LargestCrit: st.LargestCrit = player.stats.largest_critical_strike st.Creeps = st.Creeps + player.stats.minion_kills + player.stats.monster_kills st.SecondsPlayed = st.SecondsPlayed + m.duration.total_seconds() st.DamageDealt = st.DamageDealt + player.stats.damage_dealt_to_champions st.DamageReceived = st.DamageReceived + player.stats.damage_taken if i <= 5: st.TeamKillTotal = st.TeamKillTotal + m.participants[0].stats.kills + m.participants[1].stats.kills + m.participants[2].stats.kills + m.participants[3].stats.kills + m.participants[4].stats.kills else: st.TeamKillTotal = st.TeamKillTotal + m.participants[5].stats.kills + m.participants[6].stats.kills + m.participants[7].stats.kills + m.participants[8].stats.kills + m.participants[9].stats.kills st.DoubleKills = st.DoubleKills + player.stats.double_kills st.TripleKills = st.TripleKills + player.stats.triple_kills st.QuadraKills = st.QuadraKills + player.stats.quadra_kills st.PentaKills = st.PentaKills + player.stats.penta_kills st.save() with open('olsrunner/matches/' + str(newgame.Number) + '.pk', 'wb') as outfile: pickle.dump( m , outfile) newgame.filename = 'olsrunner/matches/' + str(newgame.Number) + '.pk' newgame.save() return HttpResponse("match added")
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(False) os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428" key = os.environ["DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.eager) gigglepuss = riotapi.get_summoner_by_name("GigglePuss") match_list = riotapi.get_match_list(gigglepuss) sub_list = match_list[:10] matchid = [] versionpatch = [] maptype = [] queue = [] p_names = [] p_sides = [] p_champs = [] p_lanes = [] p_roles = [] p_golds = [] p_wins= [] for i in range(len(sub_list)): match = riotapi.get_match(match_list[i]) matchid.append(match.id) versionpatch.append(match.version) maptype.append(match.map) queue.append(match.queue) p1name = [] p1side = [] p1champ = [] p1lane = [] p1role = [] p1gold = [] p1win = [] for part in match.participants: print(part.summoner_name) p1name.append(part.summoner_name) p1side.append(part.side) p1champ.append(part.champion.name) p1lane.append(part.timeline.lane) p1role.append(part.timeline.role) p1gold.append(part.stats.gold_earned) p1win.append(part.stats.win) p_names.append(p1name) p_sides.append(p1side) p_champs.append(p1champ) p_lanes.append(p1lane) p_roles.append(p1role) p_golds.append(p1gold) p_wins.append(p1win) filename = "test_data.csv" columns = ['matchid', 'versionpatch', 'maptype', 'queue', 'p_names', 'p_sides', 'p_champs', 'p_lanes', 'p_roles', 'p_golds', 'p_wins'] df = pd.DataFrame([matchid, versionpatch, maptype, queue, p_names, p_sides, p_champs, p_lanes, p_roles, p_golds, p_wins], index = columns) df = df.T df.to_csv(filename) print(df)
def begin_crawling(seed_summoner_id, seasons, ranked_queues): ''' Breadth first crawling interations, Summoner -> Match -> Summoner... ''' #seed intialization try: print('Seed initializing...') seed_summoner = riotapi.get_summoner_by_id(seed_summoner_id) conn = sqlite3.connect('lola.db') conn.execute("INSERT INTO Summoner VALUES('{}','{}',{})".format( seed_summoner.id, seed_summoner.name, 0)) #watch out "" / '' conn.commit() conn.close() print('\nInitialization completed.') except Exception as e: print('\nInitialization failed: ', e) # possibly because the seed is already in database pass # summoner queue interations total_summoner_processed = 0 total_match_processed = 0 total_match_cralwed = 0 total_match_duplicate = 0 total_match_none = 0 iteration = 0 try: conn = sqlite3.connect('lola.db') queue_summoner_ids = pd.read_sql( "SELECT summoner_id FROM Summoner WHERE is_crawled=0", conn) except Exception as e: raise (e) finally: conn.close() while not queue_summoner_ids.empty: print('\nSummoner Queue Length:', len(queue_summoner_ids)) iteration += 1 # only a relative number because of crawling restrarts print('Iteration', iteration, 'in the process...') queue_summoner_ids_list = list(queue_summoner_ids['summoner_id']) random.shuffle(queue_summoner_ids_list) for summoner_id in queue_summoner_ids_list[:]: # pd.dataframe to list of list(queue_summoner_ids['summoner_id']) conn = sqlite3.connect('lola.db') summoner = riotapi.get_summoner_by_id(summoner_id) match_reference_list = riotapi.get_match_list( summoner=summoner, seasons=seasons, ranked_queues=ranked_queues) if match_reference_list is None: # TODO: tag this summoner to be 400/404 status (or the loop may happen quite rarely) print("Summoner {} has None MatchList, skip..".format( summoner_id)) continue print('\nSummoner {} ({}) in {}, {}: '.format( summoner.name, summoner.id, ranked_queues, seasons)) print('Total Match Number of the summoner: {}'.format( len(match_reference_list))) match_no = 0 # crawled + duplicate + none crawled_match_no = 0 duplicate_match_no = 0 none_match_no = 0 for mf in match_reference_list[:]: if is_match_duplicate(mf, conn) == False: try: # TODO: urllib.error.URLError: <urlopen error [Errno 11001] getaddrinfo failed> match = riotapi.get_match( mf) # match reference -> match except Exception as e: raise (e) # may be None even if mf is not None, see https://github.com/meraki-analytics/cassiopeia/issues/57 # can not use != because of Match.__eq__ use Match.id if match is None: none_match_no += 1 continue # jump to the next interation match_to_sqlite(match, summoner, conn) # match is crawled conn.execute( "UPDATE Match SET is_crawled = 1 WHERE match_id='{}'". format(mf.id)) crawled_match_no += 1 else: duplicate_match_no += 1 match_no += 1 if match_no % 10 == 0: print(match_no, 'matches in', len(match_reference_list), 'processed.') # summoner has been crawled conn.execute( "UPDATE Summoner SET is_crawled = 1 WHERE summoner_id='{}'". format(summoner_id)) conn.commit() # commit after every summoner finished conn.close() # sums of different kinds of matches total_summoner_processed += 1 total_match_processed += match_no total_match_cralwed += crawled_match_no total_match_duplicate += duplicate_match_no total_match_none += none_match_no print('\ntotal processed summoner:', total_summoner_processed,'\ntotal processed match:', total_match_processed, \ '\ntotal crawled match', total_match_cralwed, '\ntotal duplicate match:', total_match_duplicate, \ '\ntotal none match:', total_match_none) # read new queue for next iteration try: conn = sqlite3.connect('lola.db') queue_summoner_ids = pd.read_sql( "SELECT summoner_id FROM Summoner WHERE is_crawled=0", conn) #update queue except Exception as e: raise (e) finally: conn.close()