示例#1
0
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(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()
示例#3
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.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)
    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)
    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))
示例#6
0
 async def set(self, ctx, region: str):
     """Set your server's default region"""
     try:
         riotapi.set_region(region)
     except ValueError:
         embed = discord.Embed(
             title="Error!",
             description="{0} is not a valid region!".format(region),
             colour=0xCA0147)
         utilities.footer(ctx, embed)
         await ctx.send("", embed=embed)
         return
     db = database.Database('guilds.db')
     try:
         region_found = db.find_entry(ctx.guild.id)
         db.close_connection()
         embed = discord.Embed(
             title="Error!",
             description="{0} is already {1}'s default region!".format(region_found, ctx.guild.name),
             colour=0xCA0147)
         utilities.footer(ctx, embed)
         await ctx.send("", embed=embed)
     except TypeError:
         db.add_entry(ctx.guild.id, region)
         db.close_connection()
         embed = discord.Embed(
             title="Success!",
             description="{0} set as {1}'s default region!".format(region, ctx.guild.name),
             colour=0x1AFFA7)
         utilities.footer(ctx, embed)
         await ctx.send("", embed=embed)
示例#7
0
 async def update(self, ctx, region: str):
     """Update your server's default region"""
     try:
         riotapi.set_region(region)
     except ValueError:
         embed = discord.Embed(
             title="Error!",
             description="{0} is not a valid region!".format(region),
             colour=0xCA0147)
         utilities.footer(ctx, embed)
         await ctx.send("", embed=embed)
         return
     db = database.Database('guilds.db')
     try:
         db.find_entry(ctx.guild.id)
         db.update_entry(ctx.guild.id, region)
         db.close_connection()
         embed = discord.Embed(
             title='Success!',
             description="Set {0} as {1}'s default region!".format(region, ctx.guild.name),
             colour=0x1AFFA7)
         utilities.footer(ctx, embed)
         await ctx.send("", embed=embed)
     except TypeError:
         db.close_connection()
         embed = discord.Embed(
             title="Error!",
             description="A default region for this server has not been set!",
             colour=0xCA0147)
         utilities.footer(ctx, embed)
         await ctx.send("", embed=embed)
示例#8
0
def set_region(new_region: str):
    """
    Set a new Region for the API to make Calls on.
    
    :param new_region: The New Region to set 
    """
    riotapi.set_region(new_region)
def getCurrentMatch(summonerName, region="NA"):
	riotapi.set_region(region)
	summoner = riotapi.get_summoner_by_name(summonerName)
	match = riotapi.get_current_game(summoner)
	if match is None:
		return None
	roleMap = allRoles(match)
	# for x in roleMap:
	# 	print x.champion.name, x.side.name, roleMap[x]
	if len(roleMap.keys()) < 10:
		print "Role confusion!"
		return None
	statMap = {}
	rankMap = {}
	nonNormMap = {}
	for p in match.participants:
		role = roleMap[p]
		stats, nonNorm, rank = avgPerformance.getAvgPerformance(p, role)
		if stats is None:
			#currently filling with avg gold?
			stats = getAvg()
			rank = "unranked"
		statMap[p.side.name+role] = list(stats)
		rankMap[p] = rank
		nonNormMap[p] = nonNorm
		print p.summoner_name, p.side.name+role
	statVector = (statMap['blueTop']+statMap['blueMid']+statMap['blueJung']+
				statMap['blueSup']+statMap['blueADC']+statMap['redTop']+
				statMap['redMid']+statMap['redJung']+statMap['redSup']+
				statMap['redADC'])
	model = fetchModel(match)
	results = model.predict_proba(statVector)
	return format.prepareReturn(roleMap, rankMap, nonNormMap, results, match)
def 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))
示例#11
0
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
示例#12
0
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
示例#13
0
	def __str__(self):
		try:
			p =Player.objects.get(SummonerNumber=self.PlayerID)
			return p.PlayerIGN
		except ObjectDoesNotExist:
			riotapi.set_region("NA")
			s= riotapi.get_summoner_name(self.PlayerID)
			return s
示例#14
0
	def __str__(self):
		try:
			p =Player.objects.get(SummonerNumber=self.PlayerID)
			return p.PlayerIGN
		except ObjectDoesNotExist:
			riotapi.set_region("NA")
			s= riotapi.get_summoner_name(self.PlayerID)
			return s
