Пример #1
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
Пример #2
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
Пример #3
0
def main():
    riotapi.set_rate_limits((10, 10), (500, 600))
    riotapi.get_summoner_by_id = auto_retry(riotapi.get_summoner_by_id) # handling server errors
    riotapi.get_match_list = auto_retry(riotapi.get_match_list)
    riotapi.get_match = auto_retry(riotapi.get_match)
    print('\nCrawling process starts...')
    # set your api key amd seed summoner here
    begin_crawling(api_key='', seed_summoner_id='')
Пример #4
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")
Пример #5
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")
Пример #6
0
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 = []
Пример #7
0
        try:
            data = function(*args)
        except APIError as err:
            print(err)
            if (err.error_code == 404):
                break
            else:
                time.sleep(10)
                continue
        break
    return data


# Setup libraries
riotapi.set_api_key(secret_keys.riotapikey)
riotapi.set_rate_limits((9, 10), (499, 600))
Session = sessionmaker()
Session.configure(bind=engine)  # engine is from model

# Constrain querying to certain regions (to continue from a previously
# interrupted run)
if not sys.argv[1:]:
    regions = [
        'BR', 'EUNE', 'EUW', 'KR', 'LAN', 'LAS', 'NA', 'OCE', 'RU', 'TR'
    ]
else:
    regions = sys.argv[1:]

# Iterating over each region
for region in regions:
    # Customize libraries to region
Пример #8
0
if RIOT_API_KEY:
    riotapi.set_api_key(os.environ["RIOT_API_KEY"])
    riotapi.set_region("NA")
    riotapi.print_calls(True)
    riotapi.set_load_policy(LoadPolicy.lazy)

RIOT_API_KEY_LIMITS = os.environ.get("RIOT_API_KEY_LIMITS")
if RIOT_API_KEY_LIMITS:
    # Expected ENV var format is something like:
    # RIOT_API_KEY_LIMITS=1500/10,90000/600
    rates = RIOT_API_KEY_LIMITS.replace(" ", "")
    rate_tuples = []
    for rate in rates.split(","):
        calls, time = rate.split("/")
        rate_tuples.append((int(calls), int(time)))
    riotapi.set_rate_limits(*rate_tuples)

champion_id = 35
champion_name = "Thresh"
mastery_id = 6361
match_id = 1505030444
rune_id = 5234
summoner_id = 22508641
summoner_name = "FatalElement"
summoner_spell_id = 7
team_id = "TEAM-49fc9f10-1290-11e3-80a6-782bcb4d0bb2"
item_id = 3031


def test_result(result=None):
    assert True  # ??? was Pass previously
