def setup_cass(): riotapi.set_load_policy("lazy") riotapi.set_rate_limit(25000, 10) riotapi.set_data_store(None) riotapi.set_api_key(os.environ["API_KEY"]) riotapi.set_region("NA") riotapi.print_calls(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) # Load and connect to your database. (Comment this code to use local memory. Don't forget to comment db.close() below too.) # db = SQLAlchemyDB("mysql+mysqlconnector", "databse_hostname", "database_name", "username", "password") # riotapi.set_data_store(db) # Gather master names master = [entry.summoner for entry in riotapi.get_challenger()] print("Pulled Master tier. Got {0} summoners.".format(len(master))) gather_start = datetime(2016, 12, 26) gather_end = datetime(2016, 12, 27) for player in master: matches = player.match_list(begin_time=gather_start, end_time=gather_end) matchestoday = len(matches) print(matchestoday) for match in matches: for participant in match.participants: print(participant.champion.name)
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(True) key = 'b7190b84-484d-4cc7-88ca-8e2b90fb7f56' # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) # Pull the data for one of Dyrus' matches. match = riotapi.get_match(2034758953) # Create a namedtuple called "Info" that is used to store some information about participants. # We use a namedtuple because it allows for a clear way to access this data later in the script. Info = namedtuple("Info", ["side", "role", "lane"]) # Loop through the participants in this match and record which side they played on (blue or red), # which role they played, and what lane they played in. mapping = {} for participant in match.participants: mapping[participant.champion.name] = Info(participant.side.name, participant.timeline.role.value, participant.timeline.lane.value) print() # Print out the information we just collected. for champion, info in sorted(mapping.items(), key=lambda tuple: (tuple[1].side, tuple[1].lane)): print("{0}: {1}".format(champion, info))
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(True) os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428" key = os.environ[ "DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) # Pull the data for one of Dyrus' matches. match = riotapi.get_match(2034758953) # Create a namedtuple called "Info" that is used to store some information about participants. # We use a namedtuple because it allows for a clear way to access this data later in the script. Info = namedtuple("Info", ["side", "role", "lane"]) # Loop through the participants in this match and record which side they played on (blue or red), # which role they played, and what lane they played in. mapping = {} for participant in match.participants: mapping[participant.champion.name] = Info( participant.side.name, participant.timeline.role.value, participant.timeline.lane.value) print() # Print out the information we just collected. for champion, info in sorted(mapping.items(), key=lambda tuple: (tuple[1].side, tuple[1].lane)): print("{0}: {1}".format(champion, info))
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(True) os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428" key = os.environ["DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) # Load and connect to your database. (Comment this code to use local memory. Don't forget to comment db.close() below too.) # db = SQLAlchemyDB("mysql+mysqlconnector", "databse_hostname", "database_name", "username", "password") # riotapi.set_data_store(db) master = [entry.summoner for entry in riotapi.get_master()] print("Pulled Master tier. Got {0} summoners.".format(len(master))) gather_start = datetime(2016, 2, 23) # 1 day after patch 5.14 for summoner in master: for match in summoner.match_list(begin_time=gather_start): # If you are connected to a database, the match will automatically be stored in it without you having to do anything. # Simply pull the match, and it's in your database for whenever you need it again! # If you pull a match twice, the second time it will be loaded from the database rather than pulled from Riot # and therefore will not count against your rate limit. This is true of all datatypes, not just Match. match = get_match(match) print("Stored {0} in my database".format(match))
def riotapi_setting(api_key, region): try: riotapi.set_rate_limits((10, 10), (500, 600)) riotapi.set_api_key(api_key) riotapi.set_region(region) except Exception as e: raise e
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(True) key = os.environ["DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.eager) # Load and connect to your database. (Comment this code to use local memory. Don't forget to comment db.close() below too.) db = SQLAlchemyDB("mysql+mysqlconnector", "databse_hostname", "database_name", "username", "password") riotapi.set_data_store(db) master = [entry.summoner for entry in riotapi.get_master()] print("Pulled Master tier. Got {0} summoners.".format(len(master))) gather_start = datetime(2015, 7, 23) # 1 day after patch 5.14 for summoner in master: for match in summoner.match_list(begin_time=gather_start): # If you are connected to a database, the match will automatically be stored in it without you having to do anything. # Simply pull the match, and it's in your database for whenever you need it again! # If you pull a match twice, the second time it will be loaded from the database rather than pulled from Riot # and therefore will not count against your rate limit. This is true of all datatypes, not just Match. match = get_match(match) print("Stored {0} in my database".format(match)) db.close()
def get_region(request): if request.method == 'POST': reg= request.POST.get("region") else: reg= "euw" riotapi.set_region(reg) riotapi.set_api_key(settings.RIOT_KEY) summoners = riotapi.get_challenger() return summoners
def init(bot: commands.Bot, cfg: dict): global config config = cfg[__name__] riotapi.set_region(config["api_region"]) riotapi.set_api_key(config["api_key"]) from .trivia import LoLTrivia bot.add_cog(LoLTrivia(bot))
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 setup_cassiopeia(region="NA", print_calls=True, key="development"): from cassiopeia import riotapi riotapi.set_region(region) riotapi.print_calls(print_calls) key = key.lower() riotapi.set_load_policy('lazy') if key in ("d", "dev", "development"): key = os.environ['DEV_KEY'] elif key in ("p", "prod", "production"): key = os.environ["PROD_KEY"] riotapi.set_rate_limits((3000, 10), (180000, 600)) riotapi.set_api_key(key) riotapi.set_locale(locale="en_US")
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(True) os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428" key = os.environ["DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) champions = riotapi.get_champions() mapping = {champion.name for champion in champions} print(mapping)
def main(): db = MySQLdb.connect(host="localhost", user="******", passwd="1234", db="lol") cursor = db.cursor() db.autocommit(True) # Autocommit INSERTs to spotify DB db.set_character_set('utf8') cursor.execute('SET NAMES utf8;') cursor.execute('SET CHARACTER SET utf8;') cursor.execute('SET character_set_connection=utf8;') # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(True) key = os.environ[ "DEV_KEY2"] # 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) # Get total masteries cursor.execute("SELECT id FROM Summoner") summoners = list(cursor) for (summoner, ) in summoners: cursor.execute( "SELECT EXISTS (SELECT * FROM SummonerMasteries WHERE summId = %s)", [summoner]) is_present = list(cursor)[0][0] if not is_present: cursor.execute( "SELECT region " "FROM MatchParticipant PA, MatchPlayer PL, MatchDetail D " "WHERE PL.summonerId = %s " "AND PL._participant_id = PA._id " "AND PA._match_id = D.matchId", [summoner]) region = list(cursor) if region: region = region[0][0] riotapi.set_region(region) mastery_score = championmasteryapi.get_champion_mastery_score( summoner) else: mastery_score = 0 cursor.execute( "INSERT INTO SummonerMasteries (summId, mastery) VALUES (%s, %s)", (summoner, mastery_score)) cursor.close() db.close()
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
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 main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(True) key = os.environ["DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) champions = riotapi.get_champions() mapping = {champion.id: champion.name for champion in champions} print(mapping) print() # Annie's champion ID is 1, so this will print "Annie" print(mapping[1])
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(False) key = os.environ[ "DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) dyrus = riotapi.get_summoner_by_name("Dyrus") # SummonerID is 5908 # dyrus = riotapi.get_summoner_by_id(5908) # You could use this as well match_list = riotapi.get_match_list(dyrus) num_matches = 20 kills = 0 deaths = 0 assists = 0 print("Calculating K/D/A from the past {0} matches...".format(num_matches)) for i, match_reference in enumerate(match_list[0:num_matches]): match = riotapi.get_match(match_reference) for participant in match.participants: if participant.summoner_id == dyrus.id: kills += participant.stats.kills deaths += participant.stats.kills assists += participant.stats.assists kda = (kills + assists) / deaths print( "Rolling K/D/A for {0}: {1}/{2}/{3} == {4} over most recent {5} matches" .format(dyrus.name, kills, deaths, assists, round(kda, 3), i + 1)) print("Final average K/D/A: {0}/{1}/{2} == {3} over past {4} matches". format(kills, deaths, assists, round(kda, 3), num_matches)) print() print( "If we want K/D/A we really should be using the /stats/ endpoint, but it seems to be inaccurate or missing key information." ) stats = riotapi.get_stats(dyrus) stats = stats[StatSummaryType.ranked_fives].stats print("Total ranked K/D/A for {0}: {1}/{2}/{3} == {4}".format( dyrus.name, stats.kills, stats.deaths, stats.assists, round(stats.kda, 3)))
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(False) key = os.environ["DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) match = riotapi.get_match(2034758953) print("Match start time: {0}".format(match.creation)) print("Match duration: {0}".format(match.duration)) # You can just add them together! print("Match end time: {0}".format(match.creation + match.duration)) print("Match version: {0}".format(match.version))
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(True) key = os.environ[ "DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) champions = riotapi.get_champions() mapping = {champion.id: champion.name for champion in champions} print(mapping) print() # Annie's champion ID is 1, so this will print "Annie" print(mapping[1])
def main(): riotapi.set_region("kr") riotapi.print_calls(True) riotapi.set_load_policy(LoadPolicy.lazy) riotapi.set_api_key("d045c326-dc9f-4de4-a463-793944aa6984") db = SQLAlchemyDB("mysql+mysqlconnector", "localhost", "kr_challenger_522", "root", "0123") riotapi.set_data_store(db) challenger = [entry.summoner for entry in list(riotapi.get_challenger()[1:10])] gather_start = datetime(2015, 11, 12) # 1 day after patch 5.19 for summoner in challenger: for match in summoner.match_list(begin_time=gather_start): get_match(match) db.close()
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(False) key = os.environ[ "DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) match = riotapi.get_match(2034758953) print("Match start time: {0}".format(match.creation)) print("Match duration: {0}".format(match.duration)) # You can just add them together! print("Match end time: {0}".format(match.creation + match.duration)) print("Match version: {0}".format(match.version))
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(True) key = os.environ[ "DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) # Load and connect to your database. (Comment this code to use local memory. Don't forget to comment db.close() below too.) db = SQLAlchemyDB("mysql+mysqlconnector", "databse_hostname", "database_name", "username", "password") riotapi.set_data_store(db) # We will seed with all the summoners in Master's tier unpulled_summoners = deque(entry.summoner for entry in riotapi.get_master()) print("Pulled Master tier for seeding. Got {0} summoners.".format( len(unpulled_summoners))) # We need this so that we don't get a recursive loop of summoners pulled_summoners = deque() gather_start = datetime(2015, 7, 23) # 1 day after patch 5.14 while len(unpulled_summoners) > 0: summoner = unpulled_summoners.popleft() for match_reference in summoner.match_list(begin_time=gather_start): # If you are connected to a database, the match will automatically be stored in it without you having to do anything. # Simply pull the match, and it's in your database for whenever you need it again! # If you pull a match twice, the second time it will be loaded from the database rather than pulled from Riot # and therefore will not count against your rate limit. This is true of all datatypes, include Summoner. match = riotapi.get_match(match_reference) if match is None: # If the match still fails to load, continue on to the next one continue print("Stored {0} in my database".format(match)) for participant in match.participants: if participant.summoner not in unpulled_summoners and participant.summoner not in pulled_summoners: unpulled_summoners.append(participant.summoner) pulled_summoners.append(summoner) db.close()
def main(): riotapi.set_region("kr") riotapi.print_calls(True) riotapi.set_load_policy(LoadPolicy.lazy) riotapi.set_api_key("d045c326-dc9f-4de4-a463-793944aa6984") db = SQLAlchemyDB("mysql+mysqlconnector", "localhost", "kr_challenger_522", "root", "0123") riotapi.set_data_store(db) challenger = [ entry.summoner for entry in list(riotapi.get_challenger()[1:10]) ] gather_start = datetime(2015, 11, 12) # 1 day after patch 5.19 for summoner in challenger: for match in summoner.match_list(begin_time=gather_start): get_match(match) db.close()
def main(): # Setup riotapi riotapi.set_region("KR") riotapi.print_calls(True) key = os.environ["DEV_KEY1"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) # Load and connect to your database. (Comment this code to use local memory. Don't forget to comment db.close() below too.) db = SQLAlchemyDB("mysql+mysqlconnector", "localhost", "lol", "root", "1234") riotapi.set_data_store(db) #riotapi.get_masteries() #riotapi.get_champions() #riotapi.get_runes() #riotapi.get_summoner_spells() # We will seed with all the summoners in Master's tier unpulled_summoners = deque(entry.summoner for entry in riotapi.get_master()) print("Pulled Master tier for seeding. Got {0} summoners.".format(len(unpulled_summoners))) # We need this so that we don't get a recursive loop of summoners pulled_summoners = deque() gather_start = datetime(2017, 1, 12) # 1 day after patch 7.1 while len(unpulled_summoners) > 0: summoner = unpulled_summoners.popleft() for match_reference in summoner.match_list(begin_time=gather_start): match = riotapi.get_match(match_reference) if match is None: # If the match still fails to load, continue on to the next one continue print("Stored {0} in my database".format(match)) for participant in match.participants: # cm = riotapi.get_champion_mastery(participant.summoner, participant.champion) if participant.summoner not in unpulled_summoners and participant.summoner not in pulled_summoners: unpulled_summoners.append(participant.summoner) pulled_summoners.append(summoner) db.close()
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(False) os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428" key = os.environ["DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) gigglepuss = riotapi.get_summoner_by_name("GigglePuss") # SummonerID is 5908 # dyrus = riotapi.get_summoner_by_id(5908) # You could use this as well match_list = riotapi.get_match_list(gigglepuss) num_matches = 20 kills = 0 deaths = 0 assists = 0 print("Calculating K/D/A from the past {0} matches...".format(num_matches)) for i, match_reference in enumerate(match_list[0:num_matches]): match = riotapi.get_match(match_reference) for participant in match.participants: if participant.summoner_id == gigglepuss.id: kills += participant.stats.kills deaths += participant.stats.kills assists += participant.stats.assists kda = (kills + assists) / deaths print("Rolling K/D/A for {0}: {1}/{2}/{3} == {4} over most recent {5} matches".format(gigglepuss.name, kills, deaths, assists, round(kda, 3), i + 1)) print("Final average K/D/A: {0}/{1}/{2} == {3} over past {4} matches".format(kills, deaths, assists, round(kda, 3), num_matches)) print() print("If we want K/D/A we really should be using the /stats/ endpoint, but it seems to be inaccurate or missing key information.") stats = riotapi.get_stats(gigglepuss) stats = stats[StatSummaryType.ranked_fives].stats print("Total ranked K/D/A for {0}: {1}/{2}/{3} == {4}".format(gigglepuss.name, stats.kills, stats.deaths, stats.assists, round(stats.kda, 3)))
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(False) os.environ["DEV_KEY"] = "94e831f6-ef9f-4823-81fc-cfc9342f4428" key = os.environ["DEV_KEY"] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) gigglepuss = riotapi.get_summoner_by_name("GigglePuss") # SummonerID is 5908 match_list = riotapi.get_match_list(gigglepuss) match = riotapi.get_match(match_list[0]) print("Basic match information:") print(" Match ID: {0}".format(match.id)) print(" Version/Patch: {0}".format(match.version)) print(" Creation date: {0} (which was {1} ago)".format(match.creation, datetime.datetime.now() - match.creation)) print(" Duration: {0}".format(match.duration)) print(" Map: {0}".format(match.map)) print(" Mode: {0}".format(match.mode)) print(" Type: {0}".format(match.type)) print(" Platform: {0}".format(match.platform)) print(" Queue: {0}".format(match.queue)) print(" Region: {0}".format(match.region)) print(" Season: {0}".format(match.season)) print(" Red Team Bans: {0}".format([ban.champion.name for ban in match.red_team.bans])) print(" Blue Team Bans: {0}".format([ban.champion.name for ban in match.blue_team.bans])) print() champion = match.participants["GigglePuss"].champion print("You can use special key-words/key-objects to lookup the participants in the match.") print(" Lookup via Summoner: {0}".format(match.participants[gigglepuss])) print(" Lookup via summoner name: {0}".format(match.participants["GigglePuss"])) print(" Lookup via Champion played: {0}".format(match.participants[champion])) print(" Lookup via champion name: {0}".format(match.participants[champion.name]))
def main(): # Setup riotapi riotapi.set_region("NA") riotapi.print_calls(True) key = os.environ[ "DEV_KEY" ] # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) # Load and connect to your database. (Comment this code to use local memory. Don't forget to comment db.close() below too.) db = SQLAlchemyDB("mysql+mysqlconnector", "databse_hostname", "database_name", "username", "password") riotapi.set_data_store(db) # We will seed with all the summoners in Master's tier unpulled_summoners = deque(entry.summoner for entry in riotapi.get_master()) print("Pulled Master tier for seeding. Got {0} summoners.".format(len(unpulled_summoners))) # We need this so that we don't get a recursive loop of summoners pulled_summoners = deque() gather_start = datetime(2015, 7, 23) # 1 day after patch 5.14 while len(unpulled_summoners) > 0: summoner = unpulled_summoners.popleft() for match_reference in summoner.match_list(begin_time=gather_start): # If you are connected to a database, the match will automatically be stored in it without you having to do anything. # Simply pull the match, and it's in your database for whenever you need it again! # If you pull a match twice, the second time it will be loaded from the database rather than pulled from Riot # and therefore will not count against your rate limit. This is true of all datatypes, include Summoner. match = riotapi.get_match(match_reference) print("Stored {0} in my database".format(match)) for participant in match.participants: if participant.summoner not in unpulled_summoners and participant.summoner not in pulled_summoners: unpulled_summoners.append(participant.summoner) pulled_summoners.append(summoner) db.close()
def main(): # Setup riotapi riotapi.set_region(REGION) riotapi.print_calls(True) key = #redacted # You can create an env var called "DEV_KEY" that holds your developer key. It will be loaded here. riotapi.set_api_key(key) riotapi.set_load_policy(LoadPolicy.lazy) # Load and connect to your database. (Comment this code to use local memory. Don't forget to comment db.close() below too.) db = SQLAlchemyDB("sqlite", host="", database=OUTFILE, username="", password="") riotapi.set_data_store(db) # We will seed with all the summoners in Master's tier unpulled_summoners = deque(entry.summoner for entry in riotapi.get_master()) print("Pulled Master tier for seeding. Got {0} summoners.".format(len(unpulled_summoners))) # We need this so that we don't get a recursive loop of summoners pulled_summoners = deque() gather_start = datetime(2015, 1, 1) # since we have data for all of 2015 times_crashed = 0 #store number of times we've had the NoneType error times_looped = 0 #store number of times we've made a call as a rough proxy for when to stop the script while len(unpulled_summoners) > 0: summoner = unpulled_summoners.popleft() for match_reference in summoner.match_list(begin_time=gather_start): # If you are connected to a database, the match will automatically be stored in it without you having to do anything. # Simply pull the match, and it's in your database for whenever you need it again! # If you pull a match twice, the second time it will be loaded from the database rather than pulled from Riot # and therefore will not count against your rate limit. This is true of all datatypes, include Summoner. match = riotapi.get_match(match_reference) if match is None: # If the match still fails to load, continue on to the next one continue print("Stored {0} in my database".format(match)) for participant in match.participants: try: if participant.summoner not in unpulled_summoners and participant.summoner not in pulled_summoners: unpulled_summoners.append(participant.summoner) except TypeError: times_crashed += 1 print("I've run into the NoneType error {} times so far!".format(times_crashed)) pass times_looped += 1 print("I have now looped {} times.".format(times_looped)) if times_looped > LOOPS: exit("I have looped {} times and am done now.".format(times_looped)) pulled_summoners.append(summoner) db.close()
logger.addHandler(handler) client = discord.Client() client.login('*****@*****.**', 'Daniel7415295051') if not client.is_logged_in: print('Logging in to Discord failed') exit(1) random.seed() games = requests.get( 'https://gist.githubusercontent.com/ZetaHunter/56f9e37455bbcdd7f2ef/raw/981703ac5ea835bdf4d418ec919c10af24d04f7e/games.json').json() riotapi.set_region("NA") riotapi.set_api_key("37a65ef7-6cfa-4d98-adc0-a3300b9cfc3a") player = media.Player() def bot(message): client.send_message(message.channel, "Hi, I'm {name}. I am running version {version}.".format(name=name, version=__version__)) def cinfo(message): if not message.channel.is_private: client.send_message(message.channel, "```Name: " + message.channel.name + "\nID: " + message.channel.id + "\nType: " + message.channel.type + "```") else: client.send_message(message.channel, "```User: "******"\nID: " + message.channel.id + "```")
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())
import os from cassiopeia import riotapi from cassiopeia.type.core.common import LoadPolicy from flask import render_template from . import main @main.route('/') def index(): return render_template('main.html', free=free_to_play()) riotapi.set_region("EUW") riotapi.set_api_key(os.environ['API_KEY']) riotapi.set_load_policy(LoadPolicy.lazy) def free_to_play(): freechamps = riotapi.get_champion_statuses(free_to_play=True) free = {champ.name for champ in freechamps} return free
from cassiopeia import riotapi from cassiopeia.type.core.common import Queue import os #TODO: Set a proper way to select server riotapi.set_region("EUW") # 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
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 begin_crawling(api_key, seed_summoner_id, region='NA', seasons='PRESEASON2016', ranked_queues='RANKED_SOLO_5x5'): ''' Breadth first crawling interations, Summoner -> Match -> Summoner... ''' #seed intialization try: print('Seed initializing...') riotapi.set_api_key(api_key) riotapi.set_region(region) seed_summoner = riotapi.get_summoner_by_id(seed_summoner_id) conn = sqlite3.connect('lola.db') conn.execute("INSERT INTO Summoner VALUES('{}','{}',{})".format(seed_summoner.id, seed_summoner.name, 0)) #watch out "" | '' conn.commit() conn.close() print('\nInitialization completed.') except Exception as e: print('\nInitialization failed possibly because the seed is already in database:', e) pass # summoner queue interations total_summoner_processed = 0 total_match_processed = 0 total_match_cralwed = 0 total_match_duplicate = 0 total_match_none = 0 iteration = 0 try: conn = sqlite3.connect('lola.db') queue_summoner_ids = pd.read_sql("SELECT summoner_id FROM Summoner WHERE is_crawled=0", conn) except Exception as e: raise(e) finally: conn.close() while not queue_summoner_ids.empty: print('\nSummoner Queue Length:', len(queue_summoner_ids)) iteration += 1 # only a relative number because of crawling restrarts print ('Iteration', iteration, 'in the process...') queue_summoner_ids_list = list(queue_summoner_ids['summoner_id']) random.shuffle(queue_summoner_ids_list) for summoner_id in queue_summoner_ids_list[:]: # pd.dataframe to list of list(queue_summoner_ids['summoner_id']) conn = sqlite3.connect('lola.db') summoner = riotapi.get_summoner_by_id(summoner_id) match_reference_list = riotapi.get_match_list(summoner=summoner, seasons=seasons, ranked_queues=ranked_queues) print('\nSummoner {} ({}) in {}, {}: '.format(summoner.name, summoner.id, ranked_queues, seasons)) print('Total Match Number of the summoner: {}'.format(len(match_reference_list))) match_no = 0 # crawled + duplicate + none crawled_match_no = 0 duplicate_match_no = 0 none_match_no = 0 for mf in match_reference_list[:]: if is_match_duplicate(mf, conn) == False: try: match = riotapi.get_match(mf) # match reference -> match except Exception as e: raise(e) # may be None even if mf is not None, see https://github.com/meraki-analytics/cassiopeia/issues/57 # can not use != because of Match.__eq__ use Match.id if match is None: none_match_no += 1 continue # jump to the next interation match_to_sqlite(match, summoner, conn) # match is crawled conn.execute("UPDATE Match SET is_crawled = 1 WHERE match_id='{}'".format(mf.id)) crawled_match_no += 1 else : duplicate_match_no += 1 match_no += 1 if match_no % 10 == 0: print (match_no, 'matches in', len(match_reference_list), 'processed.') # summoner is crawled conn.execute("UPDATE Summoner SET is_crawled = 1 WHERE summoner_id='{}'".format(summoner_id)) conn.commit() # commit after every summoner finished conn.close() # sums of different kinds of matches total_summoner_processed += 1 total_match_processed += match_no total_match_cralwed += crawled_match_no total_match_duplicate += duplicate_match_no total_match_none += none_match_no print('\ntotal processed summoner:', total_summoner_processed,'\ntotal processed match:', total_match_processed, \ '\ntotal crawled match', total_match_cralwed, '\ntotal duplicate match:', total_match_duplicate, \ '\ntotal none match:', total_match_none) # read new queue for next iteration try: conn = sqlite3.connect('lola.db') queue_summoner_ids = pd.read_sql("SELECT summoner_id FROM Summoner WHERE is_crawled=0", conn) #update queue except Exception as e: raise(e) finally: conn.close()
Copyright: 2017 John Cleaver License: MIT (See LICENSE file) """ import os from datetime import datetime from cassiopeia import riotapi from cassiopeia.type.core.common import Queue from cassiopeia.type.api.store import SQLAlchemyDB from cassiopeia.type.api.exception import APIError riotapi.set_region("NA") riotapi.print_calls(True) key = key = os.environ["DEV_KEY"] riotapi.set_api_key(key) current_patch_start = datetime(2017, 3, 22) queue = Queue.flex_threes def auto_retry(api_call_method): """ A decorator to automatically retry 500s (Service Unavailable) and skip 400s (Bad Request) or 404s (Not Found). """ def call_wrapper(*args, **kwargs): try: return api_call_method(*args, **kwargs) except APIError as error: # Try Again Once if error.error_code in [500]: try:
from cassiopeia import riotapi riotapi.set_region("NA") riotapi.set_api_key("bf735671-a14a-4c52-8e02-ed476b7f8434") riotapi.set_rate_limits((10, 10), (500, 600)) def getDeaths(match): deathList = [] frameSet = match.frames eventSet = [event for eventList in [frame.events for frame in frameSet] for event in eventList] for event in eventSet: if event.type.name == 'kill': deathList.append(event) return deathList def getWinner(match): #Return winner of the match if match.blue_team.data.winner: return 0 else: return 1 def getRoles(match): '''Return a dict with the following setup: {'teamPosition': idNum} ''' roleMap = {} #Take care of the duo lanes where sup can't be auto determined #Base this on CS value blueDuo = []
from cassiopeia import riotapi from cassiopeia import baseriotapi from cassiopeia.type.core.common import LoadPolicy # Create a list of all the players you are looking up players = ['cakesofspan','Crs Risen','Maknae Seohyun'] ids = [30864736,30251656,49359126] # Setting a rate limit for how often you are pinging Riot's API so they don't get mad # 10 calls per 10 seconds AND 500 calls per 10 minutes riotapi.set_rate_limits((10, 10), (500, 600)); # Set your region and API Key which can be found here: (https://developer.riotgames.com/) # Do NOT release your API Key to the public riotapi.set_region("NA") riotapi.set_api_key("VALUE HERE") # Get the information for each summoner division_list = [] tier_list = [] points_list = [] wins_list = [] losses_list = [] for i in range(0,len(ids)): full = baseriotapi.get_league_entries_by_summoner(ids[i]) info_string = str(full['%d' % ids[i]][0]) division = re.findall('"division": "(.+?)",', info_string) tier = re.findall('"tier": "(.+?)"', info_string) points = re.findall('"leaguePoints": (.+?),', info_string) # wins = re.findall('"wins": (.+?),', info_string)
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)
import sched import time import pandas as pd import threading import datetime import logging from pymongo import MongoClient from collections import defaultdict from cassiopeia import riotapi from cassiopeia.type.core.common import LoadPolicy logging.basicConfig(filename='update_tfedb_2.log', level=logging.INFO) riotapi.set_api_key("your API key") riotapi.set_load_policy(LoadPolicy.lazy) client = MongoClient("your connection") db = client.tfedb collsums = db.summoners_copy collgame = db.games collanal = db.analysis collcont = db.sums_count collsubs = db.mailchimp_subscribers collsend = db.send_emails s = sched.scheduler(time.time, time.sleep)
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)
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 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?")
from lolsteak.models import LolAccount from django.conf import settings from cassiopeia import riotapi from cassiopeia.type.core.common import StatSummaryType from lolsteak.models import LolStat riotapi.set_region("NA") riotapi.set_api_key(settings.LOL_KEY) def update_lol_stats(): lol_accounts = LolAccount.objects.all() account_stats = [] for account in lol_accounts: stats = get_lol_stats(account.summoner_name) stat, created = LolStat.objects.get_or_create( account=account, stat_type=LolStat.UNRANKED ) stat.turrets_killed = stats.totalTurretsKilled stat.minions_killed = stats.totalMinionKills stat.nuetral_minions_killed = stats.totalNeutralMinionsKilled stat.champions_killed = stats.totalChampionKills stat.assists = stats.totalAssists stat.save() account_stats.append(stat) return account_stats
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([
# Enchantments should follow the item name, separated by ' - ' (note the spaces around the dash) items = ["Stalker's Blade - Cinderhulk", "Mercury's Treads - Alacrity", "Dead Man's Plate", "Banshee's Veil", 'Abyssal Scepter', "Liandry's Torment"] build = Build(champion='Amumu', level=18, item_set=items, rune_page=rp, mastery_page=mp) return build def Thresh(): mp = {6311: 5, 6322: 1, 6332: 5, 6342: 1, 6211: 5, 6223: 1, 6232: 5, 6241: 1, 6251: 5, 6263: 1} rp = {5317: 9, 5245: 9, 5289: 9, 5296: 3} items = [3111, 3097, 1011] build = Build(champion=412, level=5, item_set=items, rune_page=rp, mastery_page=mp) return build if __name__ == '__main__': riotapi.set_api_key(os.environ['DEV_KEY']) riotapi.print_calls(True) riotapi.set_region('NA') try: champ = sys.argv[1].lower() except IndexError: champ = 'jinx' if champ == 'jinx': build = Jinx() elif champ == 'annie': build = Annie() elif champ == 'amumu': build = Amumu() elif champ == 'thresh':
def __init__(self): riotapi.set_region("NA") riotapi.set_api_key("462d0d85-d692-4af5-b91f-4ed9cf0b2efe") self.champions = riotapi.get_champions() self.items = riotapi.get_items()
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]):
def riotapi_setup(): riotapi.set_region("NA") api_key = API_key() riotapi.set_api_key(api_key)
# coding=utf-8 """Test for a champ-list """ from cassiopeia import riotapi #riotparams riotapi.set_region("EUW") riotapi.set_api_key("RGAPI-fea9f643-7979-4b87-b857-a8330157d2c8") file = open("champ_list", "r") champs = file.read().splitlines() for champ in champs: xxx = riotapi.get_champion_by_name(champ) try: status = riotapi.get_champion_by_name(champ) except: print("Error while looking up {0}".format(champ))
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) # Load and connect to your database. (Comment this code to use local memory. Don't forget to comment db.close() below too.) # db = SQLAlchemyDB("mysql+mysqlconnector", "databse_hostname", "database_name", "username", "password") # riotapi.set_data_store(db) # Gather master names master = [entry.summoner for entry in riotapi.get_challenger()] mastertests = master print("Pulled Master tier. Got {0} summoners.".format(len(master))) #Make empty lists for match information matchid = [] versionpatch = [] matchdate = [] maptype = [] queue = [] p_names = [] p_sides = [] p_champs = [] p_lanes = [] p_roles = [] p_golds = [] p_wins = [] #Define a start date, and then for each player in the master list, get the match ID number gather_start = datetime(2016, 12, 28, 18) # 1 day after patch 5.14, year month date for summoner in master: for match in summoner.match_list(begin_time=gather_start): # If you are connected to a database, the match will automatically be stored in it without you having to do anything. # Simply pull the match, and it's in your database for whenever you need it again! # If you pull a match twice, the second time it will be loaded from the database rather than pulled from Riot # and therefore will not count against your rate limit. This is true of all datatypes, not just Match. match = get_match(match) print("Got {0}".format(match)) #Then save the match information to some empty lists matchid.append(match.id) versionpatch.append(match.version) matchdate.append(match.creation) maptype.append(match.map) queue.append(match.queue) #Now make empty lists for the player information p1name = [] p1side = [] p1champ = [] p1lane = [] p1role = [] p1gold = [] p1win = [] #Make a loop to get the rest of the participants for part in match.participants: 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) #Save information into the lists 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) #db.close() filename = "master_data_28Dec2016.csv" columns = [ 'matchid', 'versionpatch', 'matchdate', 'maptype', 'queue', 'p_names', 'p_sides', 'p_champs', 'p_lanes', 'p_roles', 'p_golds', 'p_wins' ] df = pd.DataFrame([ matchid, versionpatch, matchdate, 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)
from cassiopeia import riotapi riotapi.set_region("NA") riotapi.set_api_key("6a178ebf-c5a8-42a3-8e3d-c00c6b3e1026") riotapi.set_rate_limits((10, 10), (500, 600)) def getDeaths(match): deathList = [] frameSet = match.frames eventSet = [event for eventList in [frame.events for frame in frameSet] for event in eventList] for event in eventSet: if event.type.name == 'kill': deathList.append(event) return deathList def getWinner(match): #Return winner of the match if match.blue_team.data.winner: return 0 else: return 1 def getRoles(match): '''Return a dict with the following setup: {'teamPosition': idNum} ''' roleMap = {} #Take care of the duo lanes where sup can't be auto determined #Base this on CS value blueDuo = []