示例#15
0
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))
示例#16
0
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
示例#17
0
def updateIDs(request):
	NoIDs = Player.objects.filter(SummonerNumber=0)
	riotapi.set_region("NA")
	for play in NoIDs:
		summtoadd = riotapi.get_summoner_by_name(play.PlayerIGN)
		play.SummonerNumber = summtoadd.id
		play.save()
		print(summtoadd.id)
	return HttpResponse("All unset IDs have been updated")
示例#18
0
def checkgame(zone,name):
    try:
        riotapi.set_region(zone)
        cgame = riotapi.get_current_game(riotapi.get_summoner_by_name(name))
    except:
        print("printing traceback:")
        traceback.print_exc()

    if cgame is None:
        return jsonify({'current_game_exists': False})
    else:
        return jsonify({'current_game_exists': True})
示例#19
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.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)
示例#20
0
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")
示例#21
0
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)
示例#22
0
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")
示例#23
0
def isSupport(summname, region):
    """Returns True if the summoner is a support main, False otherwise."""
    #initalize variables
    summoner = riotapi.get_summoner_by_name(summname)
    riotapi.set_region(region)
    match_history = riotapi.get_match_list(summoner, 5)
    counter = 0
    for match in match_history:
        if str(match.role) == 'Role.support':
            counter += 1
        if counter == 3:
            return True
    return False
def 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()
示例#25
0
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()
示例#26
0
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
示例#27
0
    async def game(self, ctx, sum_name: str, region: str):

        if region is None:
            try:
                db = database.Database('guilds.db')
                region = db.find_entry(ctx.guild.id)
                db.close_connection()
            except TypeError:
                embed = utilities.error_embed(
                    ctx,
                    "Please specify a region, or set a default region with `b!region set [region]`."
                )
                await ctx.send("", embed=embed)
                return

        if "'" in sum_name:
            embed = utilities.error_embed(
                ctx, "Please use quotation marks to enclose names")
            await ctx.send("", embed=embed)
            return

        await ctx.trigger_typing()

        try:
            riotapi.set_region(region)
        except ValueError:
            embed = utilities.error_embed(
                ctx,
                "{0} is not a valid region! Valid regions are listed in `b!region list`."
                .format(region))
            await ctx.send("", embed=embed)
            return

        try:
            summoner = riotapi.get_summoner_by_name(sum_name)
            game = riotapi.get_current_game(summoner)
        except APIError as exception:
            await Summoner.raise_exception(self, ctx, exception, sum_name,
                                           region)
            return

        try:
            does_game_exist = game.id
        except AttributeError:
            embed = utilities.error_embed(
                ctx, "{} is not in an active game!".format(summoner.name))
            await ctx.send("", embed=embed)
            return
示例#28
0
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)
    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))
示例#30
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.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 = []
示例#31
0
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(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])
示例#33
0
def addplayerlist(request):
	if not request.user.is_authenticated():
		return HttpResponseRedirect('/ols/login')
	else:
		posted = request.POST
		#playerlist = posted.split(','')
		playerlist = posted.get('players').split(',')
		print(playerlist)
		riotapi.set_region("NA")
		for player in playerlist:
			player = player.split(':')
			play = Player()		
			play.PlayerName = player[0]
			play.PlayerIGN = player[1]
			play.SummonerNumber = riotapi.get_summoner_by_name(player[1]).id
			play.save()
		return HttpResponse("Added players")
示例#34
0
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))
示例#35
0
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()
示例#38
0
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()
示例#39
0
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()
示例#40
0
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()
示例#41
0
def AddTeam(request):
	if request.POST:
		newteam = Team()
		posted = request.POST
		#print(posted.get('teamname'))
		newteam.teamName = posted.get('teamname')
		newteam.Captain = posted.get('cap')
		newteam.Player1 = posted.get('P1')
		newteam.Player2 = posted.get('P2')
		newteam.Player3 = posted.get('P3')
		newteam.Player4 = posted.get('P4')
		riotapi.set_region("NA")
		summtoadd = riotapi.get_summoner_by_name(newteam.Captain)
		print(summtoadd)
		newteam.CaptainID = summtoadd.id
		summtoadd = riotapi.get_summoner_by_name(newteam.Player1)
		print(summtoadd)
		newteam.Player1ID = summtoadd.id
		summtoadd = riotapi.get_summoner_by_name(newteam.Player2)
		print(summtoadd)
		newteam.Player2ID = summtoadd.id
		summtoadd = riotapi.get_summoner_by_name(newteam.Player3)
		print(summtoadd)
		newteam.Player3ID = summtoadd.id
		summtoadd = riotapi.get_summoner_by_name(newteam.Player4)
		print(summtoadd)
		newteam.Player4ID = summtoadd.id
		#print(Team.objects.all().aggregate(Max('teamID')))
		try:
			if Team.objects.all().aggregate(Max('teamID'))['teamID_max'] is not None:
				newteam.teamID = Team.objects.all().aggregate(Max('teamID'))['teamID__max'] + 1
			else:
				raise KeyError("no teams yet")
		except KeyError:
			newteam.teamID = 0
		newteam.save()
		return HttpResponse(render(request, 'addedteam.html'))
	else:
		return HttpResponse(render(request, 'addteam.html'))
