def index(): s = Summoner() data = s.grab_profile() rg_data = s.grab_recent_games(data['gravelordnito']['id']) m_data = s.grab_masteries(data['gravelordnito']['id']) r_data = s.grab_runes(data['gravelordnito']['id']) return render_template('index.html', data=[data, m_data, r_data, rg_data])
def test_summoner_won_match(self): test_sum_1 = Summoner( sum_id='b4GC5iDhDIQzR05I_FWcsqXLI398w_fpEXuyfEnY3jjBkcE', offline=True) self.assertTrue(util.summoner_won_match(test_sum_1, test_match)) test_sum_2 = Summoner( sum_id='5XsnqsNCkNphk3nSWU3MfthVWDlL5cKEZUzjL8nUmTPOyQw', offline=True) self.assertFalse(util.summoner_won_match(test_sum_2, test_match))
def test_participant_id_for_summoner_in_match(self): test_sum_1 = Summoner( sum_id='KQz-bIZbhbAePHwBIv1YWSiObUmQ7-3VFeAvdzluh2_OiAY', offline=True) self.assertTrue( util.participant_id_for_summoner_in_match(test_sum_1, test_match)) test_sum_2 = Summoner( sum_id='cZblwBWSNBQJyXmIyrvuHIhToxB7Zx92-8bmEOQbH_4emuc', offline=True) self.assertTrue( util.participant_id_for_summoner_in_match(test_sum_2, test_match))
def pullEntireTier(url): res = requests.get(url) res = res.json() tier = res['tier'] league_name = res['name'] summoners = res['entries'] sums = [] for summoner in summoners: s = Summoner(summoner) s.tier = tier s.league_name = league_name sums.append(s) s.printAll()
def test_participant_by_summoner_in_match(self): test_sum = Summoner( sum_id='MnQWQZHlXGaaDHR28XJe0aT5VO9wOuLmgLRl6-bLzGvToWQ', offline=True) test_participant = util.participant_by_summoner_in_match( test_sum, test_match) self.assertEqual(test_participant['participantId'], 4)
def get_top_positions(): all_roles = {'top': 0, 'jg': 0, 'mid': 0, 'bot': 0, 'sup': 0} challengers = queries.get_challengers() for c in challengers['entries']: # Take last 20 matches, skipping over naming issues summoner = Summoner(sum_id=c['summonerId']) matches = queries.get_matches(summoner, endIndex=20)['matches'] roles = {'top': 0, 'jg': 0, 'mid': 0, 'bot': 0, 'sup': 0} for m in matches: if m['lane'] == 'TOP': roles['top'] += 1 elif m['lane'] == 'JUNGLE': roles['jg'] += 1 elif m['lane'] == 'MID': roles['mid'] += 1 elif m['role'] == 'DUO_CARRY' or (m['lane'] == 'BOTTOM' and m['lane'] == 'SOLO'): roles['bot'] += 1 elif m['role'] == 'DUO_SUPPORT': roles['sup'] += 1 best_role = None best_count = 0 for r in roles.keys(): if roles[r] > best_count: best_count = roles[r] best_role = r all_roles[best_role] += 1 return all_roles
def get(self): self.response.write(fronthtml) self.response.write(htmltools.getContentTitle("<h2>패작러 목록</h2>")) self.response.write( htmltools.getContent( "<h3>2018.5.31 수정</h3><p>현재 패작도감은 관리가 되지 않는 상태이며, 등재된 패작러 중 상당수는 삭제 또는 닉변된 계정 혹은 패작유저 여부가 논란에 있습니다.</p><br>" )) self.response.write('<div class="ContentText"><ul>') summonerdata = memcache.get("summonerdata") if not summonerdata: dic = OrderedDict() summoners = Summoner.query().order( Summoner.SummonerName).fetch(keys_only=True) for k in summoners: info = k.get() dic[info.SummonerName] = info.SummonerID memcache.add("summonerdata", dic) for key, value in dic.iteritems(): self.response.write( '<li><a href="../summoner?SummonerID=%s">%s</a></li>' % (value, key)) else: for key, value in summonerdata.iteritems(): self.response.write( '<li><a href="../summoner?SummonerID=%s">%s</a></li>' % (value, key)) self.response.write('</ul></div>') self.response.write(htmltools.getFooter())
def post(self): id = self.request.get("SummonerID") comment = self.request.get("comment") if not id or not comment: self.redirect("../db") comment = comment.replace("<", "") mode = "enable" if mode == "disable": self.response.write( "<script>alert('일시적으로 해당 기능을 비활성화했습니다.');document.location.href='/summoner?SummonerID=%s';</script>" % (id)) else: query = Summoner.query(Summoner.SummonerID == int(id)).get() if query: if query.UserComments: txt = query.UserComments + comment + "\n" query.UserComments = txt else: query.UserComments = (comment + "\n") query.put() self.response.write( "<script>alert('추가했습니다.');document.location.href='/summoner?SummonerID=%s';</script>" % (id)) else: self.redirect("../db")
def loadSummonerData(): SUMMONER_DATA.clear() try: with open(DATA_FILE, "r") as input_file: json_data = input_file.read() parsed = json.loads(json_data) for name in parsed: SUMMONER_DATA[name.lower()] = Summoner.fromJson(parsed[name]) except FileNotFoundError: logging.info(f"Could not find file {DATA_FILE}") return None return SUMMONER_DATA
def get(self): summonerdata = memcache.get("summonerdata") dic = OrderedDict() summoners = Summoner.query().order( Summoner.SummonerName).fetch(keys_only=True) for k in summoners: info = k.get() dic[info.SummonerName] = info.SummonerID if not summonerdata: memcache.add("summonerdata", dic) else: memcache.set("summonerdata", dic) self.response.write("200")
def scrape( name, region='na' ): url = f"https://lol.mobalytics.gg/summoner/{region}/{name}?game-types=2&season=13" d = pq(url=url) divs = d('div') champs_infos = [ pq(div).find('p').text() for div in divs if pq(div).attr('class') and "champions-statisticstyles__ChampionInfoRow" in pq(div).attr('class') ] lp = [ pq(div).text() for div in divs if pq(div).attr('class') and "profilestyles__LP" in pq(div).attr('class') ] win_rate = [ pq(div).text() for div in divs if pq(div).attr('class') and "profilestyles__WinRate" in pq(div).attr('class') ] game_types = [ pq(div).text() for div in divs if pq(div).attr('class') and "profilestyles__TierInfoGameType" in pq(div).attr('class') ] spans = d('span') wins = [ pq(span).text() for span in spans if pq(span).attr('class') and "profilestyles__Wins" in pq(span).attr('class') ] losses = [ pq(span).text() for span in spans if pq(span).attr('class') and "profilestyles__Losses" in pq(span).attr('class') ] ps = d('p') ranks = [ pq(p).text() for p in ps if pq(p).attr('class') and "profilestyles__TierInfoLabel" in pq(p).attr('class') ] summoner = Summoner( name ) stats = zip( game_types, ranks, wins, losses, win_rate ) summoner.set_from_tup( stats ) return summoner
def refreshSummonerData(): SUMMONER_DATA.clear() logging.info("Refreshing Summoner Profile Data") for name in settings.SUMMONER_NAMES: url = api_calls.BASE_API_URL + api_calls.SUMMONER_API_URL.format( summonerName=name) response = api_calls.call_api(url) if response is None or response.status_code != 200: logging.info(f"Failed to obtain data for {name}") logging.info(f"Response Code: {response.status_code}") continue SUMMONER_DATA[name.lower()] = Summoner() SUMMONER_DATA[name.lower()].SummonerDTO = response.json() logging.info("Completed Refreshing Summoner Profile Data") saveSummonerData() logging.info(f"Dumped json output to {DATA_FILE}") return SUMMONER_DATA
def get_summoner(name, region): global api name = escape(session["name"]) region = escape(session["region"]) if (region != "NA"): api = APICalls(region) #print("API: " , api) name_l = len(name) summoner_data = Summoner(name, region, api) if (summoner_data.account_exists): match_history = summoner_data.get_match_history() p_icon = summoner_data.get_profile_icon() #print(match_history) if (match_history is None): return render_template("user.html", name=name, lvl=summoner_data.get_lvl(), region=region, profile_icon=p_icon) #print(match_history) league_data = summoner_data.get_league_rank() return render_template("user.html", name=name, lvl=summoner_data.get_lvl(), region=region, profile_icon=p_icon, matches=match_history, league=league_data) """ match_history = MatchHistory(region, name, api) matches = match_history.get_matches(30) if(matches is None): return render_template("user.html") elif(matches == "Empty"): return render_template("user.html", name=name, lvl=match_history.lvl, region=region, profile_icon=match_history.get_summoner_icon()) else: #print(matches.match_data()) champ_icon = match_history.get_champ_icon() #print(champ_icon) return render_template("user.html", name=name, lvl=match_history.lvl, region=region, matches=matches, icon=champ_icon, profile_icon=match_history.get_summoner_icon()) """ return render_template("user.html")
def __init__(self, server, summoner_name_list, begin_time): self.server = server self.summoner_list = [ Summoner(server, summoner_name_list[i], begin_time) for i in range(len(summoner_name_list)) ] self.num_games = 0 self.total_time = 0 self.modes = { 400: Mode('Normal Draft'), 420: Mode('Ranked Solo/Duo'), 430: Mode('Normal Blind'), 440: Mode('Ranked Flex'), 450: Mode('ARAM'), 700: Mode('Clash'), 900: Mode('URF'), 1020: Mode('One For All'), 1300: Mode('Nexus Blitz') } self.played_with = {} self.played_with_list = []
def putSummonersInDB(): # Get the top n players numPlayers = 1000 topPlayers = getTopPlayers(numPlayers) # Get summoners by requesting Riot API count = 1 summoners = [] for player in topPlayers: try: summoner = Summoner(player['summonerName']) except: continue summoners.append(summoner) print(f'Summoners: {count}/{len(topPlayers)}') count += 1 # Connect to the MongoDB database load_dotenv() mongoUsername = os.getenv('MONGO_USERNAME') mongoPassword = os.getenv('MONGO_PASSWORD') mongoConnect = f'mongodb+srv://{mongoUsername}:{mongoPassword}@cluster0-vmp4h.mongodb.net/test?retryWrites=true&w=majority' client = pymongo.MongoClient(mongoConnect) db = client['summoner_db'] oldCollection = db['summoners'] oldCollection.drop() collection = db['summoners'] # Put summoners in database for summoner in summoners: summonerName = summoner.accountInfo['name'] summonerCollection = { '_id': summonerName, 'accountInfo': summoner.accountInfo, 'matchIdList': summoner.matchIdList, 'matchInfoList': summoner.matchInfoList, 'unitsAndTraitsList': summoner.unitsAndTraitsList } summonerInsertion = collection.insert_one(summonerCollection)
def post(self): query = self.request.get("query") if not query: self.redirect("../") if query == "Hide on bush": self.response.write( "<script>alert('소환사 이름: %s\\n 모든 인간들을 패작하고 있습니다');document.location.href='/';</script>" % ( query)) else: indb = "등재안됨" incdb = "등재안됨" cdbhits = 0 summonerdata = memcache.get("summonerdata") result = None output = "소환사 이름: %s\\n 도감 등재여부:%s\\n커뮤니티 도감 등재여부: %s\\n커뮤니티 도감 등재 횟수: %d" if not summonerdata: dic = OrderedDict() summoners = Summoner.query().order(Summoner.SummonerName).fetch(keys_only=True) for k in summoners: info = k.get() dic[info.SummonerName] = info.SummonerID if info.SummonerName == query.encode(): result = info.SummonerID memcache.add("summonerdata", dic) if result: indb = "등재됨" else: for key, val in summonerdata.iteritems(): if key == query.encode(): result = val if result: indb = "등재됨" commq = CommunitySummoner.query(CommunitySummoner.SummonerName == query.encode()).fetch() if commq: incdb = "등재됨" commq = commq[0] cdbhits = commq.SummonerHits self.response.write( '<script>alert("%s");document.location.href="/";</script>' % ( output%(query.encode(), indb, incdb, cdbhits)))
def getSummonerDataFromDB(): load_dotenv() mongoUsername = os.getenv('MONGO_USERNAME') mongoPassword = os.getenv('MONGO_PASSWORD') mongoConnect = f'mongodb+srv://{mongoUsername}:{mongoPassword}@cluster0-vmp4h.mongodb.net/test?retryWrites=true&w=majority' client = pymongo.MongoClient(mongoConnect) db = client['summoner_db'] collection = db['summoners'] # Get summoners using database summoners = [] cursor = collection.find({}) for document in cursor: accountInfo = document['accountInfo'] matchIdList = document['matchIdList'] matchInfoList = document['matchInfoList'] unitsAndTraitsList = document['unitsAndTraitsList'] summoner = Summoner(None, accountInfo, matchIdList, matchInfoList, unitsAndTraitsList) summoners.append(summoner) return summoners
def getInfoSummoner(name): try: summ = Summoner() summ.name = name k = utils.getKey() id, level = getSummonerInfoByName(name, k) if id != None and level != None: # print(f"Id recuperado: {id}") summ.id = id summ.level = level #Obtener los champs con puntos de maestría. summ.champions = getChampsMastery(summ.id, k) # print(summ.champions) mostMastery = summ.champions[0] recordChamp = processChampRecord(mostMastery) if recordChamp != None: summ.mostMasteryChamp = recordChamp with open(f"test_{name}.json", "w") as f: f.write(str(summ)) resume = f"[+]Name: {summ.name}\n\tLevel: {summ.level}\n\tchamp with mastery: {len(summ.champions)}.\n[+]Champ with most mastery:\n\tName: {summ.mostMasteryChamp['name']}\n\tLevel: {summ.mostMasteryChamp['level']}" resume += f"\n\tPoints: {summ.mostMasteryChamp['points']}\n\tChest?: {summ.mostMasteryChamp['chest']}\n\tLast time played: {summ.mostMasteryChamp['lastTimePlayed']}" resume += "\n\t[+]Info extra:" resume += f"\n\t\tTitle: {summ.mostMasteryChamp['infoExtra']['title']}\n\t\tBlurb: {summ.mostMasteryChamp['infoExtra']['blurb']}\n\t\tTags: {summ.mostMasteryChamp['infoExtra']['tags']}" resume += f"\n\t\tPartype: {summ.mostMasteryChamp['infoExtra']['partype']}\n\t\tStats: {summ.mostMasteryChamp['infoExtra']['stats']}" print(resume) with open(f"test_{name}.txt", "w") as f: f.write(resume) print("Information Saved!") print("File: " + f"test_{name}.txt") else: print("Something went wrong getting the data.") except Exception as ex: print(f"Except: {ex}")
def main(): print(stats.get_botlane_stats(Summoner(name="who what")))
from challengerList import ChallengerList from match import Match from summoner import Summoner #do this for all supported regions regions = ['na', 'euw', 'kr'] for region in regions: #update list of challengers players = ChallengerList(region) challengers = players.getChallengers() #update list of challenger matchlists for challenger in challengers['entries']: player = Summoner(challenger['playerOrTeamId'], region) matchlist = player.getMatches() matchIDs = matchlist.getMatchIds() localMatches = [] for matchID in matchIDs: if matchID not in localMatches: match = Match(matchID, region) items = match.getParticipantById( player.getID()).getStats('items') print(items) #use breaks here to execute requests only once, otherwise dev key rate limit is maxed out QUICKLY break break break
from rifters import leagues from summ_data import scrape from summoner import Summoner me = "jiangpro" peers_jk = leagues( me, 'NA' ) summoners = [] start = time.perf_counter_ns() for pj in peers_jk: summ = scrape( pj ) summoners.append( summ ) end = time.perf_counter_ns() elapsed_secs = (end - start) / 1000000000 print( f"Collecting took {str(elapsed_secs)}s" ) filtered_summs = [ summ.filter() for summ in summoners ] Summoner.sort( filtered_summs, 'win_rates', False ) f = open('silvers.txt', 'w+') start = time.perf_counter() f.writelines( f"{summ}\n" for summ in filtered_summs ) end = time.perf_counter() elapsed_secs = (end - start) / 1000000000 f.close() print( f"Storing took {str(elapsed_secs)}s" )
from challengerList import ChallengerList from match import Match from summoner import Summoner #do this for all supported regions regions = ['na', 'euw', 'kr'] for region in regions: #update list of challengers players = ChallengerList(region) challengers = players.getChallengers() #update list of challenger matchlists for challenger in challengers['entries']: player = Summoner(challenger['playerOrTeamId'], region) matchlist = player.getMatches() matchIDs = matchlist.getMatchIds() localMatches = [] for matchID in matchIDs: if matchID not in localMatches: match = Match(matchID, region) items = match.getParticipantById(player.getID()).getStats('items') print(items) #use breaks here to execute requests only once, otherwise dev key rate limit is maxed out QUICKLY break break break
def get(self): if not self.request.get("summonerid"): self.redirect("../db") else: summonerid = self.request.get("summonerid") query = Summoner.query( Summoner.SummonerID == int(summonerid)).get() if query.APIUpdateTime_int: if int(time.time()) - query.APIUpdateTime_int < 180: self.response.write( '<script>alert("최근에 정보를 갱신했습니다");document.location.href="/summoner?SummonerID=%s";</script>' % (summonerid)) if query.RiotID: riotid = query.RiotID apidata = json.loads( urlopen(get_league_info % (riotid, api_key)).read()) tierinfo = " ".join([ apidata[0]["tier"], apidata[0]["rank"], str(apidata[0]["leaguePoints"]) + " LP" ]) totalgames = (apidata[0]["wins"] + apidata[0]["losses"]) winrate = int( float(apidata[0]["wins"]) / float(totalgames) * 100) ctime = int(time.time()) dt = datetime.fromtimestamp(time.mktime(time.localtime())) dt = dt - timedelta(hours=3) friendlytime = "%d:%s:%s" % (dt.hour, str(dt.minute).rjust( 2, "0"), str(dt.second).rjust(2, "0")) query.SummonerTier = tierinfo query.SummonerWinRate = winrate query.SummonerGameInfo = "%d전 %d승 %d패" % ( (apidata[0]["wins"] + apidata[0]["losses"]), apidata[0]["wins"], apidata[0]["losses"]) query.APIUpdateTime = friendlytime query.APIUpdateTime_int = ctime query.put() self.response.write( '<script>alert("정보를 갱신했습니다");document.location.href="/summoner?SummonerID=%s";</script>' % (summonerid)) else: try: riotid = str( json.loads( urlopen(get_riot_id % (quote(query.SummonerName.encode()), api_key)).read())["id"]) if not riotid: self.response.write( '<script>alert("정보를 갱신할수 없습니다(해당 소환사가 존재하지 않습니다)");document.location.href="/summoner?SummonerID=%s";</script>' % (summonerid)) except: self.response.write( '<script>alert("정보를 갱신할수 없습니다(해당 소환사가 존재하지 않습니다)");document.location.href="/summoner?SummonerID=%s";</script>' % (summonerid)) else: apidata = json.loads( urlopen(get_league_info % (riotid, api_key)).read()) tierinfo = " ".join([ apidata[0]["tier"], apidata[0]["rank"], str(apidata[0]["leaguePoints"]) + " LP" ]) totalgames = (apidata[0]["wins"] + apidata[0]["losses"]) winrate = int( float(apidata[0]["wins"]) / float(totalgames) * 100) ctime = int(time.time()) dt = datetime.fromtimestamp(time.mktime(time.localtime())) dt = dt - timedelta(hours=3) friendlytime = "%d:%s:%s" % (dt.hour, str(dt.minute).rjust( 2, "0"), str(dt.second).rjust(2, "0")) query.SummonerTier = tierinfo query.SummonerWinRate = winrate query.SummonerGameInfo = "%d전 %d승 %d패" % ( (apidata[0]["wins"] + apidata[0]["losses"]), apidata[0]["wins"], apidata[0]["losses"]) query.APIUpdateTime = friendlytime query.APIUpdateTime_int = ctime query.put() self.response.write( '<script>alert("정보를 갱신했습니다");document.location.href="/summoner?SummonerID=%s";</script>' % (summonerid))
Thread(target=get_summs, args=[batch, DIVISION, TIER, QUEUE]) for batch in range(i, i + NUM_THREADS) ] for thread in threads: thread.start() for thread in threads: thread.join() i += NUM_THREADS end = time.process_time() summoner_objs = [ Summoner.from_json(summ) for summ in summoners if type(summ) != str ] print(f'{len(summoner_objs)} summoners collected in {end-start}s') for summ in summoner_objs: summ['win_rates'] = int( summ['wins']) / (int(summ['wins']) + int(summ['losses'])) summ['games_played'] = int(summ['wins']) + int(summ['losses']) filtered_summs = Summoner.list_filter(summoner_objs, 'games_played', 100) Summoner.sort(filtered_summs, 'win_rates') start = time.process_time() f = open('./data/leaguers.txt', 'w+') f.write(f"{ json.dumps( Summoner.list_json( filtered_summs ), indent=3 ) }\n") f.close()
from summoner import Summoner import os if __name__ == '__main__': airking = Summoner( os.path.expanduser( '~/Desktop/Summoners War Exporter Files/Airking77-23182654.json')) airking.analyze_grinds() #airking.print_runes() airking.analyze_reapps(10)
logger.info('Creating new Twilio client') client = Client(account_sid, auth_token) logger.info('Twilio client created successfully') # Gets Riot API Key riot_file = open('Credentials/riot_key.txt', 'r') if riot_file.mode == 'r': logger.debug('Reading riot api key from riot_key.txt') riot_key = riot_file.read() riot_file.close() # Loads player data from json file players_dict = load_player_data() # Checks Zach's matches for new games logger.info('Creating Summoner object for Zach') zach = Summoner('Zach', players_dict, riot_key, client, champion_dict) zach.check_for_new_match() # Checks Jarrod's matches for new games logger.info('Creating Summoner object for Jarrod') jarrod = Summoner('Jarrod', players_dict, riot_key, client, champion_dict) jarrod.check_for_new_match() # Checks Brandon's matches for new games logger.info('Creating Summoner object for Brandon') brandon = Summoner('Brandon', players_dict, riot_key, client, champion_dict) brandon.check_for_new_match() sys.exit()