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 main: def __init__(self, _APIkey, _sumName, _matchNo, _region, _rankedType): # ==== Definitions self._gameType = '' if _rankedType == "solo": self._gameType = 'RANKED_TEAM_5x5' elif _rankedType == "ranked": self._gameType = 'RANKED_SOLO_x5' self._APIkey = _APIkey # API key for developers self._summoner_name = _sumName # Name of LoL Summoner self._watcherObj = RiotWatcher(self._APIkey) # riotwatcher data self._sumObj = self._watcherObj.get_summoner(name=self._summoner_name, region=_region) # Data on Summoner self._sID = self._sumObj['id'] # ID of Summoner self._match = _matchNo # ID of match to work with self._sumGames = self._watcherObj.get_match_history(summoner_id=self._sID, region=_region, ranked_queues=self._gameType) self._stats1 = json.dumps(self._watcherObj.get_match(self._match, region=_region, include_timeline='true')) self._parsed1 = json.loads(self._stats1) self._matchId = self._parsed1['matchId'] self._mapId = self._parsed1['mapId'] def getPeopleForMatch(self): _people = {} # ID | name for a in self._parsed1['participantIdentities']: _people[a['player']['summonerId']] = str(a['player']['summonerName']) return _people def getParticipantsForMatch(self): _participants = {} # number | ID for values in self._parsed1['participantIdentities']: _participants[values['participantId']] = values['player']['summonerId'] return _participants def getEventsPerPerson(self): _eventsPerPerson = {} for count in range(10): _eventsPerPerson[str(count + 1)] = [] for items in self._parsed1['timeline']['frames']: # ignores wards try: tempList = items['events'] for vals in tempList: #if "participantId" in str(vals): # _eventsPerPerson[str(vals['participantId'])] = _eventsPerPerson[str(vals['participantId'])] + [vals] if "killerId" in str(vals) and "BUILDING_KILL" not in str(vals): _eventsPerPerson[str(vals['killerId'])] = _eventsPerPerson[str(vals['killerId'])] + [vals] except KeyError: continue # print "skipped", str(items['participantFrames']) return _eventsPerPerson def getFramesPerPerson(self): _framesPerPerson = {} for count in range(10): _framesPerPerson[str(count + 1)] = [] for values in self._parsed1['timeline']['frames']: for count in range(1, 11): tempDict = dict(values['participantFrames'][str(count)]) _framesPerPerson[str(count)] = _framesPerPerson[str(count)] + [tempDict] return _framesPerPerson #for key in _eventsPerPerson: # print "Participant:", str(key) # for events in _eventsPerPerson[key]: # temp = json.dumps(events, indent=4, sort_keys=True) # print temp #match = 1960675310 #run = main('', "StirlingArcher69", match) #print "==== Match details for", str(match), "====" #print(json.dumps(run.getEventsPerPerson(), indent=4, sort_keys=True))
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 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): player = self.riotWatcher.get_summoner(name=playerName) playerID = player['id'] match_list = self.riotWatcher.get_match_list(playerID,region='na',season='SEASON2016') if raw_input("Get Match Data? yes/no\n") == "yes": matches = [Match(playerID,self.riotWatcher,f) for f in match_list['matches']]
def on_button_click(self): self.error_label.configure(text='validating...') w = RiotWatcher(self.apikey.get()) #validate summoner name and api key try: me = w.get_summoner(name=self.summoner.get(), region=self.region_var.get()) print me #save new settings self.settings['summonerName'] = self.summoner.get() self.settings['region'] = self.region_var.get() self.settings['apikey'] = self.apikey.get() with open('settings.json', 'w') as f: json.dump(self.settings, f) self.error_label.configure(text='settings saved!') except Exception as error: if error.error == "Unauthorized": self.error_label.configure(text='API Key is invalid!') else: self.error_label.configure(text='Summoner does not exist!')
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
def league_rank(self, **options): try: from riotwatcher import RiotWatcher, LoLException except ImportError: log.error('Missing required module for League Rank module: riotwatcher') return False source = options['source'] message = options['message'] bot = options['bot'] riot_api_key = self.settings['riot_api_key'] summoner_name = self.settings['default_summoner'] def_region = self.settings['default_region'] if len(riot_api_key) == 0: log.error('Missing riot API key in settings.') return False region_list = ['br', 'eune', 'euw', 'kr', 'lan', 'las', 'na', 'oce', 'ru', 'tr'] if message: summoner_name = message.split()[0] try: region = message.split()[1].lower() except IndexError: region = def_region.lower() if region not in region_list: bot.whisper(source.username, 'Region is not valid. Please enter a valid region, region is optional and the default region is {}'.format(def_region.upper())) return False else: pass else: region = def_region.lower() if len(summoner_name) == 0 or len(region) == 0: return False error_404 = 'Game data not found' error_429 = 'Too many requests' try: rw = RiotWatcher(riot_api_key, default_region=region) summoner = rw.get_summoner(name=summoner_name) summoner_id = str(summoner['id']) summoner_name = summoner['name'] except LoLException as e: if e == error_429: bot.say('Too many requests. Try again in {} seconds'.format(e.headers['Retry-After'])) return False elif e == error_404: bot.say('The summoner not found. Use a valid summoner name (remove spaces) and region FailFish') return False else: log.info('Something unknown went wrong: {}'.format(e)) return False try: summoner_league = rw.get_league_entry(summoner_ids=(summoner_id, )) tier = summoner_league[summoner_id][0]['tier'] division = summoner_league[summoner_id][0]['entries'][0]['division'] league_points = summoner_league[summoner_id][0]['entries'][0]['leaguePoints'] bot.say('The Summoner {} on region {} is currently in {} {} with {} LP 4Head'.format(summoner_name, region.upper(), tier, division, league_points)) except LoLException as e: if e == error_429: bot.say('Too many requests. Try again in {} seconds'.format(e.headers['Retry-After'])) return False elif e == error_404: bot.say('The Summoner {} on region {} is currently UNRANKED.. FeelsBadMan'.format(summoner_name, region.upper())) return False else: bot.say('Trouble fetching summoner rank.. Kappa Try again later!') return False
class DataStore: """ DataStore is the script that reads json repsonses from the League of Legends API and stores these responses to disk in the respective player's folder. """ def __init__(self, api, sumName, region): """ Initialisation function. :param api: The API key for the user, this is obtained through Riot's developer site. :param sumName: The name of the LoL Summoner that data will be pulled for. :param region: The region that the Summoner plays in. :return: None """ self.watcherOb = RiotWatcher(api) # LolStats # The match history is a temporary solution to get this done quick, # basically it just dumps a match history file every time instead of # adding on to the current one. :( self.origDir = os.getcwd() self._playerName = sumName self._playerRegion = region self._playerData = '' self._playerID = 0 self._playerHist = '' if self._playerRegion != '': self._playerData = self.watcherOb.get_summoner(name=self._playerName, region=self._playerRegion) self._playerID = int((self.watcherOb.get_summoner(name=self._playerName, region=self._playerRegion))['id']) self._playerHist = self.watcherOb.get_match_history(summoner_id=self._playerID, ranked_queues='RANKED_SOLO_5x5', region=self._playerRegion) else: self._playerData = self.watcherOb.get_summoner(name=self._playerName) self._playerID = int((self.watcherOb.get_summoner(name=self._playerName))['id']) self._playerHist = self.watcherOb.get_match_history(summoner_id=self._playerID, ranked_queues='RANKED_SOLO_5x5') #print self._playerHist self._playerMatches = [] for allVals in self._playerHist['matches']: self._playerMatches.append(allVals['matchId']) _dir = str(os.getcwd())+"/static/json/" # Dir creation def writer(_dir, _file, _data, _json): """ Helper function to write data to the disk. :param _dir: The directory to store the data. :param _file: The name to call the file that is created. :param _data: The data object to write to the file. :param _json: Flag to indicate if the data is JSON or not. :return: None """ writeFile = open(str(_dir)+"/"+str(_file), "w") if _json is True: writeFile.write(json.dumps(_data, indent=4)) else: writeFile.write(_data) writeFile.close() if not os.path.exists(_dir+str(self._playerID)): os.makedirs(str(_dir+str(self._playerID))) writer((str(_dir+str(self._playerID))), "_playerData.json", self._playerData, True) writer((str(_dir+str(self._playerID))), "_playerHist1.json", self._playerHist, True) else: if not os.path.isfile(str(_dir+str(self._playerID)+"/_playerData.json")): writer((str(_dir+str(self._playerID))), "_playerData.json", self._playerData, True) if not os.path.isfile(str(_dir+str(self._playerID)+"/_playerHist1.json")): writer((str(_dir+str(self._playerID))), "_playerHist1.json", self._playerHist, True) elif os.path.isfile(str(_dir+str(self._playerID)+"/_playerHist1.json")): os.chdir(_dir+str(self._playerID)) temp = glob.glob("_playerHist*") inc = int(re.search(r'\d+', str(temp[-1])).group()) + 1 writer((str(_dir+str(self._playerID))), "_playerHist"+str(inc)+".json", self._playerHist, True) if filecmp.cmp("_playerHist"+str(inc-1)+".json", "_playerHist"+str(inc)+".json") is True: os.remove("_playerHist"+str(inc)+".json") os.chdir(self.origDir) if not os.path.exists(_dir+str(self._playerID)+"/matchData"): os.makedirs(_dir+str(self._playerID)+"/matchData") os.chdir(_dir+str(self._playerID)) for i in glob.glob("_playerHist*"): temp = json.load(open(i, 'r')) for vals in temp['matches']: if not os.path.isfile(str(_dir+str(self._playerID)+"/matchData/"+str(vals['matchId'])+".json")): writer(str(_dir+str(self._playerID)+"/matchData/"), str(vals['matchId'])+".json", self.watcherOb.get_match(match_id=vals['matchId'], include_timeline=True), True) os.chdir(self.origDir) def getPlayerID(self): return self._playerID
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),
from riotwatcher import RiotWatcher import json w = RiotWatcher('RGAPI-bcc0bb05-6e09-4d0c-b7dd-49fd76069f19', default_region='jp') summoner = w.get_summoner(name='Sethena') summoner_id = summoner['id'] results = w.get_recent_games(summoner_id) a = "" i = 0 for result in results['games']: for player in result['fellowPlayers']: #print(player['summonerId']) a += str(player['summonerId']) a += "\n" i += 1 if i % 9 == 0: a += "\n" print(a) print(i) #with open('saveresults.json','w') as file: # file.write(json.dumps(player['summonerId']) #for sumid in player['summonerId']: # print(sumid) #with open(str(result['gameId'])+'.json','w') as file: # file.write(json.dumps(result)) #print(summoner) #print(summoner_id) #print(results)
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
"rPercentAttackSpeedModPerLevel": ["+", "%" + " attack speed at level 18", 1800], "rPercentCooldownMod": ["+", "%" + " cooldown reduction", 100], "rPercentCooldownModPerLevel": ["+", "%" + " cooldown reduction at level 18", 1800], "rPercentMagicPenetrationMod": ["+", "%" + " magic penetration", 100], "rPercentMagicPenetrationModPerLevel": ["+", "%" + " magic penetration at level 18", 1800], "rPercentMovementSpeedModPerLevel": ["+", "%" + " movement speed at level 18", 1800], "rPercentTimeDeadMod": ["-", "%" + " time spent dead", 100], "rPercentTimeDeadModPerLevel": ["-", "%" + " time spent dead at level 18", 1800] } me = watcher1.get_summoner(name=name) my_id = me['id'] #Returns an array [val, k, d, a, gamesPlayed, winRate] where val is -1 (scrub), 0 (normal), or 1 (one trick) def isOneTrick(player): watcher = getWatcher() try: stats = watcher.get_ranked_stats(player['summonerId'])['champions'] except: return (-1, 0.0, 0.0, 0.0, 0, 0.0) allIndex = -1 try: allIndex = next(index for (index, d) in enumerate(stats) if d['id'] == 0) except:
__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)
def league_rank(self, bot, source, message, **rest): try: from riotwatcher import RiotWatcher, LoLException except ImportError: log.error( "Missing required module for League Rank module: riotwatcher") return False riot_api_key = self.settings["riot_api_key"] summoner_name = self.settings["default_summoner"] def_region = self.settings["default_region"] if len(riot_api_key) == 0: log.error("Missing riot API key in settings.") return False region_list = [ "br", "eune", "euw", "kr", "lan", "las", "na", "oce", "ru", "tr" ] if message: summoner_name = message.split()[0] try: region = message.split()[1].lower() except IndexError: region = def_region.lower() if region not in region_list: bot.whisper( source, f"Region is not valid. Please enter a valid region, region is optional and the default region is {def_region.upper()}", ) return False else: pass else: region = def_region.lower() if len(summoner_name) == 0 or len(region) == 0: return False error_404 = "Game data not found" error_429 = "Too many requests" try: rw = RiotWatcher(riot_api_key, default_region=region) summoner = rw.get_summoner(name=summoner_name) summoner_id = str(summoner["id"]) summoner_name = summoner["name"] except LoLException as e: if e == error_429: bot.say( f"Too many requests. Try again in {e.headers['Retry-After']} seconds" ) return False elif e == error_404: bot.say( "The summoner not found. Use a valid summoner name (remove spaces) and region FailFish" ) return False else: log.info(f"Something unknown went wrong: {e}") return False try: summoner_league = rw.get_league_entry(summoner_ids=(summoner_id, )) tier = summoner_league[summoner_id][0]["tier"] division = summoner_league[summoner_id][0]["entries"][0][ "division"] league_points = summoner_league[summoner_id][0]["entries"][0][ "leaguePoints"] bot.say( f"The Summoner {summoner_name} on region {region.upper()} is currently in {tier} {division} with {league_points} LP 4Head" ) except LoLException as e: if e == error_429: bot.say( f"Too many requests. Try again in {e.headers['Retry-After']} seconds" ) return False elif e == error_404: bot.say( f"The Summoner {summoner_name} on region {region.upper()} is currently UNRANKED.. FeelsBadMan" ) return False else: bot.say( "Trouble fetching summoner rank.. Kappa Try again later!") return False
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"
def league_rank(self, **options): try: from riotwatcher import RiotWatcher, LoLException except ImportError: log.error('Missing required module for League Rank module: riotwatcher') return False source = options['source'] message = options['message'] bot = options['bot'] riot_api_key = self.settings['riot_api_key'] summoner_name = self.settings['default_summoner'] def_region = self.settings['default_region'] region_list = ['br', 'eune', 'euw', 'kr', 'lan', 'las', 'na', 'oce', 'ru', 'tr'] if message: summoner_name = message.split()[0] try: region = message.split()[1].lower() except IndexError: region = def_region.lower() if region not in region_list: bot.whisper(source.username, 'Region is not valid. Please enter a valid region, region is optional and the default region is {}'.format(def_region.upper())) return False else: pass else: region = def_region.lower() error_404 = "Game data not found" error_429 = "Too many requests" try: rw = RiotWatcher(riot_api_key, default_region=region) summoner = rw.get_summoner(name=summoner_name) summoner_id = str(summoner['id']) summoner_name = summoner['name'] except LoLException as e: if e == error_429: bot.say('Too many requests. Try again in {} seconds'.format(e.headers['Retry-After'])) return False elif e == error_404: bot.say('The summoner not found. Use a valid summoner name (remove spaces) and region FailFish') return False try: summoner_league = rw.get_league_entry(summoner_ids=(summoner_id, )) tier = summoner_league[summoner_id][0]['tier'] division = summoner_league[summoner_id][0]['entries'][0]['division'] league_points = summoner_league[summoner_id][0]['entries'][0]['leaguePoints'] bot.say('The Summoner {} on region {} is currently in {} {} with {} LP 4Head'.format(summoner_name, region.upper(), tier, division, league_points)) except LoLException as e: if e == error_429: bot.say('Too many requests. Try again in {} seconds'.format(e.headers['Retry-After'])) return False elif e == error_404: bot.say('The Summoner {} on region {} is currently UNRANKED.. FeelsBadMan'.format(summoner_name, region.upper())) return False else: bot.say('Trouble fetching summoner rank.. Kappa Try again later!') return False
from django.shortcuts import render from django.template import RequestContext from django.shortcuts import render_to_response from riotwatcher import LATIN_AMERICA_SOUTH from riotwatcher import RiotWatcher from riotwatcher import LoLException from dataRunes import dataRunes from dataMasteries import dataMasteries # Create your views here. ''' Aqui esta toda la logica de todos los pedidos a la API de league Of Leagends. Por temas de comodidad se utilizo la herramienta Riot Watcher, sirve para hacer los pedidos mediante funciones de Python.''' riotWatcher = RiotWatcher("98f4f837-c794-4a58-bcb7-b436873a03d2", default_region=LATIN_AMERICA_SOUTH) me = riotWatcher.get_summoner(name='sadjockerking')#Se le agradece a Sad Jocker King por prestar su cuenta try: rankedst = riotWatcher.get_ranked_stats(me['id']) x = int(len(rankedst['champions'])) - 1 except(LoLException): rankedst = {} x = 0 def home(request): free_to_play = True context = RequestContext(request) # sumInf = summonerInfo() # mpcInf = mostPlayedChampInfo() # featgames = featuredGames() # free = freeChamps()
def wait_for_request(): while not watcher.can_make_request(): time.sleep(0.1) with open('settings.json') as f: settings = json.load(f) region = settings['region'] summoner_name = settings['summonerName'] key = settings['apikey'] watcher = RiotWatcher(key) summoner_id = watcher.get_summoner(name=summoner_name, region=region)['id'] game_found = False while not game_found: try: wait_for_request() game = watcher.get_current_game(summoner_id) print game game_found = True except Exception as e: pass #find which champion they are playing champion_id = None for player in game["participants"]: if player["summonerId"] == summoner_id:
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: James # # Created: 28/01/2015 # Copyright: (c) James 2015 # Licence: <your licence> #------------------------------------------------------------------------------- #!/usr/bin/env python from riotwatcher import RiotWatcher import pygametools as pt w = RiotWatcher('e4a0c61e-4a2b-41b2-9b98-5f95f745b1b7') # check if we have API calls remaining #print(w.can_make_request()) me = w.get_summoner(name='salvsis') print(me) a = pt.Linesoftext([str(me['name'])],(300,50),True) a.test((600,300)) #print(w.get_stat_summary(me['id']))
def wait_for_request(): while not watcher.can_make_request(): time.sleep(0.1) with open("settings.json") as f: settings = json.load(f) region = settings["region"] summoner_name = settings["summonerName"] key = settings["apikey"] watcher = RiotWatcher(key) summoner_id = watcher.get_summoner(name=summoner_name, region=region)["id"] game_found = False while not game_found: try: wait_for_request() game = watcher.get_current_game(summoner_id) print game game_found = True except Exception as e: pass # find which champion they are playing champion_id = None for player in game["participants"]: if player["summonerId"] == summoner_id:
__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:
def main(): #my_riot_api_key = str(raw_input('\nPaste Riot API Key: ')) #my_championgg_api_key = str(raw_input('\nPaste champion.gg API Key: ')) my_riot_api_key = '8792f2e9-2e9e-4f23-81bd-a219f81ea98f' my_championgg_api_key = '3f9e409bd58bc1868f8bfc4a3a75d40c' w = RiotWatcher(my_riot_api_key) c = championggAPI(my_championgg_api_key) #print('\nInput API Key can make requests?') #print(w.can_make_request()) summoner_to_check = str(raw_input('\nWhat summoner do you want to know about? ')) summoner = w.get_summoner(name=summoner_to_check) #print(summoner) my_mastery_pages = w.get_mastery_pages([summoner['id'], ])[str(summoner['id'])] show_masteries = str(raw_input('Show current masteries? ')) len_mastery_data = len(my_mastery_pages['pages']) if show_masteries == 'Yes': for x in range(0, len_mastery_data): if my_mastery_pages['pages'][x]['current']: current_mastery_page = my_mastery_pages['pages'][x] print ('Current masteries: ') print '\"{name}\"'.format(name=current_mastery_page['name']) mastery = MasteryPageParsing(current_mastery_page) m = mastery.tree_divider() print m elif show_masteries == 'yes': for x in range(0, len_mastery_data): if my_mastery_pages['pages'][x]['current']: current_mastery_page = my_mastery_pages['pages'][x] print ('Current mastery page: ') print '\"{name}\"'.format(name=current_mastery_page['name']) mastery = MasteryPageParsing(current_mastery_page) m = mastery.tree_divider() print m my_rune_pages = w.get_rune_pages([summoner['id'], ])[str(summoner['id'])] show_runes = str(raw_input('Show current runes? ')) len_rune_data = len(my_rune_pages['pages']) if show_runes == 'Yes': for x in range(0, len_rune_data): if my_rune_pages['pages'][x]['current']: current_rune_page = my_rune_pages['pages'][x] print ('Current rune page: ') print '\"{name}\"'.format(name=current_rune_page['name']) runes = RunePageParsing(current_rune_page) r = runes.rune_descriptions() print r elif show_runes == 'yes': for x in range(0, len_rune_data): if my_rune_pages['pages'][x]['current']: current_rune_page = my_rune_pages['pages'][x] print ('Current runes: ') print '\"{name}\"'.format(name=current_rune_page['name']) runes = RunePageParsing(current_rune_page) r = runes.rune_descriptions() print r champ_to_check = str(raw_input('\nWhat champion are they on? ')) role_of_champ = str(raw_input('What role are they in? (Valid inputs: Top, Jungle, Middle, ADC, Support) ')) championID = CONSTS.CHAMPION_ID[champ_to_check] #print ('{cha}\'s championID: {id}').format(cha=champ_to_check, id=championID) champion_mastery = ChampionMastery(my_riot_api_key) r = champion_mastery.get_champion_mastery(summoner['id'], championID) print'{name} is level {level} on {champ}'.format(name=summoner['name'], level=r['championLevel'], champ=champ_to_check) ranked_champion_stats = w.get_ranked_stats(summoner['id']) length_ranked_data = len(ranked_champion_stats['champions']) champ_found = False for x in range(0, length_ranked_data): if ranked_champion_stats['champions'][x]['id'] == int(championID): champ_games_won = float(ranked_champion_stats['champions'][x]['stats']['totalSessionsWon']) #print 'champ games won', champ_games_won champ_games_lost = float(ranked_champion_stats['champions'][x]['stats']['totalSessionsLost']) #print 'games lost', champ_games_lost champ_games_played = float(ranked_champion_stats['champions'][x]['stats']['totalSessionsPlayed']) winrate = round((champ_games_won / champ_games_played) * 100, 3) if champ_games_played > 5: if 60 <= winrate: winrate_reaction = 'strong' elif 50 <= winrate < 60: winrate_reaction = 'good' elif 40 <= winrate < 50: winrate_reaction = 'bad' else: winrate_reaction = 'ebolAIDS-causing, cancer-giving, hope-sundering' else: winrate_reaction = 'unreliable' print '{name} on {champ} has a {reac} winrate of {rate}% with {num} games played.'.format(name=summoner['name'], champ=champ_to_check, reac=winrate_reaction, rate=winrate, num=champ_games_played) champ_found = True champ_stats = c.request_by_champion(champ_to_check) champ_winrate = 'unable to be found.' length_champion_ranked_data = len(champ_stats) for y in range(0, length_champion_ranked_data): if champ_stats[y]['role'] == role_of_champ: champ_winrate = float(champ_stats[y]['general']['winPercent']) print 'Average winrate for {champ} as {role} is {winrate}.'.format(champ=champ_to_check, role=role_of_champ, winrate=champ_winrate) calc = winrate_calcuations(summoner['name']) calc.winrate_difference(winrate, champ_winrate) if champ_found is False: print 'No ranked champion data found for {champ}\n'.format(champ=champ_to_check)
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']
class LeagueBot(DiscordBot): def __init__(self, client): super(LeagueBot, self).__init__(client, 'leaguebot') self.storage_manager = CouchbaseManager( os.environ.get('MATCH_HISTORY_BUCKET')) self.riot = RiotWatcher(os.environ.get('RIOT_API_KEY'), default_region=EUROPE_WEST) self.players = self.load_player_list() self.champions = self.load_champions() self.memes = self.load_memes() self.cleverbot = cleverbot.Cleverbot() def load_player_list(self): try: players = self.storage_manager.get('players') except FileNotFoundError: players = {} return players def load_champions(self): try: champs = self.storage_manager.get('champions') except FileNotFoundError: champs = import_champs() self.storage_manager.set('champions', champs) return champs def load_memes(self): try: memes = self.storage_manager.get('memes') except FileNotFoundError: memes = [] return memes @DiscordBot.add_command('add') def add_player(self, *args): """Adds a player to be tracked""" player = ''.join(args) if player.lower() not in self.players: try: summoner = self.riot.get_summoner(name=player) except LoLException as e: if e == error_404: self.send_message( 'Error - Player {} does not exist'.format(player)) else: self.send_message( 'An unknown error occurred, let Matt know!') league_bot_logger.warning(e) return self.players[summoner['name'].lower()] = summoner['id'] self.send_message('Added {} to list of players'.format(player)) self.storage_manager.set('players', self.players) else: self.send_message( '{} already in the list of players'.format(player)) @DiscordBot.add_command('list') def print_players(self, *_): """Prints out the list of players""" if self.players: player_list = '\n' for player, player_id in self.players.iteritems(): try: number_of_games = len( self.storage_manager.get( 'matches-{}'.format(player_id))['games']) except FileNotFoundError: number_of_games = 0 player_list += '{} - {} games\n'.format( player, number_of_games) self.send_message(player_list) else: self.send_message('Player list empty') @DiscordBot.add_command('current-games') def get_current_games(self, *_): for player in self.players: self.get_current_game(player) @DiscordBot.add_command('current-game') def get_current_game(self, *args): """Gets current-game information for the provided player""" player = ''.join(args).lower() if player not in self.players.keys(): try: summoner = self.riot.get_summoner(name=player) except LoLException as e: if e == error_404: self.send_message( 'Error - Player {} does not exist'.format(player)) else: self.send_message( 'An unknown error occurred, let Matt know!') league_bot_logger.warning(e) return else: player_id = summoner['id'] else: player_id = self.players[player] try: curr_game = self.riot.get_current_game(player_id) except LoLException as e: if e == error_404: self.send_message('{} is not in a game'.format(player)) else: league_bot_logger.warning(e) else: game_length = (int(curr_game['gameLength']) / 60) + 3 for participant in curr_game['participants']: if participant['summonerName'].lower() == player.lower(): champion = self.champions[str(participant['championId'])] lolnexus_url = ( 'http://www.lolnexus.com/EUW/search?name={}®ion=EUW' .format(player)) self.send_message( '{} has been in a game for {} minutes - Playing {}\n' 'Link to game: {}'.format(player, game_length, champion, lolnexus_url)) break @DiscordBot.add_command('stats') def summarise_stats(self, *args): """Prints out average stats for the given player""" player = ' '.join(args).lower() if player not in self.players: self.send_message( '{} not in list of players, no stats found'.format(player)) matches = self.storage_manager.get('matches-{}'.format( self.players[player])) stat_averages = defaultdict(list) match_counter = 0 for match in matches['games']: if match['subType'] in WANTED_SUB_TYPES: match_counter += 1 for stat, value in match['stats'].iteritems(): stat_averages[stat].append(value) output = '' for stat, value in OrderedDict(sorted( stat_averages.items())).iteritems(): try: output += '{} - {:.3f}\n'.format( stat, float(sum(value)) / match_counter) except TypeError: pass output += 'Games - {}'.format(match_counter) self.send_message(output) @DiscordBot.add_command('is Neku eloboosted?') def dank_meme(self, *args): """'Nuff said""" self.send_message( "It's not boosting, it's just elo rushing, he is entitled to be there" ) @DiscordBot.add_command('help') def list_commands(self, *args): """Lists all commands and their purpose""" command_str = 'List of commands:' for command in sorted(self.__class__.commands): command_str += '\n{} - {}'.format(command, self.commands[command].__doc__) self.send_message(command_str) @DiscordBot.add_command('meme add') def add_meme(self, *args): """Adds a new meme""" meme = ' '.join(args) if meme not in self.memes: self.memes.append(meme) self.storage_manager.set('memes', self.memes) self.send_message("Added '{}' to list of memes".format(meme)) else: self.send_message('No reposts pls') @DiscordBot.add_command('meme me') def random_meme(self, *args): """Prints a random meme""" self.send_message(random.choice(self.memes)) @DiscordBot.add_command('chat') def ask_cleverbot(self, *args): """Have a conversation with leaguebot""" response = self.cleverbot.ask(' '.join(args)) self.send_message(response)
print('static tests passed') status_tests() print('status tests passed') champion_tests() print('champion tests passed') s = summoner_tests(summoner_name) print('summoner tests passed') game_tests(s) print('game tests passed') league_tests(s) print('league tests passed') stats_tests(s) print('stats tests passed') team_tests(s) print('team tests passed') m = match_history_tests(s) print('match history tests passed') match_tests(m) print('match passed') print('all tests passed, w00t. if only they were better tests...') summoner = w.get_summoner(name=summoner_name) wait() print w.get_stat_summary(summoner['id']) wait() print w.get_ranked_stats(summoner['id']) if __name__ == '__main__': main()
#print(my_ranked_stats_last_season) # all static methods are prefaced with 'static' # static requests do not count against your request limit # but at the same time, they don't change often.... #static_champ_list = w.static_get_champion_list() #print(static_champ_list) # import new region code from riotwatcher import EUROPE_WEST # request data from EUW euw = RiotWatcher('RGAPI-62c12c6d-5a21-4d8e-96b2-c3cad4aa9baa', default_region=EUROPE_WEST) Manismyforte = euw.get_summoner(name='Manismyforte') #Manismyforte = euw.get_summoner(name='Manismyforte', region=EUROPE_WEST) print(Manismyforte) my_ranked_stats = euw.get_ranked_stats(me['id']) #froggen = w.get_summoner(name='froggen', region=EUROPE_WEST) #print(froggen) # create watcher with EUW as its default region #euw = RiotWatcher('RGAPI-62c12c6d-5a21-4d8e-96b2-c3cad4aa9baa', default_region=EUROPE_WEST) # proper way to send names with spaces is to remove them, still works with spaces though #xpeke = w.get_summoner(name='fnaticxmid') #print(xpeke)