def getCurrentMatch(summonerName, region="NA"):
	riotapi.set_region(region)
	try:
		summoner = riotapi.get_summoner_by_name(summonerName)
		match = riotapi.get_current_game(summoner)
	except APIError as e:
		print e
		return None
	if match is None:
		return None
	if match.mode.name != "classic":
		print "Not classic"
		return None
	roleMap = allRoles(match)
	if len(roleMap.keys()) < 10:
		roleMap = assignRandom(match)
		print "Role confusion!"
	statMap = {}
	rankMap = {}
	nonNormMap = {}
	for p in match.participants:
		role = roleMap[p]
		try:
			stats, nonNorm, rank = avgPerformance.getAvgPerformance(p, role)
		except:
			stats = getAvg(p.side.name+role)
			rank = "unranked"
			nonNorm = [0, 0, 0, 0, 0, 0]
		statMap[p.side.name+role] = list(stats)
		rankMap[p] = rank
		nonNormMap[p] = nonNorm
		print p.summoner_name, p.side.name+role
	statVector = (statMap['blueTop']+statMap['blueMid']+statMap['blueJung']+
				statMap['blueSup']+statMap['blueADC']+statMap['redTop']+
				statMap['redMid']+statMap['redJung']+statMap['redSup']+
				statMap['redADC'])
	model = fetchModel(match, rankMap)
	results = model.predict_proba(statVector)
	return format.prepareReturn(roleMap, rankMap, nonNormMap, results, match)
示例#43
0
def updateTeamIDs(request):
	teams = Team.objects.all()
	riotapi.set_region("NA")
	for t in teams:
		if t.CaptainID == 0:
			summtoadd = riotapi.get_summoner_by_name(t.Captain)
			t.CaptainID = summtoadd.id
		if t.Player1ID == 0:
			summtoadd = riotapi.get_summoner_by_name(t.Player1)
			t.Player1ID = summtoadd.id
		if t.Player2ID == 0:
			summtoadd = riotapi.get_summoner_by_name(t.Player2)
			t.Player2ID = summtoadd.id
		if t.Player3ID == 0:
			summtoadd = riotapi.get_summoner_by_name(t.Player3)
			t.Player3ID = summtoadd.id
		if t.Player4ID == 0:
			summtoadd = riotapi.get_summoner_by_name(t.Player4)
			t.Player4ID = summtoadd.id
		t.save()

	return HttpResponse("All unset IDs have been updated")
def 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)))
示例#45
0
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()
示例#46
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]))
示例#47
0
def summoner(summ):

    summ = summ.replace(" ", "")

    # regionlist = [zone.value for zone in Region]
    regionlist = ['na', 'kr', 'euw', 'eune']
    zone_summoners = []

    # Try to speed this up by using pure riot json requests simultaneously for all regions?
    for r in regionlist:

        cassdb = SQLAlchemyDB(connector, host, dbnames[r]+"?charset=utf8", user, passwd)
        riotapi.set_data_store(cassdb)

        riotapi.set_region(r)

        try:
            s = riotapi.get_summoner_by_name(summ)
            if s is not None:
                zone_summoners.append((r, s))
                print("{} from {} appended".format(s.name, r))
        except APIError as error:
            print(error)
            print(error.error_code)

        cassdb.close() # attempt to avoid mysql went away

    if len(zone_summoners) == 0:
        error = "Summoner with that name not found. Try another one."
        return render_template('index.html', error=error)

    patch = riotapi.get_versions()[0]

    return render_template('zone.html',
                        zone_summoners = zone_summoners,
                        summname = summ,
                        patch = patch)
示例#48
0
def home():
    err = None
    if request.method == 'POST':
        if not request.form['summonerName']:
            err = 'Please provide us with your summoner name'
        elif not request.form['region']:
            err = 'Please write your E-mail address'
        elif get_summoner(request.form['summonerName']) is not None:
            err = 'The username is already taken'
        else:
            db = get_db()
            db.execute(
                '''INSERT INTO summonerDBid(
              summonerName) VALUES (?)''', [request.form['summonerName']])
            db.commit()
            flash('Your summoner info has been stored')
            summonerName = request.form['summonerName']

            return redirect(
                url_for('summoner',
                        sumName=summonerName,
                        region=riotapi.set_region(request.form['region'])))

    return render_template('homepage.html', err=err)
