async def champ(self, ctx, name, champname): """Gets information about champ's use on account """ await ctx.send("Working...") try: kal = cass.Summoner(name=name, region='NA') mast = toDict(kal.champion_masteries) champ = mast[champname] time = champ.last_played.format('YYYY-MM-DD HH:mm:ss') nam = kal.name champnam = champ.champion.name chest = champ.chest_granted lp = time lvl = champ.level pts = champ.points await ctx.send(f'''```{nam}'s {champnam}: \n Chest Granted: {chest} Last played: {lp} Mastery level: {lvl} Points: {pts}```''') except: await ctx.send("Bad input or bad something else not sure")
def test_unknown_summoner(self): for e in cassiopeia.Summoner(name="Kalturi", region="NA").league_entries: print(e.league.name) self.assertFalse( cassiopeia.get_summoner(name=UNKNOWN_SUMMONER_NAME, region="NA").exists)
def _run_impl(self, args): if args: return self.print_invalid_usage() for summoner in self.db.summoners.find(): print(f'Updating matches for {summoner["name"]}...') last_updated_match_id = summoner['last_updated_match_id'] summoner = cass.Summoner(puuid=summoner['puuid']) matches_to_insert = [] latest_match_id = None for match in summoner.match_history: if latest_match_id is None: latest_match_id = match.id if match.id == last_updated_match_id: break if self.db.matches.find_one({'id': match.id}) is None: match_data = match.load().to_dict() encode.bson_ready(match_data) prune_match_data(match_data) matches_to_insert.append(match_data) if matches_to_insert: self.db.matches.insert_many(matches_to_insert) self.db.summoners.update( {'puuid': summoner.puuid}, {'$set': { 'last_updated_match_id': latest_match_id }}, upsert=False)
def test_can_get_league_entries(): config_backup = cassiopeia.configuration.settings cassiopeia.apply_settings({"global": {"default_region": "NA"}}) summoner = cassiopeia.Summoner(name=SUMMONER_NAME) summoner.league_entries # restore global settings to not affect other tests if they are run in one session cassiopeia.apply_settings(config_backup)
def _run_impl(self, args): if len(args) != 0: return self.print_invalid_usage() for summoner in self.db.summoners.find(): updated_summoner = cass.Summoner(puuid=summoner['puuid']).load() self.db.summoners.update({'puuid': summoner['puuid']}, {'$set': updated_summoner.to_dict()})
def test_match_history_8(): summoner = cass.Summoner(name="chowdog", region="NA") mh = cass.get_match_history(summoner=summoner, begin_index=0, end_index=20, queues={Queue.ranked_solo_fives}) match = mh[0] assert len(match.participants) == 10
def test_match_history_8(): summoner = cass.Summoner(name="chowdog", region="NA") mh = cass.get_match_history(summoner=summoner, region=summoner.region, begin_index=0, end_index=20) match = mh[0] assert len(match.participants) == 10
def verify_summoner(self, veigar_bot_user): # Expired user global _league_account if time_difference_in_seconds( current_time_in_seconds(), veigar_bot_user.ts_max) > MAX_DURATION_SUMM: return # process attempt adjust timestamp, in 2 seconds process again if time_difference_in_seconds( current_time_in_seconds(), veigar_bot_user.ts_min) < MIN_DURATION_SUMM: veigar_bot_user.ts_min = current_time_in_seconds() self.work_queue.put(veigar_bot_user) return try: _league_account = cass.Summoner( name=veigar_bot_user.summoner_name, region=veigar_bot_user.region) if Queue.ranked_solo_fives in _league_account.ranks \ and _league_account.ranks[Queue.ranked_solo_fives].tier.name: veigar_bot_user.tier = _league_account.ranks[ Queue.ranked_solo_fives].tier.name else: pass approved = [ _league_account.verification_string is not None, _league_account.verification_string == veigar_bot_user.hash_code ] # processed & approved if all(approved): veigar_bot_user.is_approved = True self.processed_queue.put(veigar_bot_user) return # pending & put back in queue if time_difference_in_seconds( current_time_in_seconds(), veigar_bot_user.ts_max) < MAX_DURATION_SUMM: self.work_queue.put(veigar_bot_user) except Exception as exception: if _league_account.exists and \ time_difference_in_seconds(current_time_in_seconds(), veigar_bot_user.ts_max) < MAX_DURATION_SUMM: self.work_queue.put(veigar_bot_user) return else: logger.error( "Issue verifying summoner; Riot API call: {0} {1} {2} {3}" .format(veigar_bot_user.summoner_name, veigar_bot_user.region, veigar_bot_user.is_approved, exception))
def _run_impl(self, args): if len(args) != 1: return self.print_invalid_usage() summoner_names = args[0].split(',') summoners = [] for name in summoner_names: if not name: print('Summoner name cannot be empty.') return try: summoners.append(cass.Summoner(name=name).load()) except datapipelines.common.NotFoundError: print(f'Summoner "{name}" not found.') return summoners.sort(key=lambda s: s.name) pipeline = self.match_filtering_flags.filter_steps() + [ {'$project': {'participants': True}}, {'$unwind': '$participants'}, {'$match': {'participants.accountId': {'$in': [summoner.account_id for summoner in summoners]}}}, {'$group': {'_id': {'championId': '$participants.championId', 'accountId': '$participants.accountId'}, 'champ_damage': {'$max': '$participants.stats.totalDamageDealtToChampions'}, }}, ] # yapf: disable results = {(result['_id']['championId'], result['_id']['accountId']): result for result in self.db.matches.aggregate(pipeline)} global_pipeline = self.match_filtering_flags.filter_steps() + [ {'$project': {'participants': True}}, {'$unwind': '$participants'}, {'$group': {'_id': {'championId': '$participants.championId'}, 'games_played': {'$sum': 1}, 'champ_damage': {'$max': '$participants.stats.totalDamageDealtToChampions'}, }}, ] # yapf: disable global_results = { result['_id']['championId']: result for result in self.db.matches.aggregate(global_pipeline) } champion_list = cass.get_champions() champ_id_to_name = {champ.id: champ.name for champ in champion_list} table = [] for champ_id, champ_name in sorted(champ_id_to_name.items(), key=lambda t: t[1]): row = collections.OrderedDict({'Champion': champ_name}) for summoner in summoners: row[summoner.name] = self.format_result( results.get((champ_id, summoner.account_id))) row['Global Avg'] = self.format_result( global_results.get(champ_id)) table.append(row) self.table_output_flags.output_table(table)
async def level(self, ctx, *args): """Gets level of league account""" name = listToString(args) try: kal = cass.Summoner(name=name, region='NA') await ctx.send('''```{name}'s level is {str1}```'''.format( name=kal.name, str1=kal.level)) except: await ctx.send("User doesn't exist probably maybe")
async def goodwith(self, ctx, name): """Returns champs account has above mastery 6 with (slow)""" await ctx.send("Working..." "") kalturi = cass.Summoner(name=name, region='NA') good_with = kalturi.champion_masteries.filter(lambda cm: cm.level >= 6) names = [] for item in good_with: names.append(item.champion.name) await ctx.send('```{nam}\'s best champions: \n'.format(nam=name) + pretlist(names) + '```')
def fetchCurrentMatchId(name, region): player = cass.Summoner(name=name, region=region) try: current_match_id = player.current_match.id # below for debugging # print(current_match_id) # print("User is currently in a match!") return current_match_id except: # print("User is not currently in a match!") return -1
def save(self, *args, **kwargs): if not self.pk: # api_key = riot_key() # watcher = RiotWatcher(api_key) # my_region = 'euw1' # account = watcher.summoner.by_name(my_region, self.summoner_name) account = cass.Summoner(name=self.summoner_name) self.account_id = account.account.id self.icon_id = account.profile_icon.id self.summoner_id = account.id self.level = account.level self.summoner_name = account.name super().save(*args, **kwargs)
async def pp(self, ctx, *args): """Gets profile pic of league account. 50% failure rate """ name = listToString(args) print(name) await ctx.send("Working...") try: kal = cass.Summoner(name=name, region='NA') print(kal.exists) await ctx.send(f'''{kal.name}'s profile pic: \n {kal.profile_icon.url}''') except: await ctx.send("Bad input or bad something else not sure")
def fetchMatchHistory(name, region, stream_start_time): player = cass.Summoner(name=name, region=region) start_time = arrow.get(stream_start_time) end_time = arrow.now() match_history = MatchHistory(summoner=player, begin_time=start_time, end_time=end_time) match_data = [] # OPEN matchCLip.json """ with open('matchClip.json') as clip_record: clips = json.load(clip_record) """ for match in match_history: #print(match.id) p = match.participants[player] #print("\nSince the match was created from a matchref, we only know one participant:") #print(p.summoner.name, 'playing', p.champion.name) #print(p.id, p.summoner.account.id, p.summoner.region, p.participantstats.kills, p.participantstats.deaths, p.participantstats.assists) match_dict = {} try: match_dict.update({ 'match_id': match.id, 'win': p.stats.win, 'kills': p.stats.kills, 'deaths': p.stats.deaths, 'assists': p.stats.assists, 'champion_id': p.champion.id, 'champion_name': p.champion.name, 'clips': clips[match.id] }) except: match_dict.update({ 'match_id': match.id, 'win': p.stats.win, 'kills': p.stats.kills, 'deaths': p.stats.deaths, 'assists': p.stats.assists, 'champion_id': p.champion.id, 'champion_name': p.champion.name, 'clips': '' }) match_data.append(match_dict) print(match.id, p.stats.win, p.stats.kills, p.stats.deaths, p.stats.assists, p.champion.id, p.champion.name) #print(p.summoner.region, p.summoner.account.id, p.summoner.name, p.summoner.id, p.champion.id, p.ParticipantStatsData.kills) # CLOSE matchClip.json print(match_data) return match_data
def _run_impl(self, args): if len(args) != 1: return self.print_invalid_usage() summoner_name = args[0] try: summoner = cass.Summoner(name=summoner_name).load() match = {'puuid': summoner.puuid} except datapipelines.common.NotFoundError: print( f'Summoner "{summoner_name}" does not exist. Attempting to match document by name (case-sensitive) in case the summoner name changed...' ) match = {'name': summoner_name} result = self.db.summoners.delete_one(match) if not result.deleted_count: print(f'Summoner "{summoner_name}" is already not tracked.')
def test_access_properties(self): s = cassiopeia.Summoner(name=SUMMONER_NAME) self.assertIsNotNone(s.region) self.assertIsNotNone(s.platform) self.assertIsNotNone(s.account_id) self.assertIsNotNone(s.puuid) self.assertIsNotNone(s.id) self.assertIsNotNone(s.name) self.assertIsNotNone(s.sanitized_name) self.assertIsNotNone(s.level) self.assertIsNotNone(s.profile_icon) self.assertIsNotNone(s.revision_date) self.assertIsNotNone(s.match_history_uri) self.assertIsNotNone(s.champion_masteries) self.assertIsNotNone(s.match_history) self.assertIsNotNone(s.league_entries) self.assertIsNotNone(s.rank_last_season)
def _run_impl(self, args): if len(args) != 1: return self.print_invalid_usage() summoner_name = args[0] try: summoner = cass.Summoner(name=summoner_name).load() except datapipelines.common.NotFoundError: print(f'Summoner "{summoner_name}" not found.') return data = summoner.to_dict() data['last_updated_match_id'] = None try: self.db.summoners.insert_one(data) except pymongo.errors.DuplicateKeyError: print(f'Summoner "{summoner_name}" is already being tracked.')
def setup_streamer_config(raw_json): input_dict = json.loads(raw_json) #cass.set_default_region("NA") #cass.set_default_region(input_dict["region"]) global player global stream_start_time global broadcaster_id stream_start_time = input_dict["stream_start_time"] broadcaster_id = input_dict["broadcaster_id"] player = cass.Summoner(name=input_dict["summoner_name"], region=input_dict["region"]) success = str('Streamer config setup for Summoner Name: ' + str(player.name) + ' in the ' + str(player.region) + ' region.') result = str({"setup_status": success}) return result
def print_newest_match(name: str, region: str): summoner = cass.Summoner(name=name, region=region) match_history = summoner.match_history( queues={cass.Queue.ranked_solo_fives}) match = match_history[0] print("Match ID:", match.id) print("Frame interval:", match.timeline.frame_interval) # The cumulative timeline property allows you to get some info about participants during the match. # You access the cumulative timeline by providing the duration into the game that you want the info for. # In this case, we're accessing the game at 15 minutes and 30 seconds. # Some data is only available every one minute. for p in match.participants: p_state = p.cumulative_timeline[datetime.timedelta(minutes=15, seconds=30)] # You can also use a string instead of datetime.timedelta items = p_state.items wards_placed = 0 for temp_event in p_state._processed_events: if temp_event.type == "WARD_PLACED": wards_placed += 1 items = [item.name for item in items] skills = p_state.skills print("Player:", p.summoner.name) print("Champion:", p.champion.name) print("Items:", items) print("Skills:", skills) print("Kills:", p_state.kills) print("Deaths:", p_state.deaths) print("Assists:", p_state.assists) print("KDA:", p_state.kda) print("Level:", p_state.level) print("Position:", p_state.position) print("Exp:", p_state.experience) print("Number of objectives assisted in:", p_state.objectives) print("Wards placed:", wards_placed) print("Gold earned:", p_state.gold_earned) print("Current gold:", p_state.current_gold) print("CS:", p_state.creep_score) print("CS in jungle:", p_state.neutral_minions_killed)
def __init__(self, username: str): # Check user exists on Riot's side try: user: cassiopeia.Summoner = cassiopeia.Summoner(name=username) # Load in data self.user_exists = user.exists self.username = user.name self.account_id = user.account_id self.level = int(user.level) self.icon = user.profile_icon except Exception as err: # Actually fail out if it's a bad key issue response_code = int(str(err)) if response_code == 401 or 403: raise Exception(err) # Otherwise just assume the user doesn't exist, as that'll be the # most common response self.user_exists = False return
def get_summoner(region, name): print(region) print(name) print(ONLINE) print("test") return cass.Summoner(region=region, name=name)
def test_match_participant_search(): summoner = cassiopeia.Summoner(name='Kejorn', region='NA') match = summoner.match_history[0] p = match.participants[summoner]
def _run_impl(self, args): if len(args) != 0: return self.print_invalid_usage() # --- PART 1 --- for summoner in self.db.summoners.find(): new_summoner = cass.Summoner(name=summoner['name']).load() data = new_summoner.to_dict() data['last_updated_match_id'] = summoner['last_updated_match_id'] if self.db.temp_summoners.find_one({'puuid': summoner['puuid']}): continue try: self.db.temp_summoners.insert_one(data) except pymongo.errors.DuplicateKeyError: pass already_updated_count = 0 full_renew_count = 0 partial_renew_count = 0 partial_renew_failures = 0 match_cursor = self.db.matches.find(no_cursor_timeout=True) for match in match_cursor: if self.db.temp_matches.find_one({'id': match['id']}): already_updated_count += 1 continue try: match = cass.Match(id=match['id'], region=match['region']).load() match_data = match.to_dict() encode.bson_ready(match_data) update_matches.prune_match_data(match_data) full_renew_count += 1 self.db.temp_matches.insert_one(match_data) except datapipelines.common.NotFoundError: print(f'Match {match["id"]} not found.') match['partial_migration'] = True for i, participant in enumerate(match['participants']): try: # Potentially someone could have switched their summoner name and # a different account could have stolen it but it is unlikely and # not very important for our purposes. summoner = cass.Summoner( name=participant['summonerName'], region=match['region']).load() participant['summonerId'] = summoner.id participant['currentAccountId'] = summoner.account_id participant['accountId'] = summoner.account_id partial_renew_count += 1 except datapipelines.common.NotFoundError: # Summoner changed their name and so our IDs will be incorrect, oh # well... print( f'Summoner "{participant["summonerName"]}" changed names.' ) partial_renew_failures += 1 self.db.temp_matches.insert_one(match) match_cursor.close() print(f'White: {already_updated_count}, green: {full_renew_count}, ' f'yellow: {partial_renew_count}, red: {partial_renew_failures}') # -- PART 2 --- self.db.matches.rename('old_matches') self.db.summoners.rename('old_summoners') self.db.temp_matches.rename('matches') self.db.temp_summoners.rename('summoners') print('Don\'t forget to manually update the collection indices!')
def test_ranks(self): s = cassiopeia.Summoner(name=SUMMONER_NAME) ranks = s.ranks for key in ranks: self.assertIsInstance(key, cassiopeia.Queue) self.assertIsInstance(ranks[key], cassiopeia.data.Rank)
async def wotw(send_award): win_string = '' scores = {} for row in c.execute('SELECT * FROM league'): print(row[3].encode('utf-8')) summ_id = json.loads(row[3])['id'] summoner = cass.Summoner(id=summ_id) history = summoner.match_history(begin_time=last_week, queues=[ 'NORMAL_5V5_BLIND_PICK', 'RANKED_FLEX_SR', 'RANKED_SOLO_5x5', 'TEAM_BUILDER_DRAFT_UNRANKED_5x5' ]) games_played = len(history) if games_played <= 0: continue if row[1] in scores: scores[row[1]]['count'] += games_played else: scores[row[1]] = {} scores[row[1]]['count'] = games_played scores[row[1]]['agold'] = [] scores[row[1]]['adamage'] = [] scores[row[1]]['acs'] = [] scores[row[1]]['akills'] = [] scores[row[1]]['aassists'] = [] scores[row[1]]['adeaths'] = [] scores[row[1]]['avision'] = [] # gold = [] # damage = [] # cs = [] # kills = [] # assists = [] # deaths = [] for match in history: minutes = 0 duration = str(match.duration).split(':') minutes += int(duration[0]) * 60 minutes += int(duration[1]) minutes += round(int(duration[2]) / 60) # print(minutes) # print(match.queue) if minutes <= 10: scores[row[1]]['count'] += -1 continue for p in match.participants: if p.summoner.account_id == "0": continue if p.summoner == summoner: scores[row[1]]['agold'].append(p.stats.gold_earned) scores[row[1]]['adamage'].append( p.stats.total_damage_dealt_to_champions) scores[row[1]]['acs'].append(p.stats.total_minions_killed) scores[row[1]]['akills'].append(p.stats.kills) scores[row[1]]['aassists'].append(p.stats.assists) scores[row[1]]['adeaths'].append(p.stats.deaths) scores[row[1]]['avision'].append(p.stats.vision_score) # scores[row[1]]['agold'].append(listAvg(gold,False)) # scores[row[1]]['adamage'].append(listAvg(damage,False)) # scores[row[1]]['acs'].append(listAvg(cs,False)) # scores[row[1]]['akills'].append(listAvg(kills,False)) # scores[row[1]]['aassists'].append(listAvg(assists,False)) # scores[row[1]]['adeaths'].append(listAvg(deaths,False)) # TODO: Average scores from summoners per person, then detirmine winners then build and send the win_string for user in scores: scores[user]['agold'] = listAvg(scores[user]['agold'], True) scores[user]['adamage'] = listAvg(scores[user]['adamage'], True) scores[user]['acs'] = listAvg(scores[user]['acs'], True) scores[user]['akills'] = listAvg(scores[user]['akills'], True) scores[user]['aassists'] = listAvg(scores[user]['aassists'], True) scores[user]['adeaths'] = listAvg(scores[user]['adeaths'], True) scores[user]['avision'] = listAvg(scores[user]['avision'], True) top_gold = [0, 0] top_damage = [0, 0] top_cs = [0, 0] top_kills = [0, 0] top_assists = [0, 0] top_deaths = [0, 0] top_vision = [0, 0] for user in scores: if scores[user]['count'] < 4: continue if scores[user]['agold'] > top_gold[0]: top_gold[0] = scores[user]['agold'] top_gold[1] = user if scores[user]['adamage'] > top_damage[0]: top_damage[0] = scores[user]['adamage'] top_damage[1] = user if scores[user]['acs'] > top_cs[0]: top_cs[0] = scores[user]['acs'] top_cs[1] = user if scores[user]['akills'] > top_kills[0]: top_kills[0] = scores[user]['akills'] top_kills[1] = user if scores[user]['aassists'] > top_assists[0]: top_assists[0] = scores[user]['aassists'] top_assists[1] = user if scores[user]['adeaths'] > top_deaths[0]: top_deaths[0] = scores[user]['adeaths'] top_deaths[1] = user if scores[user]['avision'] > top_vision[0]: top_vision[0] = scores[user]['avision'] top_vision[1] = user win_string = "**This weeks winners are in!**\n\n"\ "First up comes the midas award, smelted by <@{gold_user}>! On average they snatched {adj1} **{gold_top}** gold per game!\n\n"\ "Next we have the bruiser award, smashed by <@{damage_user}>! On average they dished out {adj2} **{damage_top}** damage each match!\n\n"\ "Third is the humble farmer, reaped by <@{cs_user}>! On average they harvested {adj3} **{cs_top}** minions per game!\n\n"\ "Next award is the serial killer, slaughtered by <@{kills_user}>! On average they murdered {adj4} **{kills_top}** champions in cold blood!\n\n"\ "The accomplice is the next award, slurped by <@{assists_user}>! On average they claimed {adj5} **{assists_top}** assists per game!\n\n"\ "Next we have the omnipotent award, sighted by <@{vision_user}>! On average they had {adj6} **{vision_top}** vision score per match!\n\n"\ "Finally, we have the feeder of the week. Inted by <@{deaths_user}>. On average they fed {adj7} **{deaths_top}** deaths per game. Shame them.".format(gold_user=top_gold[1], gold_top=top_gold[0], damage_user=top_damage[1], damage_top=top_damage[0], cs_user=top_cs[1], cs_top=top_cs[0], kills_user=top_kills[1], kills_top=top_kills[0], assists_user=top_assists[1], assists_top=top_assists[0], deaths_user=top_deaths[1], deaths_top=top_deaths[0], vision_user=top_vision[1], vision_top=top_vision[0], adj1=randomAdjective(),adj2=randomAdjective(),adj3=randomAdjective(),adj4=randomAdjective(),adj5=randomAdjective(),adj6=randomAdjective(),adj7=randomAdjective()) if send_award: channel = client.get_channel(int(config['league']['channel'])) await channel.send(win_string) else: print("Recieved command argument. Not sending discord message.") print(win_string) print(scores)
def _run_impl(self, args): if len(args) < 1 or len(args) > 2: return self.print_invalid_usage() summoner_name = args[0] n = 50 if len(args) == 2: n = int(args[1]) try: summoner = cass.Summoner(name=summoner_name).load() except datapipelines.common.NotFoundError: print(f'Summoner "{summoner_name}" not found.') return counts = collections.defaultdict(lambda: collections.defaultdict(int)) pipeline = self.match_filtering_flags.filter_steps() + [ {'$match': {'participants.accountId': summoner.account_id}}, ] # yapf: disable for match in self.db.matches.aggregate(pipeline): for participant in match['participants']: if participant['accountId'] == summoner.account_id: team = participant['side'] break for participant in match['participants']: if participant['accountId'] == '0': # BOT account continue if not counts[participant['accountId']]['name']: counts[participant['accountId']]['name'] = set( [participant['summonerName']]) elif self.flag('list_name_changes'): counts[participant['accountId']]['name'].add( participant['summonerName']) pass counts[participant['accountId']]['games_played'] += 1 same_team = team == participant['side'] counts[participant['accountId']]['same_team'] += int(same_team) if same_team: counts[participant['accountId']]['wins_with'] += int( participant['stats']['win']) else: counts[participant['accountId']]['wins_against'] += int( not participant['stats']['win']) table = [] for stats in counts.values(): if stats['same_team'] > 0: win_rate_with = float(stats['wins_with']) / stats['same_team'] wins_with = f'{stats["wins_with"]} / {stats["same_team"]} ({100 * win_rate_with:.3f})' else: wins_with = '-' if stats['same_team'] != stats['games_played']: win_rate_against = float(stats['wins_against']) / ( stats['games_played'] - stats['same_team']) wins_against = f'{stats["wins_against"]} / {stats["games_played"] - stats["same_team"]} ({100 * win_rate_against:.3f})' else: wins_against = '-' table.append( collections.OrderedDict([ ('Summoner', ','.join(stats['name'])), ('Games Played', stats['games_played']), ('Wins With', wins_with), ('Wins Against', wins_against), ])) table.sort(key=lambda i: i['Games Played']) table = table[-n:] table.reverse() self.table_output_flags.output_table(table)