def riothandler(): api_key = 'RGAPI-c296d748-27a8-4992-9141-487bde22f1c3' watcher = LolWatcher(api_key) my_region = 'na1' me = watcher.summoner.by_name(my_region, 'guss14') ranked_stats = watcher.league.by_summoner(my_region, me['id']) masteries = watcher.champion_mastery.by_summoner(my_region, me['id']) latest_version = watcher.data_dragon.versions_for_region( my_region)['n']['champion'] static_champ_list = watcher.data_dragon.champions(latest_version, False, 'en_US') # creating champ list dictionary champ_dict = {} for key in static_champ_list['data']: row = static_champ_list['data'][key] champ_dict[row['key']] = row['id'] # print(me) # print() print("Player Name: ", ranked_stats[0]["summonerName"]) print("Rank: ", ranked_stats[0]["tier"], ranked_stats[0]['rank']) print("Top 10 champion Masteries") top_champs = [] for i in range(0, 10): top_champs.append(masteries[i]) for i in range(0, 10): print("Name:", champ_dict[str(top_champs[i]["championId"])]) print("Champion Level:", top_champs[i]["championLevel"]) print("Champion Points:", top_champs[i]["championPoints"])
def read_account_game_ids_by_league(self): """ API reference: MatchApiv4 endpoint. Reads match history (n=1, the last game played) for each summoner name in the lists made above for just game IDs. Go from ranked_games_by_tier_by_division --> game_ids_by_tier_by_division. """ watcher = LolWatcher(self.api_key) ranked_games_by_tier_by_division = game_history_by_league( self.api_key, self.region).get_summoners_for_each_division_tier() df = pd.DataFrame(ranked_games_by_tier_by_division) for i, row in df_rg.iterrows(): try: accountId = watcher.summoner.by_name( self.region, df['summonerName'].values[i])['accountId'] games = watcher.match.matchlist_by_account( self.region, accountId)['matches'] gameId = '%.0f' % [ games[x]['gameId'] for x in range(0, len(games)) if games[x]['queue'] == 420 ][0] df.loc[i, 'gameId'] = gameId time.sleep(0.5) except: df_rg.loc[i, 'gameId'] = ''
async def lollevel(ctx, playername): watcher = LolWatcher(auth[5]) stats = watcher.summoner.by_name("EUN1", playername) json_str = json.dumps(stats) json_stripped = json.loads(json_str) to_print = "{}'s level: {}" await ctx.send(to_print.format(playername, json_stripped["summonerLevel"]))
def get_ranks(name, rank_type): lol_watcher = LolWatcher(API_KEY) my_region = 'na1' solo_dict = dict() flex_dict = dict() send_message = "" try: response = lol_watcher.summoner.by_name(my_region, name) my_ranked_stats = lol_watcher.league.by_summoner(my_region, response['id']) for i in range(len(my_ranked_stats)): if my_ranked_stats[i]['queueType'] == 'RANKED_FLEX_SR' and (rank_type == "flex" or rank_type == "both"): flex_dict['tier'] = my_ranked_stats[i]['tier'] flex_dict['rank'] = my_ranked_stats[i]['tier'] + " " + my_ranked_stats[i]['rank'] flex_dict['points'] = my_ranked_stats[i]['leaguePoints'] flex_dict['winrate'] = "***Wins***: {}\t\t ***Losses***: {}\t\t\n***WR***: {:0.2f}%".format(str(my_ranked_stats[i]['wins']), str(my_ranked_stats[i]['losses']), my_ranked_stats[i]['wins']/(my_ranked_stats[i]['losses']+my_ranked_stats[i]['wins'])*100) elif my_ranked_stats[i]['queueType'] == 'RANKED_SOLO_5x5' and (rank_type == "solo" or rank_type == "both"): solo_dict['tier'] = my_ranked_stats[i]['tier'] solo_dict['rank'] = my_ranked_stats[i]['tier'] + " " + my_ranked_stats[i]['rank'] solo_dict['points'] = my_ranked_stats[i]['leaguePoints'] solo_dict['winrate'] = "***Wins***: {}\t\t ***Losses***: {}\t\t\n***WR***: {:0.2f}%".format(str(my_ranked_stats[i]['wins']), str(my_ranked_stats[i]['losses']), my_ranked_stats[i]['wins']/(my_ranked_stats[i]['losses']+my_ranked_stats[i]['wins'])*100) except ApiError as err: if err.response.status_code == 429: send_message = "Shit is down idk what to tell you" elif err.response.status_code == 404: send_message = 'Homie does not exist in NA :tired_face:' else: raise return (flex_dict, solo_dict, send_message)
def get_timelines(game_ids, region=REGION): ''' retrieves detailed reports of all match timelines in the given matchlist and returns as a dataframe ''' watcher = LolWatcher(API_KEY) timelines = [] game_ids_success = [] failed = [] print('fetching timelines:') for i, game_id in enumerate(tqdm(game_ids)): for _ in range(3): try: timelines.append( watcher.match.timeline_by_match(region, game_id)) game_ids_success.append(game_id) break except: time.sleep(1.5) else: failed.append(game_id) time.sleep(1.5) if failed: print('game ids failed:', failed) df_tl = pd.DataFrame(timelines, index=game_ids_success) df_tl.index.rename('game_id', inplace=True) df_tl.sort_index(inplace=True) return df_tl
def get_matches(df, region=REGION): '''collects games from riot api''' watcher = LolWatcher(API_KEY) matches = [] game_ids_success = [] failed = [] print('fetching matches:') for i, game_id in enumerate(tqdm(df.game_id)): for _ in range(3): try: matches.append(watcher.match.by_id(region, game_id)) game_ids_success.append(game_id) break except: time.sleep(1.5) else: failed.append(game_id) time.sleep(1.5) if failed: print('game ids failed:', failed) df_m = pd.DataFrame(matches) df_m.rename(columns={'gameId': 'game_id'}, inplace=True) df_m.set_index('game_id', drop=False, inplace=True) return df_m
async def start(self): await super().start() print('Loading the essentials...') config = configparser.ConfigParser() config.read('loluserstatsbot/config.ini') if 'lolAPI' in config.sections() and 'KEY' in config['lolAPI']: self.lolWatcher = LolWatcher(config['lolAPI']['KEY']) try: self.lolWatcher.summoner.by_name('na1', 'pseudonym117') except ApiError as err: if err.response.status_code == 403: print( "Wrong League of Legends API Key under [lolAPI] in config.ini. Please Check!" ) exit(-1) else: print( "Missing League of Legends API Key under [lolAPI] in config.ini" ) exit(0) print('configuration completed!') me = await self.get_me() print( f"Custom Bot v{__version__} (Layer {layer}) started on @{me.username}. Hi." )
def getTodaysGamesSingle(summoner): watcher = LolWatcher(api_key) call = watcher.summoner.by_name(my_region, summoner) summoner_puuid = call["puuid"] print("Summoner Name = " + summoner) print("Summoner Level = " + str(call["summonerLevel"])) return ( summoner + " played " + str(getTodaysGames(summoner_puuid, summoner)) + " games today!")
def getTodaysGamesEveryone(): watcher = LolWatcher(api_key) summoners = ["engagingraging", "gillette", "anotherasian96", "shizzukani", "katastrophically", "lucians in paris", "kris wu did it", "Ekkos In Paris", "Joisugoi"] result = "" for summoner in summoners: result = result + getTodaysGamesSingle(summoner) + "\n" return result
def matchHistory(my_region="na1", username="******", apiKey=1): watcher = LolWatcher(apiKey) me = watcher.summoner.by_name(my_region, username) my_matches = watcher.match.matchlist_by_account(my_region, me['accountId']) lastMatch = my_matches['matches'][0] match_detail = watcher.match.by_id(my_region, lastMatch['gameId']) return match_detail
def rank_stats(self): watcher = LolWatcher(self.api_key) #league, division, games played, etc. encrypted_summoner_id = self.user['id'] self.rank_stats = watcher.league.by_summoner(self.region, self.user['id']) return self.rank_stats
def getUserStats(summoner_name): watcher = LolWatcher(api_key) summoner = summoner_name call = watcher.summoner.by_name(my_region, summoner) summoner_puuid = call["puuid"] print("Summoner Name = " + summoner) print("Summoner Level = " + str(call["summonerLevel"])) return "Wins in last 10 games = " + str(getRecentWins(summoner_puuid, summoner))
def __init__(self, api_key, name, region, gamemode, gameid): #upon calling the class we pass in a bunch of things to initialize^ self.api_key = api_key self.name = name self.region = region self.gamemode = gamemode self.gameid = gameid watcher = LolWatcher(self.api_key) self.user = watcher.summoner.by_name(region, name)
def __init__(self, summoner_name): ''' :param summoner_name: (string) game user name, case insensitive ''' self.__summoner_name = summoner_name self.lol_watcher = LolWatcher(ACCESS_KEY) self.__champions = pd.read_csv('DATA/all_champions.csv')
def outputGen(my_region="na1", username="******", apiKey=1): watcher = LolWatcher(apiKey) me = watcher.summoner.by_name( my_region, username) # JSON object containing a LOT of data # the 'id' key is what holds your summoner ID my_ranked_stats = watcher.league.by_summoner( my_region, me['id']) # Returns JSON object output return my_ranked_stats
def get_data(ser, pla): api_key = "RGAPI-26fc1222-e638-4bfb-82e6-737c81fb2c3a" watcher = LolWatcher(api_key) my_region = ser my_summoner_name = pla # Get searched player player = watcher.summoner.by_name(my_region, my_summoner_name) encrypted_summoner = player['id'] my_name = player['name'] # Get actual game current_game = watcher.spectator.by_summoner(my_region, encrypted_summoner) # Get every player in an array participants = current_game['participants'] player_one = participants[0] player_two = participants[1] player_three = participants[2] player_four = participants[3] palyer_five = participants[4] player_six = participants[5] player_seven = participants[6] player_eight = participants[7] player_nine = participants[8] player_ten = participants[9] blue_team_aux = [ player_one['summonerName'], player_two['summonerName'], player_three['summonerName'], player_four['summonerName'], palyer_five['summonerName'] ] blue_team = [ player_one, player_two, player_three, player_four, palyer_five ] red_team = [ player_six, player_seven, player_eight, player_nine, player_ten ] if my_name in blue_team_aux: enemies = red_team else: enemies = blue_team # Enemies is the list where i need to get the spellsID game_info = [] for i in range(5): enemy = enemies[i] summoner1 = get_spell(enemy['spell1Id']) summoner2 = get_spell(enemy['spell2Id']) champion = get_champion(enemy['championId']) game_info.append([champion, summoner1, summoner2]) return game_info
def __init__(self): config = ConfigParser(allow_no_value=True) config.read('config.ini') self.ingame = False self.name = '' print(Style.RESET_ALL) print(Fore.GREEN + 'Initializing...') apikey = config.get('settings', 'riot-api') self.hookline = config.get('settings', 'hookline') self.watcher = LolWatcher(apikey)
async def get_league_rank(ctx, summoner): api_key = LEAGUE_API_Key watcher = LolWatcher(api_key) my_region = 'na1' me = watcher.summoner.by_name(my_region, summoner) my_ranked_stats = watcher.league.by_summoner(my_region, me['id']) json_formatted_str = json.dumps(my_ranked_stats, indent=2) response = f"```{json_formatted_str}```" await ctx.send((response))
def __init__(self): try: with open('API-KEY') as f: self.API_KEY = f.read() f.close() except FileNotFoundError: print("No API KEY found") # TODO add exception for expired API key self.watcher = LolWatcher(self.API_KEY)
def champions(my_region, apiKey): # Returns output containing information for all champions # (Warning: long output!) watcher = LolWatcher(apiKey) # Prints data for champions versions = watcher.data_dragon.versions_for_region(my_region) champions_version = versions['n']['champion'] current_champ_list = watcher.data_dragon.champions(champions_version) return (current_champ_list)
def getTodaysGames(summoner_puuid, summoner): match_watcher = LolWatcher(api_key, default_match_v5=True) match_list = match_watcher.match.matchlist_by_puuid('AMERICAS', summoner_puuid, 0, 10) # max 100 --> bottleneck occurs here, needs to call for each match games_played_today = 0 print(match_list) for match in match_list: match_details = match_watcher.match.by_id('AMERICAS', match) if (checkDateOfMatch(match_details) == datetime.today().date()): games_played_today = games_played_today + 1 return games_played_today
def __init__(self, region, summonerName, api_key): """ :param string region: The region of the player :param string summonerName: The summoner name of the player :param string api_key: The API key used for access to the Riot API """ self.region = region self.summonerName = summonerName self.lolWatcher = LolWatcher(api_key)
def getRecentWins(summoner_puuid, summoner): match_watcher = LolWatcher(api_key, default_match_v5=True) match_list = match_watcher.match.matchlist_by_puuid('AMERICAS', summoner_puuid, 0, 10) # max 100 --> bottleneck occurs here, needs to call for each match index = 1 wins = 0 for match in match_list: index = index + 1 match_details = match_watcher.match.by_id('AMERICAS', match) if ( getSummonerTeam(summoner, match_details) == getGameResult(match_details) ): wins = wins + 1 return wins
def query_game(gameId, area): watcher = LolWatcher(os.getenv("API_KEY")) while True: try: response = watcher.match.by_id(area, gameId) except: continue break return response
def __init__(self, api_key): """Constructor Arguments: api_key {str} -- Unique API key to initialize the StatsGrabber class """ self.__api_key = api_key try: self.watcher = LolWatcher(api_key) except ApiError as e: print(f'Raised ApiError. Perhaps API Key is wrong? {e}')
def main(): watcher = LolWatcher(API_KEY, timeout=10) match_id_list = get_match_ids(path=MATCHES_ID_PATH) with open(JSON_EXPORT_PATH, 'a', encoding='utf8') as f: pipeline = PipelineAPI(watcher=watcher, file_descriptor=f) for match_id in tqdm(match_id_list, colour='green'): pipeline.run(match_id=match_id, region=REGION) script_arguments = JSON_EXPORT_PATH + ' ' + JSON_SPLIT_PATH os.system("split -l 322 -a 5 -d --additional-suffix='.json' " + script_arguments)
def getGame(summoner, api_key): watcher = LolWatcher(api_key) my_region = 'br1' me = watcher.summoner.by_name(my_region, summoner) #df = pd.DataFrame(me) my_matches = watcher.match.matchlist_by_account(my_region, me['accountId']) # fetch last match detail last_match = my_matches['matches'][0] match_detail = watcher.match.by_id(my_region, last_match['gameId']) return match_detail
def is_valid_summoner_name(summoner_name: str) -> LolWatcher.summoner: watcher = LolWatcher(api_key) region = "euw1" try: summoner = watcher.summoner.by_name(region, summoner_name) return summoner except ApiError as err: return False except Exception as exc: with open("logs.txt", "a", encoding="utf-8") as f: f.write(f"{time.localtime()}: {exc.message}") return False
def __init__(self): self.key = os.environ.get('key') self.watcher = LolWatcher(self.key) self.servers = {'BR1': 'Brazil', 'EUN1': 'Europe East', 'EUW1': 'Europe West', 'JP1': 'Japan', 'KR': 'Korea', 'LA1': 'Latin America North', 'LA2': 'Latin America South', 'NA1': 'North America', 'OC1': 'Oceania', 'TR1': 'Turkey', 'RU': 'Russia'}
def fetch_static_data(also_fetch_queues: Optional[bool] = False) -> None: """ Fetches all static data from the DDragon API. Static data that's fetched: > Version: versions for every static data type (e.g. champion, items). Creates a new instance on every call. > Champions: All champs in league. Updates or creates. Args: also_fetch_queues (Optional[bool], optional): If True, also fetches queue_types. This is generally not necessary (outside of initial loads). Defaults to False. """ watcher = LolWatcher(api_key=X_RIOT_TOKEN) version = fetch_and_save_version(watcher=watcher) fetch_and_write_champs(watcher=watcher, version=version) if also_fetch_queues: fetch_and_write_queue_types(watcher=watcher)