def get(self, request, region, summoner_a_name, summoner_b_name): setup_cassiopeia(region=region) try: summoner_a = riotapi.get_summoner_by_name(summoner_a_name) summoner_b = riotapi.get_summoner_by_name(summoner_b_name) except APIError as e: if e.error_code in [404]: summoner_name = summoner_a_name if ("by-name/" + summoner_a_name) in e.message else summoner_b_name from_url = request.META['HTTP_REFERER'] if "HTTP_REFERER" in request.META else "" context = { 'summoner_name': summoner_name, 'region': region, '404_summoner_not_found': True, 'from_url': from_url, } return render(request, 'notification.html', context=context) raise e champion_mastery_a = summoner_a.top_champion_masteries()[0] champion_mastery_b = summoner_b.top_champion_masteries()[0] champion_a = champion_mastery_a.champion champion_b = champion_mastery_b.champion champion_data_a = ChampionData.get_champion_data(summoner_a, champion_a, champion_mastery_a, region) champion_data_b = ChampionData.get_champion_data(summoner_b, champion_b, champion_mastery_b, region) if not champion_data_a.games or not champion_data_b.games: from_url = request.META['HTTP_REFERER'] if "HTTP_REFERER" in request.META else "" context = { 'cant_compare_summoners': True, 'from_url': from_url, } return render(request, 'notification.html', context=context) champion_data_a.win_percent = int((champion_data_a.wins / champion_data_a.games) * 100) champion_data_b.win_percent = int((champion_data_b.wins / champion_data_b.games) * 100) champion_data_a.kda_percent = int(champion_data_a.kda / (champion_data_a.kda + champion_data_b.kda) * 100) champion_data_b.kda_percent = 100 - champion_data_a.kda_percent context = { 'summoner_a': summoner_a, 'summoner_b': summoner_b, 'champion_a': champion_a, 'champion_b': champion_b, 'champion_data_a': champion_data_a, 'champion_data_a_averages': champion_data_a.averages, 'champion_data_b': champion_data_b, 'champion_data_b_averages': champion_data_b.averages, 'region': region, } return render(request, 'compare.html', context=context)
def get(self, request, region, summoner_name): setup_cassiopeia(region=region) try: summoner = riotapi.get_summoner_by_name(summoner_name) except APIError as e: if e.error_code in [404]: from_url = request.META['HTTP_REFERER'] if "HTTP_REFERER" in request.META else "" context = { 'summoner_name': summoner_name, 'region': region, '404_summoner_not_found': True, 'from_url': from_url, } return render(request, 'notification.html', context=context) raise e champion_mastery = summoner.top_champion_masteries()[0] champion = champion_mastery.champion champion_data = ChampionData.get_champion_data(summoner, champion, champion_mastery, region) context = { 'summoner': summoner, 'champion': champion, 'champion_data': champion_data, 'champion_data_averages': champion_data.averages, 'related_videos_ids': get_related_videos('League of legends ' + champion.name, count=6), 'region': region, } return render(request, 'summoner.html', context=context)
def isInGame(player): summoner = riotapi.get_summoner_by_name(player) current_game = riotapi.get_current_game(summoner) if current_game is None: return False else: return True
def display(): if request.method == 'POST': summoner_name = request.form['summoner_name'] summoner = riotapi.get_summoner_by_name(summoner_name) globalSummoner = "{name} is a level {level} summoner on the NA server.".format( name=summoner.name, level=summoner.level) return render_template('display.html', result=globalSummoner)
def getCurrentMatch(summonerName, region="NA"): riotapi.set_region(region) summoner = riotapi.get_summoner_by_name(summonerName) match = riotapi.get_current_game(summoner) if match is None: return None roleMap = allRoles(match) # for x in roleMap: # print x.champion.name, x.side.name, roleMap[x] if len(roleMap.keys()) < 10: print "Role confusion!" return None statMap = {} rankMap = {} nonNormMap = {} for p in match.participants: role = roleMap[p] stats, nonNorm, rank = avgPerformance.getAvgPerformance(p, role) if stats is None: #currently filling with avg gold? stats = getAvg() rank = "unranked" statMap[p.side.name+role] = list(stats) rankMap[p] = rank nonNormMap[p] = nonNorm print p.summoner_name, p.side.name+role statVector = (statMap['blueTop']+statMap['blueMid']+statMap['blueJung']+ statMap['blueSup']+statMap['blueADC']+statMap['redTop']+ statMap['redMid']+statMap['redJung']+statMap['redSup']+ statMap['redADC']) model = fetchModel(match) results = model.predict_proba(statVector) return format.prepareReturn(roleMap, rankMap, nonNormMap, results, match)
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 extract_participant(sum_name): quetype=Queue.ranked_solo myseason=Season.season_5 summoner = riotapi.get_summoner_by_name(sum_name) mygamelist=riotapi.get_match_list(summoner, num_matches=2, ranked_queues=quetype, seasons=myseason) #matchlist objects mydict= dict() yolo=[] # for i in range(0, 500, 50): for game in mygamelist: #mydict[game.id]=[] for i in range(0,10): participant=game.match().participants[i] champstat=participant.summoner.ranked_stats(season=myseason)[participant.champion] participant_list=[] #participant_list.append(game.id) participant_list.append(participant.summoner_name) participant_list.append(participant.champion.id) participant_list.append(champstat.kda) participant_list.append(champstat.wins/champstat.games_played) participant_list.append(champstat.kills) participant_list.append(champstat.deaths) participant_list.append(champstat.assists) participant_list.append(str(participant.side)[5:]) yolo.append(participant_list) #mydict[game.id]=participant_list return yolo
def updateIDs(request): NoIDs = Player.objects.filter(SummonerNumber=0) riotapi.set_region("NA") for play in NoIDs: summtoadd = riotapi.get_summoner_by_name(play.PlayerIGN) play.SummonerNumber = summtoadd.id play.save() print(summtoadd.id) return HttpResponse("All unset IDs have been updated")
def worker(): try: summoner = riotapi.get_summoner_by_name(argname) client.send_message(message.channel, "Name: {name}\nLevel: {level}\nRank: {rank}".format(name=summoner.name, level=summoner.level, rank= summoner.leagues()[ 0])) except type.api.exception.APIError as e: client.send_message(message.channel, 'Lookup Failed.\nError: ' + str(e.error_code))
def get_summoner_by_name(player_name, region): """ Get a Summoner Object by his Name and Region :param player_name: The Summoner Name :param region: The Region on which to get the Summoner :return: The Summoner """ set_region(region) return riotapi.get_summoner_by_name(player_name)
def checkgame(zone,name): try: riotapi.set_region(zone) cgame = riotapi.get_current_game(riotapi.get_summoner_by_name(name)) except: print("printing traceback:") traceback.print_exc() if cgame is None: return jsonify({'current_game_exists': False}) else: return jsonify({'current_game_exists': True})
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 AddTeam(request): if request.POST: newteam = Team() posted = request.POST #print(posted.get('teamname')) newteam.teamName = posted.get('teamname') newteam.Captain = posted.get('cap') newteam.Player1 = posted.get('P1') newteam.Player2 = posted.get('P2') newteam.Player3 = posted.get('P3') newteam.Player4 = posted.get('P4') riotapi.set_region("NA") summtoadd = riotapi.get_summoner_by_name(newteam.Captain) print(summtoadd) newteam.CaptainID = summtoadd.id summtoadd = riotapi.get_summoner_by_name(newteam.Player1) print(summtoadd) newteam.Player1ID = summtoadd.id summtoadd = riotapi.get_summoner_by_name(newteam.Player2) print(summtoadd) newteam.Player2ID = summtoadd.id summtoadd = riotapi.get_summoner_by_name(newteam.Player3) print(summtoadd) newteam.Player3ID = summtoadd.id summtoadd = riotapi.get_summoner_by_name(newteam.Player4) print(summtoadd) newteam.Player4ID = summtoadd.id #print(Team.objects.all().aggregate(Max('teamID'))) try: if Team.objects.all().aggregate(Max('teamID'))['teamID_max'] is not None: newteam.teamID = Team.objects.all().aggregate(Max('teamID'))['teamID__max'] + 1 else: raise KeyError("no teams yet") except KeyError: newteam.teamID = 0 newteam.save() return HttpResponse(render(request, 'addedteam.html')) else: return HttpResponse(render(request, 'addteam.html'))
def updateTeamIDs(request): teams = Team.objects.all() riotapi.set_region("NA") for t in teams: if t.CaptainID == 0: summtoadd = riotapi.get_summoner_by_name(t.Captain) t.CaptainID = summtoadd.id if t.Player1ID == 0: summtoadd = riotapi.get_summoner_by_name(t.Player1) t.Player1ID = summtoadd.id if t.Player2ID == 0: summtoadd = riotapi.get_summoner_by_name(t.Player2) t.Player2ID = summtoadd.id if t.Player3ID == 0: summtoadd = riotapi.get_summoner_by_name(t.Player3) t.Player3ID = summtoadd.id if t.Player4ID == 0: summtoadd = riotapi.get_summoner_by_name(t.Player4) t.Player4ID = summtoadd.id t.save() return HttpResponse("All unset IDs have been updated")
def isSupport(summname, region): """Returns True if the summoner is a support main, False otherwise.""" #initalize variables summoner = riotapi.get_summoner_by_name(summname) riotapi.set_region(region) match_history = riotapi.get_match_list(summoner, 5) counter = 0 for match in match_history: if str(match.role) == 'Role.support': counter += 1 if counter == 3: return True return False
def getid(df): riotapi.set_api_key("Your Key Here") #set your API key here idlist = [] #create an empty list to store the IDs for realm, name in zip( data.Realm, data.Names): #for loop calling two series of the data dataframe try: #try allows for exceptions riotapi.set_region(realm) summoner = riotapi.get_summoner_by_name(name) idlist.append(summoner.id) except APIError as error: #if there's a 404, it skips and moves on if error.error_code in [400, 404]: continue except AttributeError, UnicodeEncodeError: #if there's an AttributeError or UnicodeEncodeError, move on continue
async def game(self, ctx, sum_name: str, region: str): if region is None: try: db = database.Database('guilds.db') region = db.find_entry(ctx.guild.id) db.close_connection() except TypeError: embed = utilities.error_embed( ctx, "Please specify a region, or set a default region with `b!region set [region]`." ) await ctx.send("", embed=embed) return if "'" in sum_name: embed = utilities.error_embed( ctx, "Please use quotation marks to enclose names") await ctx.send("", embed=embed) return await ctx.trigger_typing() try: riotapi.set_region(region) except ValueError: embed = utilities.error_embed( ctx, "{0} is not a valid region! Valid regions are listed in `b!region list`." .format(region)) await ctx.send("", embed=embed) return try: summoner = riotapi.get_summoner_by_name(sum_name) game = riotapi.get_current_game(summoner) except APIError as exception: await Summoner.raise_exception(self, ctx, exception, sum_name, region) return try: does_game_exist = game.id except AttributeError: embed = utilities.error_embed( ctx, "{} is not in an active game!".format(summoner.name)) await ctx.send("", embed=embed) return
def rank(): try: if request.form.get('token') == SLACK_WEBHOOK_SECRET: # Get channel name and text after command channel = request.form.get('channel_name') text = request.form.get('text') # Get summoner information summoner = riotapi.get_summoner_by_name(text) # Get ranked information about the summoner rank = riotapi.get_league_entries_by_summoner(summoner) rankInfo = [rank[0].tier, rank[0].entries[0].division, rank[0].entries[0].league_points] message = str(text) + " is currently " + str(rankInfo[0])[5:].capitalize() + " " + str(rankInfo[1])[9:].capitalize() + " with " + str(rankInfo[2]) + " lp." send_message(channel,message) return Response(),200 except Exception as e: return "I could not find that summoner, maybe they are not ranked yet."
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) summoner = riotapi.get_summoner_by_name("Dyrus") # SummonerID is 5908 # dyrus = riotapi.get_summoner_by_id(5908) # You could use this as well current_game = riotapi.get_current_game(summoner) if current_game is None: print("{0} is not in-game!".format(summoner)) else: print("{0} is in-game!".format(summoner))
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) summoner = riotapi.get_summoner_by_name("Dyrs") # SummonerID is 5908 # dyrus = riotapi.get_summoner_by_id(5908) # You could use this as well current_game = riotapi.get_current_game(summoner) if current_game is None: print("{0} is not in-game!".format(summoner)) else: print("{0} is in-game!".format(summoner))
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 winrate(): try: if request.form.get('token') == SLACK_WEBHOOK_SECRET: # Code for winrate # Get channel name and text after command channel = request.form.get('channel_name') text = request.form.get('text') # Get summoner information summoner = riotapi.get_summoner_by_name(text) # Get winrates for summoner rank = riotapi.get_league_entries_by_summoner(summoner) winrate = (int(rank[0].entries[0].wins)/(int(rank[0].entries[0].wins) + int(rank[0].entries[0].losses))) message = str(text) + " has a ranked winrate of " + "{0:.0%}".format(winrate) send_message(channel,message) return Response(),200 except Exception as e: return "I could not find that summoner"
def scan_player(name, num, it): #go through every match played tries = 0 while tries < 5: try: summoner = riotapi.get_summoner_by_name(name) tries = 50 except: tries = tries + 1 print("Failed loking up {name}, tried {tries} times".format( name=name, tries=tries)) #if failed looking up if tries == 5: return try: match_list = summoner.match_list() except: print("Failed accessing summoner: {0}".format(name)) return for index in range(0, num): #trying 3 times tries = 0 while tries < 3: try: if it >= saved: print( "Currently looking up the {index}th game of {summoner}" .format(index=index, summoner=name)) match_ref = match_list[index] match = match_ref.match() game_stats(match) it = it + 1 print("Saved {it} games".format(it=it)) else: it = it + 1 #skipping loop tries = 5 except: print("An error occured, tried {num} times".format(num=tries)) tries = tries + 1
def addplayerlist(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/ols/login') else: posted = request.POST #playerlist = posted.split(','') playerlist = posted.get('players').split(',') print(playerlist) riotapi.set_region("NA") for player in playerlist: player = player.split(':') play = Player() play.PlayerName = player[0] play.PlayerIGN = player[1] play.SummonerNumber = riotapi.get_summoner_by_name(player[1]).id play.save() return HttpResponse("Added players")
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 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
async def on_message(bot, msg, msg_obj): if msg[0] == 'summoner': summoner = riotapi.get_summoner_by_name(' '.join(msg[1:])) print(summoner) match_list = summoner.match_list() first = match_list[0].match() player = first.participants[summoner] await bot.send_message( msg_obj.channel, '%s %s his last game in %s lane, role: %s.\nChampion: %s | Kills: %s | Deaths: %s | Assists: %s | CS: %s | KDA: %s\nBans: %s' % (msg[1], "won" if player.stats.win else "lost", player.timeline.lane, player.timeline.role, player.champion.name, player.stats.kills, player.stats.deaths, player.stats.assists, player.stats.cs, player.stats.kda, ('/'.join([ ban.champion.name for ban in first.red_team.bans + first.blue_team.bans ])))) return True if msg[0] == 'master': master = [entry.summoner for entry in riotapi.get_master()] for summoner in master: if master.name.lower() == ' '.join(msg[1:]).lower(): await bot.send_message(msg_obj.channel, '**YOU THINK THAT PLAYER IS A JOKE?**') await bot.send_message(msg_obj.channel, 'No, that player is basically johnny...') return True if msg[0] == 'mmr': summoner = ''.join(msg[1:]) mmr = await get_mmr(summoner) await bot.send_message( msg_obj.channel, '**%s** has an MMR of: *%s*\n%s\n`%s`' % (summoner, mmr['value'], mmr['tip'], mmr['average'])) return True
def GetKDA(player): summoner = riotapi.get_summoner_by_name(player) match_list = summoner.match_list() num_matches = 8 kills = 0 deaths = 0 assists = 0 for i, match_reference in enumerate(match_list[0:num_matches]): match = match_reference.match() for participant in match.participants: if participant.summoner_id == summoner.id: kills += participant.stats.kills deaths += participant.stats.deaths assists += participant.stats.assists kda = (kills + assists) / deaths return [kills,deaths,assists,kda]
def summoner(sumName): # images_names = os.listdir('myapplication/static/images/planes') # planeswalkerNames = planeswalker_dict.keys() username = riotapi.get_summoner_by_name(sumName) # rankedstats = riotapi.get_ranked_stats(sumName) champions = riotapi.get_champions() # championIds = riotapi.get_champions() # mapping = {champion.id: champion.name for champion in championIds} # # runes = riotapi.get_rune_pages(sumName) sumId = username.id match1 = riotapi.get_match_list(username, 3) championName = riotapi.get_champion_by_name(match1) # match = riotapi.get_match(2034758953) masteryStats = riotapi.get_champion_mastery_score(username) return render_template('testhome.html', summoner=username, champions=champions, match=match1, championName=championName, masteryscore=masteryStats)
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 getCurrentMatch(summonerName, region="NA"): riotapi.set_region(region) try: summoner = riotapi.get_summoner_by_name(summonerName) match = riotapi.get_current_game(summoner) except APIError as e: print e return None if match is None: return None if match.mode.name != "classic": print "Not classic" return None roleMap = allRoles(match) if len(roleMap.keys()) < 10: roleMap = assignRandom(match) print "Role confusion!" statMap = {} rankMap = {} nonNormMap = {} for p in match.participants: role = roleMap[p] try: stats, nonNorm, rank = avgPerformance.getAvgPerformance(p, role) except: stats = getAvg(p.side.name+role) rank = "unranked" nonNorm = [0, 0, 0, 0, 0, 0] statMap[p.side.name+role] = list(stats) rankMap[p] = rank nonNormMap[p] = nonNorm print p.summoner_name, p.side.name+role statVector = (statMap['blueTop']+statMap['blueMid']+statMap['blueJung']+ statMap['blueSup']+statMap['blueADC']+statMap['redTop']+ statMap['redMid']+statMap['redJung']+statMap['redSup']+ statMap['redADC']) model = fetchModel(match, rankMap) results = model.predict_proba(statVector) return format.prepareReturn(roleMap, rankMap, nonNormMap, results, match)
def get(self, request, region, summoner_name): setup_cassiopeia(region=region) try: summoner = riotapi.get_summoner_by_name(summoner_name) except APIError as e: if e.error_code in [404]: from_url = request.META[ 'HTTP_REFERER'] if "HTTP_REFERER" in request.META else "" context = { 'summoner_name': summoner_name, 'region': region, '404_summoner_not_found': True, 'from_url': from_url, } return render(request, 'notification.html', context=context) raise e champion_mastery = summoner.top_champion_masteries()[0] champion = champion_mastery.champion champion_data = ChampionData.get_champion_data(summoner, champion, champion_mastery, region) context = { 'summoner': summoner, 'champion': champion, 'champion_data': champion_data, 'champion_data_averages': champion_data.averages, 'related_videos_ids': get_related_videos('League of legends ' + champion.name, count=6), 'region': region, } return render(request, 'summoner.html', context=context)
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 summoner(summ): summ = summ.replace(" ", "") # regionlist = [zone.value for zone in Region] regionlist = ['na', 'kr', 'euw', 'eune'] zone_summoners = [] # Try to speed this up by using pure riot json requests simultaneously for all regions? for r in regionlist: cassdb = SQLAlchemyDB(connector, host, dbnames[r]+"?charset=utf8", user, passwd) riotapi.set_data_store(cassdb) riotapi.set_region(r) try: s = riotapi.get_summoner_by_name(summ) if s is not None: zone_summoners.append((r, s)) print("{} from {} appended".format(s.name, r)) except APIError as error: print(error) print(error.error_code) cassdb.close() # attempt to avoid mysql went away if len(zone_summoners) == 0: error = "Summoner with that name not found. Try another one." return render_template('index.html', error=error) patch = riotapi.get_versions()[0] return render_template('zone.html', zone_summoners = zone_summoners, summname = summ, patch = patch)
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")
# We get the key as an environment variable called DEV_KEY so that it's not exposed in the code KEY = os.environ["DEV_KEY"] riotapi.set_api_key(KEY) # We only get ranked games (S6 onwards) Q = Queue.ranked_dynamic_queue # We ask the user for a summoner name, this is just for testing purposes, this is supposed to be backend # only summonerName = input("Please enter summoner name: ") # We check if the summoner name is invalid and keep asking if it's not isNameInvalid = True while isNameInvalid: try: summoner = riotapi.get_summoner_by_name(summonerName) except: summonerName = input( "No summoner by that name found, please enter a valid summoner name: " ) finally: summoner = riotapi.get_summoner_by_name(summonerName) isNameInvalid = False # We get the summoner's match history, provided that it's a ranked game (Q) and up to a maximum of # 50 matches (to be refined later on) matchHistory = summoner.match_list(num_matches=50, ranked_queues=Q) bans = {} for match in matchHistory: fullMatch = match.match(include_timeline=False)
def action(message, client, config): api_key = config.get("BotSettings", "lol_api") riotapi.set_region("NA") riotapi.set_api_key(api_key) split_message = message.content.split() if split_message[0] == "!lol": if split_message[1] == "last": try: summoner_name = ' '.join(split_message[2:]) summoner = riotapi.get_summoner_by_name(summoner_name) last_game = summoner.recent_games()[0] champion = last_game.champion.name kda = last_game.stats.kda kda_tuple = (last_game.stats.kills, last_game.stats.deaths, last_game.stats.assists) cs = last_game.stats.minion_kills level = last_game.stats.level win = last_game.stats.win wards = last_game.stats.wards_placed vision_wards = last_game.stats.vision_wards_bought time_played = last_game.stats.time_played / 60 side = last_game.stats.side.name gold_earned = last_game.stats.gold_earned total_wards = wards + vision_wards role = last_game.stats.role if role is None: role = "IDONTKNOW" else: role = role.name lane = last_game.stats.lane if lane is None: lane = "IDONTKNOW" else: lane = lane.value.lower() if win: victory = "won" else: victory = "lost" message1 = "%s %s their last game as %s playing %s in the %s lane on the %s side in %.1f minutes." % ( summoner_name, victory, champion, role, lane, side, time_played) message2 = "They finished the game with a KDA of %.1f and CS of %s. They were level %s and earned %s gold. They placed %s wards." % ( kda, cs, level, gold_earned, total_wards) full_message = message1 + " " + message2 yield from client.send_message(message.channel, full_message) except APIError as error: if error.error_code in [500]: yield from client.send_message( message.channel, "I had trouble connecting, try again in a little while." ) if error.error_code in [404]: yield from client.send_message( message.channel, "I couldn't find that Summoner.") except: print(traceback.format_exc()) if split_message[1] == "tip": try: tip_type = random.choice(['ally', 'enemy']) random_champ = random.choice(riotapi.get_champions()) tip = "I ain't got no tips for you, soz." if tip_type == "ally": tip = random.choice(random_champ.ally_tips) if tip_type == "enemy": tip = random.choice(random_champ.enemy_tips) yield from client.send_message(message.channel, tip) except APIError as error: if error.error_code in [500]: yield from client.send_message( message.channel, "I had trouble connecting, try again in a little while." ) except: print(traceback.format_exc())
def test_summoner_by_name(): int_test_handler.test_result(riotapi.get_summoner_by_name(int_test_handler.summoner_name))
def action(message, client, config): if config.has_option("lolinfo", "time_limit"): time_limit = config.getint("lolinfo", "time_limit") else: time_limit = 60 if config.has_option("lolinfo", "permitted_channels"): permitted_channels = json.loads(config.get('lolinfo', 'permitted_channels')) else: permitted_channels = [] if not rl.is_rate_limited(message.author.id, "lolinfo", time_limit) and message.channel.name in permitted_channels: api_key = config.get("BotSettings", "lol_api") riotapi.set_region("NA") riotapi.set_api_key(api_key) split_message = message.content.split() if split_message[0] == "!lol": if len(split_message) > 1: if split_message[1] == "last" and len(split_message) > 2: try: summoner_name = ' '.join(split_message[2:]) summoner = riotapi.get_summoner_by_name(summoner_name) last_game = summoner.recent_games()[0] champion = last_game.champion.name kda = last_game.stats.kda kda_tuple = (last_game.stats.kills, last_game.stats.deaths, last_game.stats.assists) cs = last_game.stats.minion_kills level = last_game.stats.level win = last_game.stats.win wards = last_game.stats.wards_placed vision_wards = last_game.stats.vision_wards_bought time_played = last_game.stats.time_played/60 side = last_game.stats.side.name gold_earned = last_game.stats.gold_earned total_wards = wards + vision_wards role = last_game.stats.role if role is None: role = "IDONTKNOW" else: role = role.name lane = last_game.stats.lane if lane is None: lane = "IDONTKNOW" else: lane = lane.value.lower() if win: victory = "won" else: victory = "lost" message1 = "%s %s their last game as %s playing %s in the %s lane on the %s side in %.1f minutes." % (summoner_name, victory, champion, role, lane, side, time_played) message2 = "They finished the game with a KDA of %.1f and CS of %s. They were level %s and earned %s gold. They placed %s wards." % (kda, cs, level, gold_earned, total_wards) full_message = message1 + " " + message2 yield from client.send_message(message.channel, full_message) except APIError as error: if error.error_code in [500]: yield from client.send_message(message.channel, "I had trouble connecting, try again in a little while.") if error.error_code in [404]: yield from client.send_message(message.channel, "I couldn't find that Summoner.") except: print(traceback.format_exc()) if split_message[1] == "tip": try: tip_type = random.choice(['ally', 'enemy']) random_champ = random.choice(riotapi.get_champions()) tip = "I ain't got no tips for you, soz." if tip_type == "ally": tip = random.choice(random_champ.ally_tips) if tip_type == "enemy": tip = random.choice(random_champ.enemy_tips) yield from client.send_message(message.channel, tip) except APIError as error: if error.error_code in [500]: yield from client.send_message(message.channel, "I had trouble connecting, try again in a little while.") except: print(traceback.format_exc())
def get(self, request, region, summoner_a_name, summoner_b_name): setup_cassiopeia(region=region) try: summoner_a = riotapi.get_summoner_by_name(summoner_a_name) summoner_b = riotapi.get_summoner_by_name(summoner_b_name) except APIError as e: if e.error_code in [404]: summoner_name = summoner_a_name if ( "by-name/" + summoner_a_name) in e.message else summoner_b_name from_url = request.META[ 'HTTP_REFERER'] if "HTTP_REFERER" in request.META else "" context = { 'summoner_name': summoner_name, 'region': region, '404_summoner_not_found': True, 'from_url': from_url, } return render(request, 'notification.html', context=context) raise e champion_mastery_a = summoner_a.top_champion_masteries()[0] champion_mastery_b = summoner_b.top_champion_masteries()[0] champion_a = champion_mastery_a.champion champion_b = champion_mastery_b.champion champion_data_a = ChampionData.get_champion_data( summoner_a, champion_a, champion_mastery_a, region) champion_data_b = ChampionData.get_champion_data( summoner_b, champion_b, champion_mastery_b, region) if not champion_data_a.games or not champion_data_b.games: from_url = request.META[ 'HTTP_REFERER'] if "HTTP_REFERER" in request.META else "" context = { 'cant_compare_summoners': True, 'from_url': from_url, } return render(request, 'notification.html', context=context) champion_data_a.win_percent = int( (champion_data_a.wins / champion_data_a.games) * 100) champion_data_b.win_percent = int( (champion_data_b.wins / champion_data_b.games) * 100) champion_data_a.kda_percent = int( champion_data_a.kda / (champion_data_a.kda + champion_data_b.kda) * 100) champion_data_b.kda_percent = 100 - champion_data_a.kda_percent context = { 'summoner_a': summoner_a, 'summoner_b': summoner_b, 'champion_a': champion_a, 'champion_b': champion_b, 'champion_data_a': champion_data_a, 'champion_data_a_averages': champion_data_a.averages, 'champion_data_b': champion_data_b, 'champion_data_b_averages': champion_data_b.averages, 'region': region, } return render(request, 'compare.html', context=context)
def get_lol_stats(summoner_name): summoner = riotapi.get_summoner_by_name(summoner_name) stats = summoner.stats() unranked = stats[StatSummaryType.normal_fives] #kills = unranked.stats.kills return unranked.stats.data
import random import urllib2, cookielib from cassiopeia import riotapi from bs4 import BeautifulSoup #html parsing from time import sleep riotapi.set_region("EUNE") riotapi.set_api_key("RGAPI-fea9f643-7979-4b87-b857-a8330157d2c8") summoner = riotapi.get_summoner_by_name("petisa") index = 1 def ping_summoner(summoner_name): site = "http://www.lolskill.net/summoner/EUNE/{name}/champions".format( name=summoner_name) hdr = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive' } #rerfreshing statistics on LoLSikills req = urllib2.Request(site, headers=hdr) page = urllib2.urlopen(req)
def request_data(summoner_request): #Set Riot API information riotapi.set_region("NA") riotapi.print_calls(False) riotapi.set_api_key(os.environ["RIOT_DEV"]) riotapi.set_load_policy(LoadPolicy.lazy) #Establish database connection client = MongoClient( "mongodb://*****:*****@ds135700.mlab.com:35700/summonertest") db = client.summonertest #Declare variables kills = 0 deaths = 0 assists = 0 kda = 0 avg_time = 0 avg_cs = 0 avg_game_cs = 0 avg_time = 0 cs = 0 try: name_request = summoner_request #CHANGE TO DESIRED LOOKUP NAME except: return None summoner = riotapi.get_summoner_by_name(name_request) match_list = summoner.match_list() #Number of matches to pull from Riot Servers num_matches = 5 #CHANGE THIS TO NUMBER INTERESTED IN #Basic stats collection for i, match_reference in enumerate(match_list[0:num_matches]): match = match_reference.match() for participant in match.participants: if participant.summoner_id == summoner.id: cs += participant.stats.cs kills += participant.stats.kills deaths += participant.stats.deaths assists += participant.stats.assists avg_time += match.duration.total_seconds() if (avg_time > 0): avg_cs += (float)(participant.stats.cs / (match.duration.total_seconds() / 60)) #Matchwide averages if (deaths > 0): kda = (float)(kills + assists) / deaths else: kda = kills + assists if (num_matches > 0): avg_time = (float)((avg_time / 60) / num_matches) avg_game_cs = (float)(avg_cs / num_matches) if (avg_time > 0): avg_cs = (float)(cs / num_matches) #TODO Create scores for various items #Verify user not already on server, delete if pre-existing if (db.summoners.count() > 0): if (db.summoners.find({"summoner": summoner.name})): clear = db.summoners.delete_many({"summoner": summoner.name}) #Push to server pushVal = db.summoners.insert_one({ "summoner": summoner.name, "level": summoner.level, "matches_polled": num_matches, "kda": round(kda, 3), "kills": kills, "deaths": deaths, "assists": assists, "average_cs_per_min": round(avg_game_cs, 1), "average_cs": (int)(avg_cs), "average_time": round(avg_time, 2), "date_created": time.asctime(time.localtime(time.time())) }) #TODO Adjust so that data sometimes updates instead of always deleting #Report data on server to console """display = db.summoners.find().sort([
def summoner(request, match): args = match.split('/') key = os.environ["DEV_KEY"] riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) riotapi.set_rate_limits((3000, 10), (180000, 600)) try: riotapi.set_region(args[0]) summoner = riotapi.get_summoner_by_name(args[1]) except: return HttpResponse("<h1>Summoner was not found on the Server!</h1>") try: match_list = summoner.match_list() except: return HttpResponse("<h1>Summoner {0} was not found on the {1} Server!</h1>".format(args[1], args[0])) l = Lane.objects.all().prefetch_related("stat_set", "stat_set__guide_set", "stat_set__guide_set__author", "stat_set__guide_set__champion") stats_info = {} for lane in l: stats_info[lane.name] = {} for stat in lane.stat_set.all(): stats_info[lane.name][stat.key] = { "name": stat.name, "key": stat.key, "max_value": stat.max_value, "symbol": stat.symbol, "red_start": stat.red_start, "green_start": stat.green_start, "blue_start": stat.blue_start, "blue_end": stat.blue_end, "values": [], "champions": [], "guides": [] } g = stat.guide_set.filter(champion__isnull=True) g_champion = stat.guide_set.filter(champion__isnull=False) guides = [] guides_champion = [] num_guides_champion = lane.guides_champion num_guides_total = lane.guides_total for guide in g: guides.append({ "title": guide.title, "link": guide.link, "author": guide.author.name, "champions": [] }) for guide in g_champion: champion_obj = guide.champion.all() champions = [] for champion in champion_obj: champions.append(champion.name) guides_champion.append({ "title": guide.title, "link": guide.link, "author": guide.author.name, "champions": champions }) stats_info[lane.name][stat.key]["guides"].extend(sample(guides_champion, num_guides_champion if len(guides_champion) > num_guides_champion else len(guides_champion))) num_guides = (num_guides_total - len(guides_champion)) if (num_guides_total - len(guides_champion)) >= 0 else 0 stats_info[lane.name][stat.key]["guides"].extend(sample(guides, num_guides if len(guides) > num_guides else len(guides))) if(match_list): for i, match_reference in enumerate(match_list[0:5]): match = match_reference.match() for participant in match.participants: if participant.summoner_name == summoner.name: lane_key = str(participant.timeline.lane) if lane_key == "Lane.bot_lane": lane_key = str(participant.timeline.role) for lane in l: if(lane_key == lane.key): for stat in lane.stat_set.all(): stats_info[lane.name][stat.key]["champions"].append(participant.champion.name) if stat.symbol == "%": stats_info[lane.name][stat.key]["values"].append(getattr(participant.stats, stat.key) * 100) elif "_per_minute" in stat.key: stats_info[lane.name][stat.key]["values"].append(getattr(participant.stats, stat.key[:-11]) / (match.duration.seconds / 60)) elif stat.key == "duration": stats_info[lane.name][stat.key]["values"].append(match.duration.seconds / 60) else: stats_info[lane.name][stat.key]["values"].append(getattr(participant.stats, stat.key)) else: return HttpResponse("<h1>Summoner {0} has not played any ranked games on the {1} Server!</h1>".format(args[1], args[0])) tasks.add_summoner.delay(summoner.name, Region.objects.get(key=args[0].upper())) context = {"stats_info": {}, "summoner_info": { "name": summoner.name }} for lane, stats in stats_info.items(): context["stats_info"][lane] = [] for info in stats: try: stats_info[lane][info]["average_value"] = sum(stats_info[lane][info]["values"]) / float(len(stats_info[lane][info]["values"])) for guide in stats_info[lane][info]["guides"][:]: if guide["champions"]: if any(i in stats_info[lane][info]["champions"] for i in guide["champions"]): pass else: stats_info[lane][info]["guides"].remove(guide) context["stats_info"][lane].append(stats_info[lane][info]) except ZeroDivisionError: context["stats_info"].pop(lane, None) return render(request, "summoner/stats.html", context)
region = 'NA' key = 'DEV_KEY' riotapi.set_region(region) keyExists = os.environ.get(key) if keyExists == 'None': raise ValueError('Environment variable ' + key + ' does not exist on the system.') riotapi.set_api_key(os.environ[key]) # Load from environment variable. Source: # http://cassiopeia.readthedocs.io/en/latest/setup.html#setting-additional-environment-variables summoner = riotapi.get_summoner_by_name("Verciau") print( "{name} is a level {level} summoner on the NA server. He rocks on these champs:" .format(name=summoner.name, level=summoner.level)) ranked = summoner.ranked_stats() print("{name} has played {numChamps} champions this season.".format( name=summoner.name, numChamps=len(ranked))) for entry in ranked.items(): winRate = entry[1].wins / entry[1].games_played if winRate > 0.5: print("Champ: {champ} | Wins: {wins} | Games Played: {played}".format( champ=entry[0].name, wins=entry[1].wins,
import os import datetime from cassiopeia import riotapi from cassiopeia import baseriotapi from cassiopeia.type.core.common import LoadPolicy import json import heapq riotapi.set_region("EUW") riotapi.print_calls(False) key = "deef6b4f-d2b2-49a1-8aaf-9128a2fc54e3" # 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("eager") summoner = riotapi.get_summoner_by_name("bynikiyo") lista = riotapi.get_ranked_stats(summoner,season=None) dictionary = {} wins = [] for key,value in lista.items(): if str(key) != 'None': sumka = value.assists + value.kills wins.append(value.games_played) listData = [value.games_played,value.assists,value.kills,value.deaths,value.minions_killed,sumka] champ = riotapi.get_champion_by_name(str(key)) dictionary[champ] = listData bestof = heapq.nlargest(5,wins) final = {} for key,value in dictionary.items(): for item in bestof: if str(item) == str(value[0]):
import random from cassiopeia import riotapi riotapi.set_region("NA") riotapi.set_api_key("b14dad6b-9637-43ed-9ec6-57cdcf59a67c") summoner = riotapi.get_summoner_by_name("Crazy Anarchist") #print [method for method in dir(summoner) if callable(getattr(summoner, method))] print summoner.rune_pages()[0]
def get_summoner(): summonerName = raw_input("Summoner name: ") return riotapi.get_summoner_by_name(summonerName)
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 currentgame(zone,summonername): # Make the cgame (try to get this info pass from the ajax eventually) riotapi.set_region(zone) cgame = riotapi.get_current_game(riotapi.get_summoner_by_name(summonername)) # Gather all participants and the champ they play participants = cgame.participants # Show each participants key info like damage type (individual + team aggregate), badges(veteran, newbie, hot streak, etc.), maybe counter info text scraped from lolcounter # Average damage for all roles from now. Add a role filter to adjust it later that player can toggle when they figure out what lane champs go to. # Split into teams blueteam = [] redteam = [] # Holder to construct counters dict to avoid duplicate champs counters_set = set() # Iterate through players for p in participants: # Format data into a dict champs = ChampionGeneral.query.filter_by(key=p.champion.key).all() physicaldmg = sum([value.physicaldmg for value in champs]) / len(champs) magicdmg = sum([value.magicdmg for value in champs]) / len(champs) truedmg = sum([value.truedmg for value in champs]) / len(champs) data = { 'name': p.summoner_name, 'champion': p.champion.name, 'champion_id': p.champion.id, 'champion_key': p.champion.key, 'physical': physicaldmg, 'magical': magicdmg, 'true': truedmg } # Add team average dmg composition and matching advice (AD->Get armor, AP->Get mr, True/mix->Get HP+mix) blue_physical = sum([each['physical'] for each in blueteam]) / 5 blue_magical = sum([each['magical'] for each in blueteam]) / 5 blue_true = sum([each['true'] for each in blueteam]) / 5 red_physical = sum([each['physical'] for each in redteam]) / 5 red_magical = sum([each['magical'] for each in redteam]) / 5 red_true = sum([each['true'] for each in redteam]) / 5 # Make set of champs to fetch counter tips after loop counters_set.add(p.champion.key) print('key') print(p.champion.key) # ====== Add additional info on amount of CC/offensive skills ====== # For each participant # Fetch participant's champion # Fetch tags associated with that champion from db or cass/riotapi and look for CC, heal, shield, etc. # Create a dictionary of CHAMP: [list of tags] # Use dict in template # Add additional info on amount of shields/defensive skills (maybe make it affect the armor/mr suggestion, like # if champions on the team have a lot of shields or effects that already give armor/mr # Sort into teams if p.side.name == 'blue': blueteam.append(data) else: redteam.append(data) # ===Outside for loop=== # Create counters dict counters = {} for champ in counters_set: print('counterchamp and its counters:') print(champ) c = ChampionCounter.query.filter_by(key=champ).first() # Add a dictionary entry of CHAMPNAME : [LIST OF TIPS] counters[champ] = [tip for tip in c.counters] print(counters[champ]) return render_template('currentgame.html', round=round, blueteam=blueteam, blue_average=(blue_physical, blue_magical, blue_true), redteam=redteam, red_average=(red_physical, red_magical, red_true), counters=counters)
def test_summoner_by_name(): int_test_handler.test_result( riotapi.get_summoner_by_name(int_test_handler.summoner_name))
import random from cassiopeia import riotapi riotapi.set_region("BR") riotapi.set_api_key("9bb95c2c-6d74-4b3b-911b-9fda01efc0db") summoner = riotapi.get_summoner_by_name("Yarquen") print("{name} is a level {level} summoner on the BR server." . format(name=summoner.name, level=summoner.level)) champions = riotapi.get_champions() random_champion = random.choice(champions) print("He enjoys playing LoL on all different champions, like {name}.".format(name=random_champion.name)) challenger_league = riotapi.get_challenger() best_na = challenger_league[0].summoner print("He's much better at writing Python code than he is at LoL. He'll never be as good as {name}.".format(name=best_na.name))
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 main(): parser = argparse.ArgumentParser() parser.add_argument("-general", type=str) parser.add_argument("-streamers", type=str) parser.add_argument("-model", type=str) parser.add_argument("-train", action="store_true") parser.add_argument("-update", action="store_true") parser.add_argument("-summoner", type=str) parser.add_argument("-region", type=str) parser.add_argument("-recs", type=int) args = parser.parse_args() setup_cass() if not args.model: args.model = "model.pkl" if args.train and args.update: print("Pick train or update") sys.exit(1) if args.train: if not args.general or not args.streamers: print("Need to specify general and streamers files.") sys.exit(1) with open(args.general, "rb") as in_file: general = pickle.load(in_file) with open(args.streamers, "rb") as in_file: streamers = pickle.load(in_file) riotapi.set_region("NA") recommender = Recommender() recommender.train(general, streamers) recommender.to_file(args.model) elif args.update: if not args.streamers: print("Need to specify streamers file") sys.exit(1) with open(args.streamers, "rb") as in_file: streamers = pickle.load(in_file) recommender = Recommender.from_file(args.model) recommender._update_streamer_tree(streamers) recommender.to_file(args.model) else: if not args.summoner or not args.region: print( "Need to specify summoner and region if recommending, or train if training" ) sys.exit(1) if not args.recs: args.recs = 12 recommender = Recommender.from_file(args.model) riotapi.set_region(args.region) summoner = riotapi.get_summoner_by_name(args.summoner) masteries = summoner_masteries_from_cass(summoner.id) summoner = {"id": summoner.id, "region": args.region} for rec in recommender.recommend(summoner, masteries, num_recommendations=args.recs): print("{} - {}: {}".format(rec["id"], rec["region"], rec["score"]))
deaths = champStats.deaths kda = champStats.kda wins = champStats.wins losses = champStats.losses totalGames = champStats.games_played print_stats( assists, kills, deaths, kda, wins, losses, totalGames, champion) def print_stats( assists, kills, deaths, kda, wins, losses, totalGames, champion): print champion print "Kills: %d" % kills print "Assists: %d" % assists print "Deaths: %d" % deaths print "KDA: %f" % kda print "Total games: %d" % totalGames print "Wins: %d" % wins print "Losses: %d" % losses winPercent = ((wins * 1.0) / totalGames) * 100 print "Win percentage: %f" % winPercent def champs_list( champStats ): for champion in champStats: print "%s : %f" % (champion, (((champStats[champion].wins * 1.0) / champStats[champion].games_played) * 100)) #setup riotapi riotapi_setup() summonerName = raw_input("Summoner name: ") summoner = riotapi.get_summoner_by_name(summonerName) champStats = champion_stats(summoner) #calculate_ability( champStats, champion ) champs_list( champStats )
async def lookup(self, ctx, sumName: str, region: str): """'Summoner Name' 'Region'""" if "'" in sumName: await self.bot.send_message( ctx.message.channel, "Please use double quotes to enclose names.") return await self.bot.send_typing(ctx.message.channel) title = "Summoner Lookup - {0} ({1})".format(sumName, region) em = discord.Embed(title=title, colour=0x1affa7) loop = 0 overallWins = 0 overallLosses = 0 riotapi.set_region(region) summoner = riotapi.get_summoner_by_name(sumName) leagues = riotapi.get_league_entries_by_summoner(summoner) topChamp = riotapi.get_top_champion_masteries(summoner, max_entries=3) topChamps = "{0}, {1} and {2}".format(topChamp[0].champion.name, topChamp[1].champion.name, topChamp[2].champion.name) em.add_field(name="Top Champions", value=topChamps, inline=False) if " " in topChamp[0].champion.name: urlChampName = topChamp[0].champion.name.replace(" ", "") url = 'http://ddragon.leagueoflegends.com/cdn/7.3.3/img/champion/{}.png'.format( urlChampName) elif "Vel'Koz" in topChamp[0].champion.name: url = 'http://ddragon.leagueoflegends.com/cdn/7.3.3/img/champion/Velkoz.png' elif "Kha'Zix" in topChamp[0].champion.name: url = 'http://ddragon.leagueoflegends.com/cdn/7.3.3/img/champion/Khazix.png' elif "Rek'Sai" in topChamp[0].champion.name: url = 'http://ddragon.leagueoflegends.com/cdn/7.3.3/img/champion/RekSai.png' elif "Cho'Gath" in topChamp[0].champion.name: url = 'http://ddragon.leagueoflegends.com/cdn/7.8.1/img/champion/Chogath.png' elif "Kog'Maw" in topChamp[0].champion.name: url = 'http://ddragon.leagueoflegends.com/cdn/7.8.1/img/champion/KogMaw.png' else: url = 'http://ddragon.leagueoflegends.com/cdn/7.3.3/img/champion/{}.png'.format( topChamp[0].champion.name) em.set_thumbnail(url=url) for league in leagues: loop += 1 queue = league.queue.value tier = league.tier.value for entries in league.entries: division = entries.division.value lp = str(entries.league_points) + ' LP' wins = entries.wins overallWins += wins losses = entries.losses overallLosses += losses if queue == 'RANKED_SOLO_5x5': ratio = (wins / (wins + losses) * 100) value = "{0} {1} {2} ({3}W/{4}L {5:.2f}%)".format( tier, division, lp, wins, losses, ratio) em.add_field(name="Ranked Solo", value=value, inline=False) elif queue == 'RANKED_FLEX_SR': ratio = (wins / (wins + losses) * 100) value = "{0} {1} {2} ({3}W/{4}L {5:.2f}%)".format( tier, division, lp, wins, losses, ratio) em.add_field(name="Ranked Flex", value=value, inline=False) elif queue == 'RANKED_FLEX_TT': ratio = (wins / (wins + losses) * 100) value = "{0} {1} {2} ({3}W/{4}L {5:.2f}%)".format( tier, division, lp, wins, losses, ratio) em.add_field(name="Ranked TT", value=value, inline=False) overallRatio = (overallWins / (overallWins + overallLosses) * 100) value1 = "{0}W/{1}L ({2:.2f})%".format(overallWins, overallLosses, overallRatio) em.add_field(name="Overall", value=value1, inline=False) await self.bot.send_message(ctx.message.channel, "", embed=em)