Пример #9
0
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)
Пример #10
0
def cards(request):
	if request.GET:
		riotapi.set_api_key("3ca655bb-959d-4ed3-ab2c-287da159aa59")
		riotapi.set_rate_limits((1500, 10), (90000, 600))
		getted = request.GET
		summoner = getted.get('summ')
		region = getted.get('region')
		riotapi.set_region(region)
		riotapi.print_calls(True)
		try:
			summ = riotapi.get_summoner_by_name(summoner)
		except APIError:
			return HttpResponseRedirect('/dorans/')
		masteries = riotapi.get_champion_masteries(summ)
		trophyChampions = {}
		count = 0
		#this sets up so that champions with lvl 4 or higher mastery but if less than 4 are found add more from lower lvls

		for champion, mastery in masteries.items():
			if mastery.level >= 4 :
				trophyChampions[champion] = mastery
				count = count + 1
		if count < 4:
			for champion, mastery in masteries.items():
				if mastery.level == 3 :
					trophyChampions[champion] = mastery
		displayChampions = []
		summid = riotapi.get_summoner_by_name(summoner).id
		for c in trophyChampions:
			print(c)
			topKDA = 0
			kills = 0
			deaths = 0
			assists = 0
			wins = 0
			losses = 0
			MVP = 0
			try:
				matches = riotapi.get_match_list(summ,champions = c, seasons="SEASON2016")
			except APIError:
				matches = riotapi.get_match_list(summ,champions = c, seasons="SEASON2016")
			if not matches:
				continue
			for m in matches:
				try:
					data = riotapi.get_match(m, include_timeline = False)
				except APIError:
					continue
				teamtotal = 0
				tgold = 0
				tdamagedlt = 0
				tdamagetkn = 0
				twards = 0
				twardkls = 0
				for player in data.participants:
					if player.summoner_id == summid: #Build stats from this players participant object
						i = 0
						if player.side.name == 'blue':
							for p in data.participants:
								i +=1
								if i < 5:
									teamtotal += p.stats.kills
									tgold += p.stats.gold_earned
									tdamagedlt +=  p.stats.damage_dealt_to_champions
									tdamagetkn +=  p.stats.damage_taken
									twards +=  p.stats.wards_placed
						else:
							for p in data.participants:
								i += 1
								if i >= 5:
									teamtotal += p.stats.kills
									tgold += p.stats.gold_earned
									tdamagedlt +=  p.stats.damage_dealt_to_champions
									tdamagetkn +=  p.stats.damage_taken
									twards +=  p.stats.wards_placed
						if teamtotal == 0 :
							teamtotal = 1;
						if twards == 0:
							twards == 1;
						topKDA = player.stats.kda if player.stats.kda > topKDA else topKDA
						kills += player.stats.kills
						deaths += player.stats.deaths
						assists += player.stats.assists
						trip = player.stats.triple_kills
						quad = player.stats.quadra_kills
						penta = player.stats.penta_kills
						kp = player.stats.kills/teamtotal
						g = player.stats.gold_earned/tgold
						cs = player.stats.cs/data.duration.seconds
						dmgdlt = player.stats.damage_dealt_to_champions/tdamagedlt
						dmgtkn = player.stats.damage_taken/tdamagetkn
						wards = player.stats.wards_placed/twards
						kda = player.stats.kda
						if kda == 1:
							kda = 1.1
						if kda == 0:
							try:
								kda = .01/p.stats.deaths
							except ZeroDivisionError:
								kda = .1
						if p.timeline.role.name ==  'solo':
							if p.timeline.lane.name == 'mid_lane': #mid
								MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 12) + (dmgtkn * -1) + (wards *4)  ) + trip * .25 + quad * .5 + penta * 1
							else:
								#print(math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 7) + (dmgtkn * 7) + (wards *4)  ))
								MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 7) + (dmgtkn * 7) + (wards *4)  ) + trip * .25 + quad * .5 + penta * 1
						elif p.timeline.role.name == 'carry':# carry
							#print(math.log(kda)/math.log(6) * ((kp * 10)+(g * 6)+(cs * .7)+ (dmgdlt * 12) + (dmgtkn * 1) + (wards *1)  ))
							MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 12) + (dmgtkn * -1) + (wards *4)  )+ trip * .25 + quad * .5 + penta * 1
						elif p.timeline.role.name == 'support': #supp
							#print(math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 7) + (dmgtkn * 7) + (wards *6)  ))
							MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * 1.0)+ (dmgdlt * 6) + (dmgtkn * 7) + (wards *5)  )+ trip * .25 + quad * .5 + penta * 1

						elif p.timeline.role.name == 'none': #jungle
							#print(math.log(kda)/math.log(6))
							MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 7) + (dmgtkn * 7) + (wards *4)  )+ trip * .25 + quad * .5 + penta * 1

						else: #unknown duo setup
							#print(math.log(kda)/math.log(6))
							MVP += math.log(kda)/math.log(6) * ((kp * 10)+(g * 5)+(cs * .7)+ (dmgdlt * 10) + (dmgtkn * 2) + (wards *4)  ) + trip * .25 + quad * .5 + penta * 1
						
						if player.stats.win:
							wins = wins + 1
						else:
							losses = losses + 1

			championStats = {}
			championStats['level'] = masteries[c].level
			championStats['topGrade'] = masteries[c].highest_grade
			championStats['points'] = masteries[c].points
			championStats['topKDA'] = round(topKDA, 2)
			if deaths == 0:
				deaths = 1
			championStats['KDA'] = round((kills + assists) / deaths , 2)
			championStats['avgkills'] = round(kills / (wins+ losses), 2)
			championStats['avgdeaths'] = round(deaths / (wins+ losses), 2)
			championStats['avgassists'] = round(assists / (wins+ losses), 2)
			championStats['avgMVP'] = round(MVP / (wins + losses), 2)
			championStats['wins'] = wins
			championStats['losses'] = losses
			imagep = c.image.link
			imagep = imagep.split('.')
			image = 'http://ddragon.leagueoflegends.com/cdn/img/champion/loading/' + imagep[0] + '_0.jpg'
			displayChampions.append({'name':str(c), 'stats':championStats, 'mastery': masteries[c], 'masterypoint':masteries[c].points, 'image': image })
		displayChampions = sorted(displayChampions, key=itemgetter('masterypoint'), reverse=True)


		return HttpResponse(render(request, 'doranscards.html', {'champions' : displayChampions}))
	else:
		return HttpResponseRedirect('/dorans/')
Пример #11
0
opbeat = Opbeat(
    app,
    organization_id='8fab471734d0471da233ae94b816e421',
    app_id='d578fa0187',
    secret_token='e6f52c2d50feb7278e91aec9f516776db173c577',
)



# Set API key
# Lets cassi handle riot api rate limits. But does this work per instance of this app (if many ppl are using website at same time) or globally? is this the best place
# for this, or should this be under the relevant url routes?
riotapi.set_region('na')
riotapi.print_calls(True)
riotapi.set_api_key(API_KEY)
riotapi.set_rate_limits((9, 10), (480, 600))
riotapi.set_load_policy(LoadPolicy.lazy)

baseriotapi.set_region('na')
baseriotapi.print_calls(True)
baseriotapi.set_api_key(API_KEY)
baseriotapi.set_rate_limits((9, 10), (480, 600))


def auto_retry(api_call_method):
    """ A decorator to automatically retry 500s (Service Unavailable) and skip 400s (Bad Request) or 404 (Not Found). """
    def call_wrapper(*args, **kwargs):
        try:
            return api_call_method(*args, **kwargs)
        except APIError as error:
            # Try Again Once