def riotapi_setup():
	riotapi.set_region("NA")
	api_key = API_key()
	riotapi.set_api_key(api_key)
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?")
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 insert_games(sum_id, region):
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%d-%m-%Y %H:%M:%S')
    logging.info(st + " - Inserting games for " + str(sum_id) + " from " + str(region))
    try:
        riotapi.set_region(region)
        summoner = riotapi.get_summoner_by_id(sum_id)
        games = summoner.match_list()

        for g in games:
            if not collgame.find({'_id': str(g.id)}).count() > 0:
                try:
                    game = defaultdict(list)
                    match = g.match()
                    game.update({
                        "_id": str(g.id),
                        "date": str(match.creation),
                        "duration": str(match.duration),
                        "platform": str(match.platform),
                        "region": str(match.region),
                        "season": str(match.season),
                        "version": match.version,
                        "participants": []
                    })
                    try:
                        for p in g.match().participants:
                            try:
                                game['participants'].append({
                                    "_id": str(p.summoner_id),
                                    "name": p.summoner_name,
                                    "champion": p.champion.name,
                                    "won": p.stats.win,
                                    "side": get_side(p.side),
                                    "kills": p.stats.kills,
                                    "deaths": p.stats.deaths,
                                    "assists": p.stats.assists,
                                    "kda": p.stats.kda,
                                    "cs": p.stats.cs,
                                    "sum_d": str(p.summoner_spell_d),
                                    "sum_f": str(p.summoner_spell_f),
                                    "champ_lvl": p.stats.champion_level,
                                    "gold_earned": p.stats.gold_earned,
                                    # "items": [item.name if item is not None else None for item in p.stats.items],
                                    "m_dmg_dealt": p.stats.magic_damage_dealt,
                                    "p_dmg_dealt": p.stats.physical_damage_dealt,
                                    "dmg_2_champs": p.stats.damage_dealt_to_champions,
                                    "lane": get_lane(p.timeline.lane)
                                })
                            except:
                                ts = time.time()
                                st = datetime.datetime.fromtimestamp(ts).strftime('%d-%m-%Y %H:%M:%S')
                                logging.warning(st + " - APIError exception found while adding a participant for " + str(sum_id) + " in " + str(region))
                    except:
                        ts = time.time()
                        st = datetime.datetime.fromtimestamp(ts).strftime('%d-%m-%Y %H:%M:%S')
                        logging.warning(st + " - APIError exception found while loading participants for " + str(sum_id) + " in " + str(region))

                    key = {"_id": str(g.id)}
                    data = {"$set": game}
                    collgame.update_one(key, data, upsert=True)
                except:
                    ts = time.time()
                    st = datetime.datetime.fromtimestamp(ts).strftime('%d-%m-%Y %H:%M:%S')
                    logging.warning(st + " - APIError exception found while loading game for " + str(sum_id) + " in " + str(region))
    except:
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime('%d-%m-%Y %H:%M:%S')
        logging.error(st + " - APIError exception found while setting Region (Cassiopeia), getting summoner or getting " \
                   "match_list. Most likely it's match_list for " + str(sum_id) + " in " + str(region))

    # Updating games count value
    games_count = collgame.find({"participants._id": str(sum_id)}).count()
    collsums.update({"_id": int(sum_id)}, {"$set": {"games_count": games_count}})

    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%d-%m-%Y %H:%M:%S')
    logging.info(st + " - Analysing lane champion summoners wins for " + str(sum_id) + " in " + str(region))
    lane_sums(str(sum_id))

    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%d-%m-%Y %H:%M:%S')
    logging.info(st + " - Analysing lane summoners wins for " + str(sum_id) + " in " + str(region))
    lane_champ_sums(str(sum_id))

    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%d-%m-%Y %H:%M:%S')
    logging.info(st + " - Games inserted for " + str(sum_id) + " in " + str(region))

    # we will now send an email confirming the data is already collected if the person has subscribed to the list
    summoner = riotapi.get_summoner_by_id(sum_id)
    send_email(summoner.name, region)
示例#54
0
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))
示例#55
0
    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':
        build = Thresh()
    else:
示例#56
0
# 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))
示例#57
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.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)
 def test_we_can_use_unicode(self):
     # We shouldn't check if str instead check if NOT Region
     riotapi.set_region(u"NA")
     assert True