def get_tilt(area, summoner_name): try: watcher = RiotWatcher(API_KEY, default_region=area) champions_dict = get_champions_data(watcher) # check if we have API calls remaining if watcher.can_make_request(): current_app.logger.debug('Requests to API available') else: current_app.logger.error('Too many requests. ' 'Please try again later.') sys.exit(2) try: player = watcher.get_summoner(name=summoner_name, region=area) except LoLException: current_app.logger.debug('Summoner {0} not found.'.format( summoner_name)) raise SummonerNotFound( 'Summoner {0} not found in {1} server.'.format( summoner_name, area.upper())) recent_games = watcher.get_recent_games(player['id'])['games'] response = {"status": 200, "wins": get_wins_number(recent_games), "metadata": { "background": get_random_background_url( champions_dict), "display": get_random_display()}, "stats": get_stats(recent_games, champions_dict), "summoner_name": summoner_name, "tilt_level": get_tilt_level(recent_games)} return response except: current_app.logger.error(traceback.format_exc()) raise
class LeagueGrind(object): def __init__(self, spreadSheetName): # Establish Google Drive Connection json_key = json.load(open('credentials.json')) scope = ['https://spreadsheets.google.com/feeds'] credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'].encode(), scope) gc = gspread.authorize(credentials) self.spreadsheet = gc.open("League Grinds") #Establish Riot API Connection self.riotWatcher = RiotWatcher(getDevKey()) def update_player(self, playerName): # Get the current spread sheet for playerName # If it does not exist, create one for them try: worksheet = self.spreadsheet.worksheet("API-"+playerName) except: self.spreadsheet.add_worksheet("API-"+playerName,1,8) worksheet = self.spreadsheet.worksheet("API-"+playerName) self.init_player_spreadsheet(worksheet) # Determine Last Entered Match rows = worksheet.row_count if rows == 1: lastTimeStamp = 0 else: lastTimeStamp = worksheet.cell(rows,2).value # Get Summoner ID while self.riotWatcher.can_make_request() == False: continue player = self.riotWatcher.get_summoner(name=playerName) playerID = player['id'] # Request Match Meta Data while self.riotWatcher.can_make_request() == False: continue match_list = self.riotWatcher.get_match_list(playerID,region='na',season='SEASON2016') # Send all new Matches to SpreadSheet for f in match_list['matches'][::-1]: if f['timestamp'] > int(lastTimeStamp): Match(playerID,self.riotWatcher,f).log(worksheet) def init_player_spreadsheet(self,worksheet): worksheet.update_cell(1,1,"MatchID") worksheet.update_cell(1,2,"Timestamp") worksheet.update_cell(1,3,"Champion") worksheet.update_cell(1,4,"Kills") worksheet.update_cell(1,5,"Deaths") worksheet.update_cell(1,6,"Assists") worksheet.update_cell(1,7,"KDA") worksheet.update_cell(1,8,"Outcome")
class Request: def __init__(self): self.riot = RiotWatcher(LoL.API_KEY) self.champions = self._getChampions() def _getChampions(self): champion_list = {} champions = self.riot.static_get_champion_list() for champion in champions["data"]: champion_list[champions["data"][champion]["id"]] = champion return champion_list def _checkRequestStatus(self): return self.riot.can_make_request() def retrievePlayerData(self, playerId): while not self._checkRequestStatus(): sleep(2.6) else: player = {} player["id"] = playerId player["summoner"] = self.riot.get_summoner(name=playerId) player["match_history"] = self.riot.get_match_history(player["summoner"]["id"]) return player
from riotwatcher import RiotWatcher import time leagueApi = RiotWatcher('04328930-7ab0-4e23-8c83-af1bbc4147ea') #Get Summoner ID and Stats summoner = raw_input("Enter your summoner name: ") opponent = raw_input("Enter your opponent's summoner name:") if leagueApi.can_make_request(): summonerId = leagueApi.get_summoner(name=summoner) opponentId = leagueApi.get_summoner(name=opponent) print print "Welcome Summoner!" bet = raw_input("Enter the amount of $ you would like to bet: ") print print "You've bet", bet, "dollars" lastPlayedGame = leagueApi.get_recent_games(summonerId['id'])['games'][0]['createDate'] currentDate = lastPlayedGame print "Waiting for you to play a game!" while lastPlayedGame == currentDate: #Checks every 10 seconds for new game time.sleep(10) currentDate = leagueApi.get_recent_games(summonerId['id'])['games'][0]['createDate'] #Need to also make a check to see if the other player was playing summonerGameId = leagueApi.get_recent_games(summonerId['id'])['games'][0]['gameId'] opponentGameId = leagueApi.get_recent_games(opponentId['id'])['games'][0]['gameId']
from riotwatcher import RiotWatcher from riotwatcher import EUROPE_WEST import operator #Your API key here w = RiotWatcher('') if w.can_make_request(): dict = {} num_players = input('How many players are we comparing?\n') for x in range(0, num_players): player_name = raw_input('Enter player name\n') player = w.get_summoner(name = player_name, region = EUROPE_WEST) #Hihgly complex algorithm designed to predict a players ability to play legaue dict[player['name']] = player['id']/player['profileIconId'] + player['revisionDate']/player['id'] sortDic = sorted(dict.items(), key=operator.itemgetter(1)) print "The best player is:\n" print dict.keys()[0] else: print "You aren't allowed to"
import urllib2, json, sys, os from riotwatcher import RiotWatcher from datetime import datetime today = datetime.now() if len(sys.argv) != 3: print "Usage: python summonerids.py [max_summoners] [API_KEY]" sys.exit(0) max_summoners = int(sys.argv[1]) # input q = [] API_KEY = sys.argv[2] w = RiotWatcher(API_KEY) startid = '20120281' q.append(int(startid)) # opening a json gamehistory file if w.can_make_request() == True: readfile = urllib2.urlopen('https://na.api.pvp.net/api/lol/na/v1.3/game/by-summoner/' + startid + '/recent?api_key=' + API_KEY) data = json.load(readfile) for game in data["games"]: if game["subType"] == "RANKED_SOLO_5x5": for player in game["fellowPlayers"]: if player["summonerId"] not in q: q.append(player["summonerId"]) # print q i = 1 while len(q) < max_summoners: if w.can_make_request() == True: if i >= len(q): print "only scraped " + str(i) + " summoners" max_summoners = len(q)
91 : 'NIGHTMARE BOT 5x5 RANK1', # Doom Bots Rank 1 games 92 : 'NIGHTMARE BOT 5x5 RANK2', # Doom Bots Rank 2 games 93 : 'NIGHTMARE BOT 5x5 RANK5', # Doom Bots Rank 5 games 96 : 'ASCENSION 5x5', # Ascension games 98 : 'HEXAKILL Twisted Treeline', # Twisted Treeline 6x6 Hexakill games 100: 'BILGEWATER ARAM 5x5', # Butcher's Bridge games 300: 'KING PORO 5x5', # Poroking 5v5 310: 'COUNTER PICK (NEMESIS)', # Nemesis games 313: 'BILGEWATER 5x5', # Black Market Brawlers games 400: 'TEAM_BUILDER_DRAFT_UNRANKED_5x5', #Dynamic queue? 410: 'TEAM_BUILDER_DRAFT_RANKED_5x5', #Dynamic queue? 999: UNKNOWN #Map is not known or RIOT API didnt provide queue Type ID. } # check if we have API calls remaining logger.debug('Lets check if we can make requests to the Riot API: ' + str(w.can_make_request())) # Get Region Parameters out of cfg-file def get_region_params(region_name): region_params = {'Region' : config.get(region_name, 'region'), 'PlatformID': config.get(region_name, 'platformID'), 'Domain' : config.get(region_name, 'domain'), 'Port' : config.get(region_name, 'port')} return region_params def get_regions(): return config.sections() def get_match_details(summoner_name, region_name='EUW'):
async def on_ready(bot): # Obtain all static data required watcher = RiotWatcher(bot.configurations['discrank.py']['token']) if not watcher.can_make_request(): raise BotException(ErrorTypes.STARTUP, EXCEPTION, "The given Riot API token cannot get requests.") # Add champions by ID and name, and skills by ID champions = watcher.static_get_champion_list(data_by_id=True)['data'] champions_named = watcher.static_get_champion_list()['data'] champions_named = dict( (key.lower(), value) for key, value in champions_named.items()) champions.update(champions_named) spells = watcher.static_get_summoner_spell_list(data_by_id=True)['data'] # Add game modes by queue type and name modes = { "0": "Custom", "8": "Normal 3v3", "2": "Normal", "14": "Normal Draft", "4": "Dynamic Queue", "6": "Dynamic Queue", "9": "Ranked 3v3", "41": "Ranked 3v3", "42": "Ranked 5v5", "16": "This Gamemode doesn't even exist anymore", "17": "Same with this one", "7": "Co-op vs AI", "25": "Co-op vs AI", "31": "Co-op vs AI", "32": "Co-op vs AI", "33": "Co-op vs AI", "52": "Co-op vs AI (3v3)", "61": "Team Builder", "65": "ARAM", "70": "One For All", "72": "Magma Chamber 1v1", "73": "Magma Chamber 2v2", "75": "Hexakill", "76": "URF", "83": "Co-op vs AI (URF)", "91": "Doom Bots Lv 1", "92": "Doom Bots Lv 2", "93": "Doom Bots Lv 3", "96": "Ascension", "98": "Hexakill", "100": "Bilgewater", "300": "Legend of the Poro King", "313": "Bilgewater ARAM", "400": "Team Builder", "410": "Dynamic Queue", "CUSTOM": "0", "NORMAL_3x3": "8", "NORMAL_5x5_BLIND": "2", "NORMAL_5x5_DRAFT": "14", "RANKED_SOLO_5x5": "4", "RANKED_PREMADE_5x5*": "6", "RANKED_PREMADE_3x3*": "9", "RANKED_TEAM_3x3": "41", "RANKED_TEAM_5x5": "42", "ODIN_5x5_BLIND": "16", "ODIN_5x5_DRAFT": "17", "BOT_5x5*": "7", "BOT_ODIN_5x5": "25", "BOT_5x5_INTRO": "31", "BOT_5x5_BEGINNER": "32", "BOT_5x5_INTERMEDIATE": "33", "BOT_TT_3x3": "52", "GROUP_FINDER_5x5": "61", "ARAM_5x5": "65", "ONEFORALL_5x5": "70", "FIRSTBLOOD_1x1": "72", "FIRSTBLOOD_2x2": "73", "SR_6x6": "75", "URF_5x5": "76", "BOT_URF_5x5": "83", "NIGHTMARE_BOT_5x5_RANK1": "91", "NIGHTMARE_BOT_5x5_RANK2": "92", "NIGHTMARE_BOT_5x5_RANK5": "93", "ASCENSION_5x5": "96", "HEXAKILL": "98", "BILGEWATER_ARAM_5x5": "100", "KING_PORO_5x5": "300", "COUNTER_PICK": "310", "BILGEWATER_5x5": "313", "TEAM_BUILDER_DRAFT_UNRANKED_5x5": "400", "TEAM_BUILDER_DRAFT_RANKED_5x5": "410" } bot.data['discrank.py'] = [watcher, champions, spells, modes]
from riotwatcher import RiotWatcher import json w = RiotWatcher('21e6bb30-08e1-47ed-946f-cee514b740d8') # check if we have API calls remaining print(w.can_make_request()) me = w.get_summoner(name='Lustboy') #print(me) # takes list of summoner ids as argument, supports up to 40 at a time # (limit enforced on riot's side, no warning from code) #my_mastery_pages = w.get_mastery_pages([me['id'], ])[str(me['id'])] #print(my_mastery_pages)s recentGames = w.get_match_list(me['id'])['matches'] print(json.dumps(recentGames)) lane15 = { "DUO_CARRY": float(0), "DUO": float(0), "DUO_SUPPORT": float(0), "MID": float(0), "JUNGLE": float(0), "TOP": float(0), "SOLO": float(0) } lane13 = { "DUO_CARRY": float(0), "DUO": float(0), "DUO_SUPPORT": float(0),
class Lol: def __init__(self, key, default_region=EUROPE_WEST): self.lol_watcher = RiotWatcher(key, default_region=default_region) self.wait() self.champion_list = self.lol_watcher.static_get_champion_list( )['data'] def wait(self): while not self.lol_watcher.can_make_request(): time.sleep(1) def test_map(self, _id): if _id == 1: return "Summoner's Rift" elif _id == 2: return "Summoner's Rift" elif _id == 3: return "The Proving Grounds (tuto)" elif _id == 4: return "Twisted Treeline" elif _id == 8: return "The Crystal Scar" elif _id == 10: return "Twisted Treeline" elif _id == 11: return "Summoner's Rift" elif _id == 12: return "Howling Abyss" elif _id == 14: return "Butcher's Bridge" def test_queue(self, _id): if _id == 0: return "Custom" elif _id == 2: return "Normal 5v5 blind" elif _id == 4: return "Ranked Solo 5v5" elif _id == 6: return "Ranked Premade 5v5" elif _id == 7: return "Coop vs ia 5v5" elif _id == 8: return "Normal 3v3" elif _id == 9: return "Ranked flex" elif _id == 14: return "Normal Draft 5v5" elif _id == 16: return "Odin 5v5 Blind" elif _id == 17: return "Odin 5v5 Draft" elif _id == 25: return "Coop vs ia 5v5" elif _id == 31: return "Coop vs ia (intro)" elif _id == 32: return "Coop vs ia (beginner)" elif _id == 33: return "Coop vs ia (Intermediate)" elif _id == 41: return "Ranked Team 3v3" elif _id == 52: return "Ranked Team 5v5" elif _id == 61: return "GROUP_FINDER_5v5" elif _id == 65: return "Aram" elif _id == 70: return "One For All" elif _id == 72: return "FIRSTBLOOD_1v1" elif _id == 73: return "FIRSTBLOOD_2v2" elif _id == 75: return "Hexakill" elif _id == 76: return "URF" elif _id == 78: return "One For All" elif _id == 83: return "Bot URF" elif _id == 91: return "DOOM Bot (rank 1)" elif _id == 92: return "DOOM Bot (rank 2)" elif _id == 93: return "DOOM Bot (rank 5)" elif _id == 96: return "Ascension" elif _id == 98: return "Hexakill" elif _id == 100: return "BILGEWATER_ARAM_5v5" elif _id == 300: return "Poro King" elif _id == 310: return "COUNTER_PICK" elif _id == 313: return "BILGEWATER_5v5" elif _id == 315: return "Siege" elif _id == 317: return "Definitly Not Dominion" elif _id == 318: return "Aram URF" elif _id == 400: return "Normal Draft" elif _id == 410: return "Ranked" elif _id == 420: return "Ranked Solo/Duo" elif _id == 440: return "Ranked Flex" def test_champ(self, _id): temp = [] for k in self.champion_list: temp.append(self.champion_list[k]) temp = [nb for nb in temp if nb['id'] == _id] return temp[0]['name'] def test_ranked_stats(self, stats, key): stats = stats['champions'] stats = [nb for nb in stats if nb['id'] == 0] stats = stats[0]['stats'] return stats[key] def test_team(self, _id): if _id == 100: return ":large_blue_circle:" else: return ":red_circle:" def check_lol(self, player, region): try: self.wait() return self.lol_watcher.get_summoner(name=player, region=region) except LoLException as e: if e == error_429: return ":x: Resseye dans {} secondes.".format( e.headers['Retry-After']) elif e == error_404: return ":x: Summoner inconnu : {}".format(player) def message_lol(self, summoner): message = ":information_source: {} :video_game:\n\n".format( summoner['name']) message += " :information_source: Général Stats\n" message += " **ID**: {}\n".format(summoner['id']) message += " **Level**: {}\n".format(summoner['summonerLevel']) self.wait() temp = self.lol_watcher.get_league(summoner_ids=[summoner['id']]) rank = [] for i in temp[str(summoner['id'])]: rank.append(i['queue'] + " " + i['tier']) message += " **Rank**: {}\n".format(rank) #message += " **Mastery Levels**: {}\n".format() #message += " **Mastery Points**: {}\n".format() #message += " **Mastery Tokens**: {}\n".format() self.wait() player_stats = self.lol_watcher.get_stat_summary( summoner['id'])['playerStatSummaries'] player_stats = [ nb for nb in player_stats if nb['playerStatSummaryType'] == 'Unranked' ] player_stats = player_stats[0] message += " **Wins**: {}\n".format(player_stats['wins']) message += " **Kills**: {}\n".format( player_stats['aggregatedStats']['totalChampionKills']) message += " **Assistances**: {}\n".format( player_stats['aggregatedStats']['totalAssists']) message += " **Creeps tués**: {}\n".format( player_stats['aggregatedStats']['totalMinionKills']) message += " **Tourelles détruite**: {}\n\n".format( player_stats['aggregatedStats']['totalTurretsKilled']) #message += " **Dernière connexion**: {}\n\n".format() message += ":information_source: Ranked Stats :\n" try: self.wait() ranked_stats = self.lol_watcher.get_ranked_stats(summoner['id']) message += " **Win:** {}\n".format( self.test_ranked_stats(ranked_stats, 'totalSessionsWon')) message += " **Loose:** {}\n".format( self.test_ranked_stats(ranked_stats, 'totalSessionsLost')) message += " **Kill:** {}\n".format( self.test_ranked_stats(ranked_stats, 'totalChampionKills')) message += " **Assistance:** {}\n".format( self.test_ranked_stats(ranked_stats, 'totalAssists')) message += " **Damages infligés:** {}\n".format( self.test_ranked_stats(ranked_stats, 'totalDamageDealt')) message += " **Damages Reçus:** {}\n".format( self.test_ranked_stats(ranked_stats, 'totalDamageTaken')) message += " **Argent gagné:** {}\n".format( self.test_ranked_stats(ranked_stats, 'totalGoldEarned')) message += " **Creeps tués:** {}\n".format( self.test_ranked_stats(ranked_stats, 'totalMinionKills')) message += " **Tourelles détruites:** {}\n".format( self.test_ranked_stats(ranked_stats, 'totalTurretsKilled')) message += " **Double kills:** {}\n".format( self.test_ranked_stats(ranked_stats, 'totalDoubleKills')) message += " **Triple kills:** {}\n".format( self.test_ranked_stats(ranked_stats, 'totalTripleKills')) message += " **Quadra kills:** {}\n".format( self.test_ranked_stats(ranked_stats, 'totalQuadraKills')) message += " **Penta kills:** {}\n".format( self.test_ranked_stats(ranked_stats, 'totalPentaKills')) message += " **Total Killing Spree:** {}\n\n".format( self.test_ranked_stats(ranked_stats, 'killingSpree')) except: message += "**Aucune Stats de Ranked n'a été trouvée !**\n\n" message += ":information_source: Game en cours :\n" try: self.wait() temp = self.lol_watcher.get_current_game(summoner['id']) message += " **ID Partie:** {}\n".format(temp['gameId']) message += " **GameMode:** {}\n".format(temp['gameMode']) message += " **GameType:** {}\n".format(temp['gameType']) message += " **ID Queue:** {}\n".format( self.test_queue(temp['gameQueueConfigId'])) message += " **ID Platform:** {}\n".format(temp['platformId']) message += " **ID Map:** {}\n".format(self.test_map(temp['mapId'])) for i in temp['participants']: message += " " + i['summonerName'] + " (" + self.test_champ( i['championId']) + ") Team: " + self.test_team( i['teamId']) + "\n" except: message += "**Aucune game en cours...**" return message
__author__ = 'Vixus' from riotwatcher import RiotWatcher w = RiotWatcher('eda1ed56-6ae8-41bf-97b7-acaa970537dc') # check if we have API calls remaining print(w.can_make_request()) me = w.get_summoner(name='vixus360') print(me) # championList = w.static_get_champion_list() # print championList # print w.get_champion(championList['data']['Lux']['id']) def print_tabs(count): for i in range(count): print '\t', def print_data(obj,tabCount=-1): if type(obj) == dict: for key, value in obj.items(): print_tabs(tabCount) if hasattr(value, '__iter__'): print key,":" print_data(value,tabCount+1) else: print '%s : %s' % (key, value) elif type(obj) == list: for value in obj:
#!/usr/bin/python #matplotlib inline import re import io from riotwatcher import RiotWatcher #library for api key from riotwatcher import EUROPE_WEST #region library euw = RiotWatcher('RGAPI-62c12c6d-5a21-4d8e-96b2-c3cad4aa9baa', default_region=EUROPE_WEST) #check if we have API calls remaining, due to rate limit, 10request/10sec -> 500r/600sec print(euw.can_make_request()) ##API request def getJSONReply(URL): response = urllib2.urlopen(URL); html = response.read(); data = json.loads(html); return data; ##matchlist api request def getmatchId(SummonerID,Region, Key): #url request as the default API config matchList_URL = "https://" +Region.lower()+ ".api.pvp.net/api/lol/" +Region.lower()+ "/v2.2/matchlist/by-summoner/" +`SummonerID`+ "?api_key=" +Key matchList_data = getJSONReply(matchList_URL) matches = matchList_data['matches'] match_id = [] for i in range(len(matches)): match_id.append(matches[i]['matchId']) fo = io.open('Match_List.json', 'w', encoding='utf-8') fo.write(unicode(json.dumps(matches, ensure_ascii=False))) ##can't save match_ID because of too many request
'summoner_ids.txt'), "r") as sidfile: sids = [int(sid) for sid in sidfile.read().splitlines()] # Loop though list of summoners and get their data for sid in sids: if lastSummonerId != None: if sid == lastSummonerId: lastSummonerId = None else: continue idx = 0 inc = 1 retry = 0 while True: try: # Check to make sure we can make a request so that we don't exceede the rate limit while not w.can_make_request(): time.sleep(0) matches = w.get_match_history( sid, region=NORTH_AMERICA, ranked_queues=['RANKED_SOLO_5x5'], begin_index=idx, end_index=idx + inc) if "matches" in matches: for m in matches["matches"]: print((sid, m["matchId"])), match = get_common_match_data(m) participants = {} for p in m["participants"]: participants[p["participantId"]] = p for p in m["participantIdentities"]:
with open (os.path.join(os.path.dirname(os.path.realpath(__file__)), 'summoner_ids.txt'), "r") as sidfile: sids = [int(sid) for sid in sidfile.read().splitlines()] # Loop though list of summoners and get their data for sid in sids: if lastSummonerId != None: if sid == lastSummonerId: lastSummonerId = None else: continue idx = 0 inc = 1 retry = 0 while True: try: # Check to make sure we can make a request so that we don't exceede the rate limit while not w.can_make_request(): time.sleep(0) matches = w.get_match_history(sid,region=NORTH_AMERICA,ranked_queues=['RANKED_SOLO_5x5'],begin_index=idx,end_index=idx+inc) if "matches" in matches: for m in matches["matches"]: print((sid,m["matchId"])), match = get_common_match_data(m) participants = {} for p in m["participants"]: participants[p["participantId"]] = p for p in m["participantIdentities"]: participants[p["participantId"]].update(p["player"]) for p in participants: if participants[p]['summonerId']==sid: participant = get_participant_match_data(participants[p]) stats = get_participant_match_stat_data(participants[p]['stats'])
92: 'NIGHTMARE BOT 5x5 RANK2', # Doom Bots Rank 2 games 93: 'NIGHTMARE BOT 5x5 RANK5', # Doom Bots Rank 5 games 96: 'ASCENSION 5x5', # Ascension games 98: 'HEXAKILL Twisted Treeline', # Twisted Treeline 6x6 Hexakill games 100: 'BILGEWATER ARAM 5x5', # Butcher's Bridge games 300: 'KING PORO 5x5', # Poroking 5v5 310: 'COUNTER PICK (NEMESIS)', # Nemesis games 313: 'BILGEWATER 5x5', # Black Market Brawlers games 400: 'TEAM_BUILDER_DRAFT_UNRANKED_5x5', #Dynamic queue? 410: 'TEAM_BUILDER_DRAFT_RANKED_5x5', #Dynamic queue? 999: UNKNOWN #Map is not known or RIOT API didnt provide queue Type ID. } # check if we have API calls remaining logger.debug('Lets check if we can make requests to the Riot API: ' + str(w.can_make_request())) # Get Region Parameters out of cfg-file def get_region_params(region_name): region_params = { 'Region': config.get(region_name, 'region'), 'PlatformID': config.get(region_name, 'platformID'), 'Domain': config.get(region_name, 'domain'), 'Port': config.get(region_name, 'port') } return region_params def get_regions():