class pubg_manager: def __init__(self): self.api = PUBG(config['tokens']['pubg'], Shard.STEAM) async def wait_ratelimit(self, reset): sleep_seconds = (reset - datetime.now()).total_seconds() + 1 # 1 sec insurance print(sleep_seconds) if sleep_seconds > 0: return await asyncio.sleep(sleep_seconds) else: return True async def get_players_data(self, player_ids): players_chunks = list(self.chunk(player_ids, 10)) players_output = [] for players_chunk in players_chunks: try: players_output += await self.get_players(players_chunk) except pubg_python.exceptions.RateLimitError as e: await self.wait_ratelimit(e.rl_reset) players_output += await self.get_players(players_chunk) return players_output async def get_players(self, player_ids): try: return self.api.players().filter(player_ids=player_ids) except pubg_python.exceptions.RateLimitError as e: await self.wait_ratelimit(e.rl_reset) return await self.get_players(player_ids) async def get_match(self, match_id): return self.api.matches().get(match_id) async def get_player_id_by_name(self, player_name): try: player = self.api.players().filter(player_names=[player_name])[0] return player.id except IndexError: return -1 except pubg_python.exceptions.NotFoundError: print('NotFoundError') return -1 except pubg_python.exceptions.RateLimitError as e: print('RateLimitError') await self.wait_ratelimit(e.rl_reset) return await self.get_player_id_by_name(player_name) def find_roster_by_name(self, name, rosters): for roster in rosters: for participant in roster.participants: if participant.name == name: return roster def chunk(self, l, n): for i in range(0, len(l), n): yield l[i:i + n]
def test_player(self): api = PUBG(os.environ.get('PUBGapi'), Shard.PC_NA) players = api.players().filter(player_names=['shroud']) for player in players: player_id = player.id player = api.players().get(player_id) self.assertTrue(player.name) self.assertTrue(player.created_at) self.assertTrue(player.shard_id) self.assertTrue(player.title_id) self.assertTrue(player.updated_at)
def search_player(request): shard = request.GET['shard'] player_name = request.GET['player_name'] with open(os.path.join(os.getcwd(), 'token'), 'r') as f: api = PUBG(f.read()[:-1], Shard[shard]) try: players = api.players().filter(player_names=[player_name]) for player in players: player_id = player.id Player.objects.get(player_id=player_id) except NotFoundError: response = "Name error" return HttpResponse(response) except Player.DoesNotExist: p = Player(player_id=player_id, player_name=player_name, shard=shard, count=0) p.save() print('player ' + player_name + ' is registered') return HttpResponseRedirect( reverse('pubg_gyachat:closet', args=(player_id, )))
def gyachat(request, player_id): player = get_object_or_404(Player, pk=player_id) with open(os.path.join(os.getcwd(), 'token'), 'r') as f: api = PUBG(f.read()[:-1], player.get_shard()) api_player = api.players().get(player_id) template = loader.get_template('pubgHackGoso/gyachat.html') context = { 'player_id': player_id, 'api_player': api_player, 'count': player.count, } return HttpResponse(template.render(context, request))
def InitMatchesPerUser(api: PUBG, userList: dict): conn = sqlite3.connect('pubg.db') c = conn.cursor() c.execute("DROP TABLE IF EXISTS matches") c.execute( "CREATE TABLE IF NOT EXISTS matches (match_id varchar(125), username varchar(64))" ) players = api.players().filter(player_names=userList['users']) for player in players: try: for match in player.matches: c.execute("insert into matches values (?, ?)", [match.id, player.name]) conn.commit() print('Adding data for user ' + player.name + ', match ' + match.id) except AttributeError: print('No match found for ' + player.name) # Close db connection conn.close()
from pubg_python import PUBG, Shard import copy from enum import Enum import requests from contextlib import suppress import requests import csv import requests import json import secrets pubg_api = PUBG(secrets.pubg_key, Shard.PSN) username = input("Please specify a username: ") username player_list = [username] players = pubg_api.players().filter(player_names=player_list) try: for player in players: player_name = player.name player_id = player.id print(player_name) print(player) match_count = 0 match_time = 0 vikendi_count = 0 erangel_count = 0 miramar_count = 0 sanhok_count = 0 karakin_count = 0 playerlistitem = []
def main(argv): player_name = '' server = None out_heatmap_file_name = '' match_number = 0 try: opts, args = getopt.getopt( argv, "hp:s:o:m:", ["playername=", "server=", "outputfile=", "match"]) except getopt.GetoptError: print('pubgheatmap.py -p <playername> -s <server> -o <outputfile>') sys.exit(2) for opt, arg in opts: if opt == '-h': print('pubgheatmap.py -p <playername> -s <server> -o <outputfile>') print( 'Allowed servers: pc-as, pc-eu, pc-krjp, pc-na, pc-oc, pc-sa, pc-sea' ) print( 'Example: pubgheatmap.py -p tetraquark -s pc-eu -o heatmap.jpg' ) print('') sys.exit() elif opt in ("-p", "--playername"): player_name = arg elif opt in ("-s", "--server"): server = Shard(arg) elif opt in ("-o", "--outputfile"): out_heatmap_file_name = arg elif opt in ("-m", "--match"): match_number = int(arg) if not player_name or server is None: print('Forgot to enter the player name or server.') print('pubgheatmap.py -p <playername> -s <server> -o <outputfile>') sys.exit(2) print('Trying to get data from PUBG servers.') api = PUBG(API_KEY, server) # get required player players = api.players().filter(player_names=[player_name]) myPlayer = players[0] # get the last player matches mathcesIdList = [match.id for match in myPlayer.matches] # get required match object match = api.matches().get(mathcesIdList[match_number]) print('Done.') print('Trying to build the match heatmap.') # get match heatmap (PIL image file) heatmapImg = getMatchHeatmap(api=api, match=match) print('Done.') # save image to the file if not out_heatmap_file_name: out_heatmap_file_name = mathcesIdList[match_number] + '_heatmap.jpg' heatmapImg.save(out_heatmap_file_name)
# -*- coding: utf-8 -*- from pubg_python import PUBG, Shard with open("emacser.api_key", "r") as api_key_file: api_key = api_key_file.readline().rstrip() api = PUBG(api_key, Shard.PC_KAKAO) players = api.players().filter(player_names=['GNUemacs']) player = players[0] print(player.matches)
def main(): airLineAlpha = 0 airLineBeta = 0 limit = 0 airLineFirstPositionIndex = [] airLineEndPositionIndex = [] tempListFirst = [] tempListEnd = [] #matchedListFirst = [] #matchedListEnd = [] playerMatchList = [] #weakPlayerMatchList = [] matchedAlphaList = [] matchedBetaList = [] matchedMatchIdList = [] playerList = [] print("input player name") name = input() print("input last match (example: 0 is last match, 1 is 2d last match)") matchNumber = input() print() api = PUBG('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJiMGVhNmM0MC1kNGQzLTAxMzYtYmQ3ZC03MzkyZGYzNjZhZTAiLCJpc3MiOiJnYW1lbG9ja2VyIiwiaWF0IjoxNTQzMzY1NDQxLCJwdWIiOiJibHVlaG9sZSIsInRpdGxlIjoicHViZyIsImFwcCI6InlvdXJpNDAxIn0.Z9i2twdF8yDkSPQ2DVjy1jbr7E5PbtiiB9n3UgfyKCg', Shard.STEAM) players = api.players().filter(player_names=[name]) player = players[0] match = api.matches().get(player.matches[int(matchNumber)].id) asset = match.assets[0] telemetry = api.telemetry(asset.url) instance = getMatchInfo(telemetry) if not(match.map_name == "Range_Main"): map = getMapImg(match.map_name) print(match.game_mode) h,w,c = map.shape limit = h/10 print(getMapName(match.map_name)) airLineAlpha,airLineBeta,airLineFirstPositionIndex,airLineEndPositionIndex = instance.getAirPlaneInfo(map) df = pd.read_pickle('pickle/match.pickle') df_exact = df[df['mapName'] == match.map_name] df_exact = df[df['mode'] == match.game_mode] df_airLineFirstPos = df_exact['airLineFirstPos'] df_airLineEndPos = df_exact['airLineEndPos'] df_airLineAlpha = df_exact['airLineAplha'] df_airLineBeta = df_exact['airLineBeta'] df_matchId = df_exact['matchId'] airLineFirstList = df_airLineFirstPos.values.tolist() airLineEndList = df_airLineEndPos.values.tolist() airLineAlphaList = df_airLineAlpha.values.toList() airLineBetaList = df_airLineBeta.values.toList() matchIdList = df_matchId.values.tolist() df_player = getPlayerPickle(match.map_name,match.game_mode) for i in range(len(airLineFirstList)): tempListFirst = airLineFirstList[i].split(',') tempListEnd = airLineEndList[i].split(',') if (abs(int(tempListFirst[0])-airLineFirstPositionIndex[0])+abs(int(tempListFirst[1])-airLineFirstPositionIndex[1])+abs(int(tempListEnd[0])-airLineEndPositionIndex[0])+abs(int(tempListEnd[1])-airLineEndPositionIndex[1])) < limit: #matchedListFirst.append([int(tempListFirst[0]),int(tempListFirst[1])]) #類似AirLine出力用 #matchedListEnd.append([int(tempListEnd[0]),int(tempListEnd[1])]) matchedMatchIdList.append(matchIdList[i]) df_player_exact = df_player[df_player['matchId'].isin(matchedMatchIdList)] df_drop = df_player_exact[df_player_exact['ranking'] != '[]'].copy() castData = df_drop['ranking'].astype(np.int64) df_drop.loc[df_drop['ranking']!='[]','ranking'] = castData df_top10player = df_drop[(df_drop['ranking'] != 0) & (df_drop['ranking'] < 10)] df_weakPlayer = df_drop[(df_drop['ranking'] > 10) | (df_drop['ranking']== 0)] df_top10PlayerLanding = df_top10player['landingPos'] df_weakPlayerLanding = df_weakPlayer['landingPos'] top10PlayerList = df_top10PlayerLanding.values.tolist() weakPlayerList = df_weakPlayerLanding.values.tolist() #playerMatchList.extend(top10PlayerList) #weakPlayerMatchList.extend(weakPlayerList) print('Number of Similar Match',len(matchedMatchIdList)) mpom = matPlotOnMap(map) playerList.extend(weakPlayerList) playerList.extend(top10PlayerList) #map = pom.plotAirLine(airLineFirstPositionIndex,airLineEndPositionIndex,(0,0,0)) #mpom.plotPlayerHeatMap(top10PlayerList,'red',0.1) #mpom.plotPlayerHeatMap(weakPlayerList,'blue',0.04) #mpom.plotAirLine(airLineAlpha,airLineBeta) mpom.makeHeatIndex(weakPlayerList,-1) mpom.makeHeatIndex(top10PlayerList,1) mpom.plotHeatMap() mpom.plotAirLine(airLineAlpha,airLineBeta) mpom.getLandingPositionWinningPercentage(name,telemetry.events_from_type('LogParachuteLanding')) mpom.saveFigure(match.game_mode,getMapName(match.map_name)) print('end') else:print('this match is range map')
class Battlegrounds(): def __init__(self, bot): config = configparser.ConfigParser() config.read('config.ini') defaultConfig = config['DEFAULT'] self.api_key = defaultConfig['api_key'] self.api = PUBG(self.api_key, Shard.PC_NA) self.bot = bot def embedStats(self, match, participant, killer): """Take in player and match objects to be embedded for message""" em = discord.Embed(colour = discord.Colour.orange()) match_datetime = parseDate(match.created_at) em.description = "Created At: {}, {} UTC".format(match_datetime[0], match_datetime[1]) em.description += "\nMatch ID: {}".format(match.id) em.add_field(name='Match Type', value=match.game_mode, inline=True) em.add_field(name='Finishing Place', value=participant.win_place, inline=True) em.add_field(name='Kills', value=participant.kills, inline=True) em.add_field(name='Assists', value=participant.assists, inline=True) em.add_field(name='Headshot Kills', value=participant.headshot_kills, inline=True) em.add_field(name='Walk Distance', value=str(participant.walk_distance) + "m", inline=True) em.add_field(name='Ride Distance', value=str(participant.ride_distance) + "m", inline=True) em.add_field(name='Team Kills', value=participant.team_kills, inline=True) em.add_field(name='Killed by', value=killer, inline=True) return em @commands.command(pass_context=True) async def last(self, ctx, supplied_name=None): """Retrieves the stats of the last game played If no name is provided, the data file will be searched for the user's discord name. Parameters: supplied_name -- the PUBG in game name to search for """ if not supplied_name and not getGameName(ctx.message.author.name): await self.bot.say("No name found. Please use: `{}help last` for usage instructions".format(self.bot.command_prefix)) return pubg_name = getGameName(ctx.message.author.name) if supplied_name: pubg_name = supplied_name search_message = await self.bot.send_message(ctx.message.channel, "Searching...") player = None try: player = self.api.players().filter(player_names=[pubg_name])[0] except Exception: await self.bot.edit_message(search_message, "{} not found".format(pubg_name)) return try: last_match = self.api.matches().get(player.matches[0].id) except Exception: await self.bot.edit_message(search_message, "No recent matches for {}".format(pubg_name)) return asset = last_match.assets[0] telemetry = self.api.telemetry(asset.url) player_kill_events = telemetry.events_from_type('LogPlayerKill') killer = "#unkown" for event in player_kill_events: if event.victim.name == pubg_name: killer = event.killer.name player_found = False for roster in last_match.rosters: for participant in roster.participants: if participant.name == pubg_name: player_found = True em = self.embedStats(last_match, participant, killer) em.title = "Stat's for {}'s last game".format(participant.name) await self.bot.edit_message(search_message, new_content="Game Found", embed=em) break if player_found == False: print ("Player not found") @commands.command(pass_context=True) async def matches(self, ctx, supplied_name=None): """Returns a list of the last 5 matches for a player to choose from. Requires a response from the user. The bot will then find the stats of the selected game. Parameters: supplied-name -- the PUBG in game name to search for """ if not supplied_name and not getGameName(ctx.message.author.name): await self.bot.say("No name found. Please use: `{}help matches` for usage instructions".format(self.bot.command_prefix)) return pubg_name = getGameName(ctx.message.author.name) if supplied_name: pubg_name = supplied_name search_message = await self.bot.send_message(ctx.message.channel, "Searching...") player = None try: player = self.api.players().filter(player_names=[pubg_name])[0] except Exception: await self.bot.edit_message(search_message, "{} not found".format(pubg_name)) return words = "***Most recent matches for {}:***".format(pubg_name) for idx,m in enumerate(player.matches[0:5]): words += "\n{}. ID: {}".format(idx+1, m) await self.bot.edit_message(search_message, words) await self.bot.add_reaction(search_message, '\N{DIGIT ONE}\N{COMBINING ENCLOSING KEYCAP}') await self.bot.add_reaction(search_message, '\N{DIGIT TWO}\N{COMBINING ENCLOSING KEYCAP}') await self.bot.add_reaction(search_message, '\N{DIGIT THREE}\N{COMBINING ENCLOSING KEYCAP}') await self.bot.add_reaction(search_message, '\N{DIGIT FOUR}\N{COMBINING ENCLOSING KEYCAP}') await self.bot.add_reaction(search_message, '\N{DIGIT FIVE}\N{COMBINING ENCLOSING KEYCAP}') re_message = await self.bot.wait_for_reaction(['\N{DIGIT ONE}\N{COMBINING ENCLOSING KEYCAP}', '\N{DIGIT TWO}\N{COMBINING ENCLOSING KEYCAP}', \ '\N{DIGIT THREE}\N{COMBINING ENCLOSING KEYCAP}', '\N{DIGIT FOUR}\N{COMBINING ENCLOSING KEYCAP}', '\N{DIGIT FIVE}\N{COMBINING ENCLOSING KEYCAP}'], \ message=search_message, user=ctx.message.author) if re_message.reaction.emoji == '\N{DIGIT ONE}\N{COMBINING ENCLOSING KEYCAP}': match_index = 0 elif re_message.reaction.emoji == '\N{DIGIT TWO}\N{COMBINING ENCLOSING KEYCAP}': match_index = 1 elif re_message.reaction.emoji == '\N{DIGIT THREE}\N{COMBINING ENCLOSING KEYCAP}': match_index = 2 elif re_message.reaction.emoji == '\N{DIGIT FOUR}\N{COMBINING ENCLOSING KEYCAP}': match_index = 3 elif re_message.reaction.emoji == '\N{DIGIT FIVE}\N{COMBINING ENCLOSING KEYCAP}': match_index = 4 match_message = await self.bot.say("Searching for match {}...".format(player.matches[match_index])) await self.bot.clear_reactions(search_message) try: last_match = self.api.matches().get(player.matches[match_index].id) except Exception: await self.bot.edit_message(match_message, "Match data not available") return asset = last_match.assets[0] telemetry = self.api.telemetry(asset.url) player_kill_events = telemetry.events_from_type('LogPlayerKill') killer = "#unkown" for event in player_kill_events: if event.victim.name == pubg_name: killer = event.killer.name for roster in last_match.rosters: for participant in roster.participants: if participant.name == pubg_name: em = self.embedStats(last_match, participant, killer) em.title = "Stat's for {}'s last game".format(participant.name) await self.bot.edit_message(match_message, new_content="Game Found", embed=em) break
def test_match(self): api = PUBG(os.environ.get('PUBGapi'), Shard.PC_NA) players = api.players().filter(player_names=['shroud']) for player in players: player_id = player.id player = api.players().get(player_id) match = api.matches().get(player.matches[0]) self.assertTrue(match.map) self.assertTrue(match.created_at) self.assertTrue(match.duration) self.assertTrue(match.game_mode) self.assertTrue(match.title_id) self.assertTrue(match.shard_id) # Returns none # self.assertTrue(match.stats) # Returns an empty string # self.assertTrue(match.patch_version) # Returns none # self.assertTrue(match.tags) roster = match.rosters[0] self.assertTrue(roster.shard_id) self.assertTrue(roster.won) self.assertTrue(roster.stats) participant = roster.participants[0] self.assertTrue(participant.shard_id) self.assertTrue(participant.stats) # Returns none # self.assertTrue(participant.actor) # Stats # Minimum 0 according to api self.assertGreaterEqual(participant.dbnos, 0) self.assertGreaterEqual(participant.assists, 0) self.assertGreaterEqual(participant.boosts, 0) self.assertGreaterEqual(participant.damage_dealt, 0) self.assertGreaterEqual(participant.headshot_kills, 0) self.assertGreaterEqual(participant.heals, 0) self.assertGreaterEqual(participant.kills, 0) self.assertGreaterEqual(participant.last_kill_points, 0) self.assertGreaterEqual(participant.last_win_points, 0) self.assertGreaterEqual(participant.longest_kill, 0) self.assertGreaterEqual(participant.most_damage, 0) self.assertGreaterEqual(participant.revives, 0) self.assertGreaterEqual(participant.ride_distance, 0) self.assertGreaterEqual(participant.road_kills, 0) self.assertGreaterEqual(participant.team_kills, 0) self.assertGreaterEqual(participant.vehicle_destroys, 0) self.assertGreaterEqual(participant.weapons_acquired, 0) self.assertGreaterEqual(participant.boosts, 0) self.assertGreaterEqual(participant.damage_dealt, 0) # Between 1 and 100 according to api self.assertTrue(1 <= participant.kill_place <= 100) self.assertTrue(1 <= participant.win_place <= 100) # Between 0 and 99 according to api self.assertTrue(0 <= participant.kill_streaks <= 99) # Should be an number according to api self.assertTrue(type(participant.kill_points_delta) == float) self.assertTrue(type(participant.win_points_delta) == float) self.assertTrue(participant.name) self.assertTrue(participant.player_id) self.assertTrue(participant.time_survived) self.assertTrue(participant.walk_distance) self.assertTrue(participant.death_type)
def test_unauthorized(self): api = PUBG('', Shard.PC_NA) self.assertRaises(UnauthorizedError, api.players().get, '')
"STEAM": Shard.STEAM, "KAKAO": Shard.KAKAO, "XBOX": Shard.XBOX, "PSN": Shard.PSN } if __name__ == "__main__": api = PUBG( input("API KEY : "), SHARDS[input("platform [" + ", ".join(SHARDS.keys()) + "] : ").upper()]) sel = input( "\n[menu]\n1. get random sample matches\n2. get matches by player name\n>>> " ) if sel == "1": sample = api.samples().get() print("===================") for match in sample.matches: print(match.id) print("===================") print("match id list. pick the one you want!") elif sel == "2": players = api.players().filter(player_names=[input("player name : ")]) print("===================") for player in players: for match in player.matches: print(match.id) print("===================") print("match id list. pick the one you want!")
def main(argv): player_name = '' server = None out_heatmap_file_name = '' timed = False match_number = 0 try: opts, args = getopt.getopt(argv,"hp:s:o:m:t",["playername=","server=","outputfile=","match=","timed"]) except getopt.GetoptError: print('pubgheatmap.py -p <playername> -s <server> [-t] [-o <outputfile>]') sys.exit(2) for opt, arg in opts: if opt == '-h': print('pubgheatmap.py -p <playername> -s <server> [-t/--timed] [-o <outputfile>]') print('Allowed servers: pc-as, pc-eu, pc-krjp, pc-na, pc-oc, pc-sa, pc-sea') print('Example of a static match heatmap: pubgheatmap.py -p tetraquark -s pc-eu -o heatmap.jpg') print('Example of a temporal heatmap: pubgheatmap.py -p tetraquark -s pc-eu -t') print('In temporal heatmap frame, you can use the left or right arrow keys to rewind.') print('') sys.exit() elif opt in ("-p", "--playername"): player_name = arg elif opt in ("-s", "--server"): server = Shard(arg) elif opt in ("-o", "--outputfile"): out_heatmap_file_name = arg elif opt in ("-m", "--match"): match_number = int(arg) elif opt in ("-t", "--timed"): timed = True if not player_name or server is None: print('Forgot to enter the player name or server.') print('pubgheatmap.py -p <playername> -s <server> -o <outputfile>') sys.exit(2) print('Trying to get data from PUBG servers.') api = PUBG(API_KEY, server) # get required player players = api.players().filter(player_names=[player_name]) myPlayer = players[0] # get the last player matches mathcesIdList = [match.id for match in myPlayer.matches] # get required match object match = api.matches().get(mathcesIdList[match_number]) print('Done.') if not timed: print('Trying to build the match heatmap.') # get match heatmap (PIL image file) heatmapImg = getMatchHeatmap(api=api, match=match) # save image to the file if not out_heatmap_file_name: out_heatmap_file_name = mathcesIdList[match_number] + '_heatmap.jpg' print('Heatmap built. Saving to file', out_heatmap_file_name) heatmapImg.save(out_heatmap_file_name) print('Done.') else: print('Trying to build the match heatmaps.') # get match heatmaps heatmapImgs = getMatchTimedHeatmap(api=api, match=match) root = tk.Tk() root.title("pubgheatmap - temporal hitmap") heatmapsPhotoImgsList = [] final_img_size = root.winfo_screenheight() - 20 # 20px for slider if heatmapImgs[0][1].size[0] > final_img_size or heatmapImgs[0][1].size[1] > final_img_size: for time, heatmapImg in heatmapImgs: heatmapsPhotoImgsList.append(ImageTk.PhotoImage( heatmapImg.resize((final_img_size, final_img_size), Image.ANTIALIAS))) else: for time, heatmapImg in heatmapImgs: heatmapsPhotoImgsList.append(ImageTk.PhotoImage(heatmapImg)) # Launching an image gallery with a slider sliderGalleryFrame = SliderGalleryFrame(root, heatmapsPhotoImgsList, final_img_size) sliderGalleryFrame.mainloop() print('Done.')
class pubgData(): def __init__(self, name): self.name = name self.api = PUBG(api_token, Shard.PC_NA) # Player Data: self.playerMatchDetail = self._getMatchDetail( (self.api.players().filter(player_names=[self.name])[0]).matches) self.playerDF = self._getDF(self.playerMatchDetail) def f(self, x): return self.api.matches().get(x.id) def _getMatchDetail(self, lofMatchID): with mp.Pool(processes=mp.cpu_count()) as pool: answer = pool.map(self.f, lofMatchID) pool.close() return answer def g(self, x): answer = { 'matchID': None, 'createdAt': None, 'mapName': None, 'name': None, 'gameMode': None, 'duration': None, 'rank': None, 'kills': None, 'longestKill': None, 'headshotKills': None, 'assists': None, 'damageDealt': None, 'timeSurvived': None, 'timeSurvivedMIN': None, 'endedAt': None, 'date': None, 'enemy': None, 'ally': None } answer['matchID'] = x.id answer['createdAt'] = datetime.strptime(x.attributes['createdAt'], "%Y-%m-%dT%H:%M:%SZ") tempName = x.attributes['mapName'] if tempName == 'Erangel_Main': answer['mapName'] = 'Erangel' elif tempName == 'Desert_Main': answer['mapName'] = 'Miramar' elif tempName == 'Savage_Main': answer['mapName'] = 'Sanhok' elif tempName == 'Range_Main': answer['mapName'] = 'Practice' elif tempName == 'DihorOtok_Main': answer['mapName'] = 'Vikendi' else: answer['mapName'] = 'Unknown' answer['gameMode'] = x.attributes['gameMode'] answer['duration'] = x.attributes['duration'] enemy = [] for roster in x.rosters: temp_team = [] for participant in roster.participants: temp_team.append(participant.name) if participant.name == self.name: answer['name'] = participant.name answer['rank'] = roster.attributes['stats']['rank'] answer['kills'] = participant.attributes['stats']['kills'] answer['longestKill'] = participant.attributes['stats'][ 'longestKill'] answer['headshotKills'] = participant.attributes['stats'][ 'headshotKills'] answer['assists'] = participant.attributes['stats'][ 'assists'] answer['damageDealt'] = participant.attributes['stats'][ 'damageDealt'] answer['timeSurvived'] = participant.attributes['stats'][ 'timeSurvived'] answer['timeSurvivedMIN'] = float( format(Decimal(answer['timeSurvived'] / 60), '.2f')) answer['endedAt'] = answer['createdAt'] + timedelta( seconds=answer['timeSurvived']) answer['date'] = str( answer['createdAt'].month) + "-" + str( answer['createdAt'].day) if self.name in temp_team: answer['ally'] = temp_team else: enemy += temp_team answer['enemy'] = enemy return answer def _getDF(self, matchDetails): with mp.Pool(processes=mp.cpu_count()) as pool: answer = pool.map(self.g, matchDetails) pool.close() return pd.DataFrame(answer) def _filterBy(self, df, type): game = {} for element in set(df[type]): game[element] = len(df[df[type] == element]) return game def _getPIE(self, df): return [['gmaeMode', 'Number of Games'] ] + [[k, v] for k, v in self._filterBy(df, 'gameMode').items()] def _getBAR(self, df): return [['mapName', 'Count'] ] + [[k, v] for k, v in self._filterBy(df, 'mapName').items()] def _getSCATTER(self, df): return [['timeSurvived', 'kills']] + df[['timeSurvivedMIN', 'kills' ]].values.tolist() def _getLINE(self, df): df = df[df['gameMode'] != 'practice'] data = [['Date', 'kills_assists', 'damageDealt', 'headshotKills']] split = df.groupby(df['date']) for each in split: temp = [] temp.append(each[0]) temp.append( sum(list(each[1].kills + each[1].assists)) / len(each[1])) temp.append((sum(list(each[1].damageDealt)) / len(each[1])) / 100) # headshotKills if sum(list(each[1].headshotKills)) == 0: temp.append(0) elif sum(list(each[1].kills)) == 0: temp.append(10) else: temp.append((sum(list(each[1].headshotKills)) / sum(list(each[1].kills))) * 10) data.append(temp) return data def _getGANTT(self, df): data = list( df.apply(lambda row: [ row.date, row.createdAt.hour, row.createdAt.minute, row.endedAt .hour, row.endedAt.minute ], axis=1)) data = data[::-1] for i in range(len(data)): if data[i][1] > data[i][3]: data[i] = [data[i][0], data[i][1], data[i][2], data[i][1], 59] return data def _getSNIPE(self, df): test = df[(df['gameMode'] == 'solo') | (df['gameMode'] == 'duo') | (df['gameMode'] == 'squad') | (df['gameMode'] == 'solo-fpp') | (df['gameMode'] == 'duo-fpp') | (df['gameMode'] == 'squad-fpp')] dicTotal = {} for index, row in test.iterrows(): for single in row.enemy: if single in dicTotal: dicTotal[single] += [index] else: dicTotal[single] = [index] dicTotal = {k: v for (k, v) in dicTotal.items() if len(v) >= 3} temp = {} for k, v in dicTotal.items(): count = 0 for i in range(1, len(v)): if v[i] - v[i - 1] <= 2: count += 1 if count >= 2: temp[k] = v dicTotal = temp data = [['Player Name', 'List of Match Date']] for k, v in dicTotal.items(): data.append([k, [str(df.iloc[x].createdAt) for x in v][::-1]]) return data
jogs.append(jogadores[i]) i+=1 if len(jogadores)-i<5: posFinalConjunto5Array1 = i jogadoresSeparados.append(jogs) cont+=1 jogs = [] while posFinalConjunto5Array1 < len(jogadores): jogs = jogadores [posFinalConjunto5Array1] posFinalConjunto5Array1+=1 playersColetados = 0 for jogadores in jogadoresSeparados: try: players = api.players().filter(player_names=jogadores) for player in players: playersColetados+=1 print(str(playersColetados)+" - Coletando dados de "+player.name) idsMatches = [match["id"] for match in player.relationships["matches"]["data"]] matches = [] for idMatch in idsMatches: match = api.matches().get(idMatch) rosters = match.rosters for roster in rosters: for participant in roster.participants: if participant.name == player.name: kills = participant.kills winPlace = participant.attributes["stats"]["winPlace"]