예제 #1
0
파일: pubg.py 프로젝트: krmoffett/PLUNK
 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
예제 #2
0
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, )))
예제 #3
0
    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)
예제 #4
0
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]
예제 #5
0
 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)
예제 #6
0
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))
예제 #7
0
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()
예제 #8
0
def makeScrimResult(date):
    [year, month, day] = (int(s) for s in date.split('-'))
    api = PUBG(api_key.api_key(), Shard.PC_TOURNAMENT)
    scrim_result_list = []
    rank_pts_list = {
        "1": 10,
        "2": 6,
        "3": 5,
        "4": 4,
        "5": 3,
        "6": 2,
        "7": 1,
        "8": 1,
        "9": 0,
        "10": 0,
        "11": 0,
        "12": 0,
        "13": 0,
        "14": 0,
        "15": 0,
        "16": 0,
        "17": 0,
        "18": 0,
        "19": 0,
        "20": 0,
        "21": 0,
        "22": 0,
        "23": 0,
        "24": 0,
        "25": 0
    }
    map_name_list = {"Desert_Main": "Miramar", "Baltic_Main": "Erangel"}
    name = "test-pjssc"
    for match in (api.tournaments().get(name)).matches:
        match_time = datetime.strptime(match.attributes['createdAt'],
                                       '%Y-%m-%dT%H:%M:%SZ')
        if ([match_time.year, match_time.month,
             match_time.day] == [year, month, day]):
            matchDetail = func4start.get_matchData_from_server(
                api_key.api_key(), match.id, "tournament")
            for rosters in matchDetail.rosters:
                for participants in rosters.participants:
                    if ("zoo" in participants.name.lower()):
                        pts = sum(item.kills for item in rosters.participants
                                  ) + rank_pts_list[str(rosters.stats['rank'])]
                        high_pts = " "
                        if pts > 9:
                            high_pts = "★"
                        scrim_result_list.append({
                            'map_name':
                            map_name_list[str(matchDetail.map_name)],
                            'rank':
                            rosters.stats['rank'],
                            'pts':
                            pts,
                            'id':
                            matchDetail.id,
                            'high_pts':
                            high_pts
                        })
                        break

    # send scrim result to Dscord
    result_list = []
    result_list.append("**" + date + "**")
    for i in reversed(scrim_result_list):
        result_list.append('{high_pts} {map_name} {rank}位 {pts}pt'.format(
            high_pts=i['high_pts'],
            map_name=i['map_name'],
            rank=str(i['rank']),
            pts=str(i['pts']),
        ))
    resultStr = "\r".join(result_list)
    webhook_url = api_key.discord4scrim_result()
    main_content = {'content': resultStr}
    headers = {'Content-Type': 'application/json'}
    requests.post(webhook_url, json.dumps(main_content), headers=headers)

    # send match id to Discord
    result_list = []
    result_list.append("**" + date + "**")
    for i in reversed(scrim_result_list):
        result_list.append('{id}'.format(id=str(i['id'])))
    resultStr = "\r".join(result_list)
    webhook_url = api_key.discord4match_id()
    main_content = {'content': resultStr}
    headers = {'Content-Type': 'application/json'}
    requests.post(webhook_url, json.dumps(main_content), headers=headers)

    return scrim_result_list
예제 #9
0
 def __init__(self, shard):
     Configuration.__init__(self)
     self.api = PUBG(self.API_KEY, shard)
예제 #10
0
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.')
예제 #11
0
def main():
    shardName = 'STEAM'
    charaNameIndex = []
    charaIdIndex = []
    charaPositionXIndex = []
    charaPositionYIndex = []
    charaPositionZIndex = []
    charaRankIndex = []
    elapsedTimeIndex = []
    playerDeadPositionIndex = []
    killPlayerPositionIndex = []
    playerKillCountIndex = []
    playerLandingPositionIndex = []

    zoneElapsedTimeIndex = []
    safetyZonePositionXIndex = []
    safetyZonePositionYIndex = []
    safetyZoneRadiusIndex = []
    poisonGasPositionXIndex = []
    poisonGasPositionYIndex = []
    poisonGasRadiusIndex = []
    airLineAlpha = 0
    airLineBeta = 0
    airLineFirstPositionIndex = []
    airLineEndPositionIndex = []
    airLineFirstPos = []
    matchDay = ""

    api = PUBG('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJiMGVhNmM0MC1kNGQzLTAxMzYtYmQ3ZC03MzkyZGYzNjZhZTAiLCJpc3MiOiJnYW1lbG9ja2VyIiwiaWF0IjoxNTQzMzY1NDQxLCJwdWIiOiJibHVlaG9sZSIsInRpdGxlIjoicHViZyIsImFwcCI6InlvdXJpNDAxIn0.Z9i2twdF8yDkSPQ2DVjy1jbr7E5PbtiiB9n3UgfyKCg', Shard.STEAM)
    sample = api.samples().get()

    for i in range(len(sample.matches)):
        try:
            matchId = sample.matches[i].id
            match = api.matches().get(matchId)
            asset = match.assets[0]
            telemetry = api.telemetry(asset.url)
            log_match_start = telemetry.events_from_type('LogMatchStart')
            log_player_position = telemetry.events_from_type('LogPlayerPosition')

            if not(log_match_start[0].map_name == "Range_Main"):
                if not(log_match_start[0].is_event_mode):
                    map = getMapImg(log_match_start[0].map_name)
                    player = getPlayersPositonInfo(map,telemetry)
                    matchDay = match.attributes["createdAt"]
                    customMatchFlag = log_match_start[0].is_custom_game
                    charaNameIndex,charaIdIndex,charaPositionXIndex,charaPositionYIndex,charaPositionZIndex,charaRankIndex,elapsedTimeIndex = player.getAllPlayersAllInfo()
                    playerDeadPositionIndex,killPlayerPositionIndex,playerKillCountIndex = player.getPlayerKillDeadPosition(charaIdIndex,charaRankIndex)
                    playerLandingPositionIndex = player.getPlayerLandingPosition(charaIdIndex)
                    instanceMatch = getMatchInfo(telemetry)
                    zoneElapsedTimeIndex,safetyZonePositionXIndex,safetyZonePositionYIndex,safetyZoneRadiusIndex,poisonGasPositionXIndex,poisonGasPositionYIndex,poisonGasRadiusIndex = instanceMatch.getSafetyAndPoisonGasPosInfo()
                    airLineAlpha,airLineBeta,airLineFirstPositionIndex,airLineEndPositionIndex = instanceMatch.getAirPlaneInfo(map)

                    wpIndex = makePlayerWriteIndex(charaNameIndex,charaIdIndex,charaRankIndex,playerLandingPositionIndex,elapsedTimeIndex,charaPositionXIndex,charaPositionYIndex,charaPositionZIndex,playerDeadPositionIndex,killPlayerPositionIndex,playerKillCountIndex,match.id)
                    wmIndex = makeMatchWriteIndex(match.map_name,match.game_mode,match.id,matchDay,customMatchFlag,airLineAlpha,airLineBeta,airLineFirstPositionIndex,airLineEndPositionIndex,zoneElapsedTimeIndex,safetyZonePositionXIndex,safetyZonePositionYIndex,safetyZoneRadiusIndex,poisonGasPositionXIndex,poisonGasPositionYIndex,poisonGasRadiusIndex,shardName)

                    print(str(i)+"/"+str(len(sample.matches))+"  :  "+match.map_name)

                    writePlayerCsv(wpIndex,match.map_name,match.game_mode)
                    writeMatchCsv(wmIndex)

                else: print(str(i)+" : this match is EventMode")
            else: print(str(i)+"/"+str(len(sample.matches))+" : this match is Range_Main")
        except Exception as e:
            print(e)
예제 #12
0
from pubg_python import PUBG, Shard, exceptions, domain
from flask import Flask, render_template
from flask_bootstrap import Bootstrap

app = Flask(__name__)

boostrap = Bootstrap(app)

api_key = ""
with open("emacser.api_key", "r") as api_key_file:
    api_key = api_key_file.readline().rstrip()
api = PUBG(api_key, Shard.PC_KAKAO)


@app.route('/')
def route_index():
    return render_template("home.html")


def search_roster(rosters, player_name):
    for roster in rosters:
        for (i, player) in enumerate(roster.participants):
            if player.name == player_name:
                return (i, roster.participants)
    return None


def make_dummy_player():
    player = domain.base.Player
    player.name = "NULL"
    player.patch_version = "0.0"
예제 #13
0
from pubg_python import PUBG, Shard

player_name = ""

api = PUBG("", Shard.PC_NA)


def iterator_func(player_name, api):
    players = api.players().filter(player_names=[player_name])
    player = players[0]

    for index, match in enumerate(player.matches):
        match_data = api.matches().get(player.matches[index].id)
        #print(match_data)
        match_roster = match_data.rosters
        print("-----------------MATCH NUMBER %s ---------------" % (index + 1))
        print("Game Mode -", match_data.game_mode)
        print("Match Duration -", match_data.duration)
        participant_filtering(match_roster)
        print("\n")


def participant_filtering(match_roster):
    # Filter the list of participants for the one I want
    for squads in match_roster:
        participant = squads.participants[0]
        #print(participant.name)
        if participant.name == player_name:
            print("Player Name -----", participant.name)
            print("Kills -", participant.kills)
            print("Assists -", participant.assists)
예제 #14
0
from pubg_python import PUBG, Shard

api = PUBG('apikey', Shard.STEAM)


def test_asia_shard():
    api.shard = Shard.PC_AS
    assert isinstance(api._shard, Shard)
    assert api._shard.value == 'pc-as'


def test_europe_shard():
    api.shard = Shard.PC_EU
    assert isinstance(api._shard, Shard)
    assert api._shard.value == 'pc-eu'


def test_pc_kakao_shard():
    api.shard = Shard.PC_KAKAO
    assert isinstance(api._shard, Shard)
    assert api._shard.value == 'pc-kakao'


def test_korea_shard():
    api.shard = Shard.PC_KRJP
    assert isinstance(api._shard, Shard)
    assert api._shard.value == 'pc-krjp'


def test_north_america_shard():
    api.shard = Shard.PC_NA
예제 #15
0
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)
예제 #16
0
 def test_unauthorized(self):
     api = PUBG('', Shard.PC_NA)
     self.assertRaises(UnauthorizedError, api.players().get, '')
예제 #17
0
파일: profile.py 프로젝트: rico0821/pubgi
def show_profile(player_name):
    """
    Show player profile page.
    
    ARGS: player_name, region
    
    1. Check whether player name and region are correctly given. 
        i) If not so: abort.
    2. Check if player with given name and region exists in DB.
        i) If not so:
            (a) Find PUBG player ID using API. If not found, render page for not found.
            (b) Create new player with stats for each game mode, append them accordingly and commit.
            (c) Render profile page for player created.
        ii) If so: render profile page for player found.
    3. Check whether stats exist for current season. 
        i) If not so:
            (a) Create new stats for each game mode, for current season.
            (b) Add all, append and then commit.
            
    """

    api_key = current_app.config['API_KEY']
    season = current_app.config['CURRENT_SEASON']
    region = request.args.get('region', '')

    if not (player_name or region):
        abort(404)

    player = dao.query(Player).filter_by(name=player_name).\
                               filter_by(region=region).first()

    if not player:

        api = PUBG(api_key, shardDict(region))
        pubg_player = api.players.filter(player_names=[player_name])
        #pubg_id = getPlayerId(region, player_name, api_key[region])

        if not pubg_id:
            return render_template('search.html',
                                   results=None,
                                   query=player_name)
        try:
            player = Player(player_name, pubg_id, region)
            soloStats = SoloStats(season)
            duoStats = DuoStats(season)
            squadStats = SquadStats(season)
            dao.add_all([player, soloStats, duoStats, squadStats])

            player.solo.append(soloStats)
            player.duo.append(duoStats)
            player.squad.append(squadStats)

            dao.commit()

            Log.info('New player %r added.' % player)

        except Exception as e:
            dao.rollback()
            Log.error(str(e))
            raise e

        else:
            return render_template('profile_overview.html', player=player)

    stats_exist = any(x.season == season for x in player.solo)

    if not stats_exist:
        try:
            soloStats = SoloStats(season)
            duoStats = DuoStats(season)
            squadStats = SquadStats(season)
            dao.add_all([soloStats, duoStats, squadStats])

            player.solo.append(soloStats)
            player.duo.append(duoStats)
            player.squad.append(squadStats)

            dao.commit()
            Log.info('New season stats for player %r added.' % player)

        except Exception as e:
            dao.rollback()
            Log.error(str(e))
            raise e

    return render_template('profile_overview.html', player=player)
예제 #18
0
 def __init__(self):
     self.api = PUBG(config['tokens']['pubg'], Shard.STEAM)
예제 #19
0
from pubg_python import PUBG, Shard

SHARDS = {
    "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)
예제 #20
0
from pubg_python import PUBG, Shard, Telemetry
import time, pprint, json
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from multiprocessing import Pool
import pymysql
import math

api = PUBG(apikey, Shard.PC_NA)


class PlayerPosition():
    def __init__(self, ftime, position):
        # the final time this persons position is recorded
        self.final_time = ftime
        # the final position that the person was recorded in
        self.position = position
        self.location = False

    def updateposition(self, newposition):
        self.position = newposition

    def town_location(self):
        if self.location == False:
            self.towns = town_list()
            self.location = self.distance_formula()

        return self.location

    def distance_formula(self):
예제 #21
0
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')
예제 #22
0
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
예제 #23
0
파일: test.py 프로젝트: ReolSt/PUBGInfo
# -*- 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)
import json
import requests
from pubg_python import PUBG, Shard
from PIL import Image

VendingMachinecount=0
#打开图片读取数组
im=Image.open('C:/Users/a7385/Desktop/PUBG/测试数据/Miramar_Main_High_Res.png')  #打开图像
pix=im.load()#导入像素

api = PUBG("Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJhMmZiNjI1MC0wZDQzLTAxMzgtNzE2NS0yZGY4YzdjNjQ2ZmYiLCJpc3MiOiJnYW1lbG9ja2VyIiwiaWF0IjoxNTc3NzE4Mjg0LCJwdWIiOiJibHVlaG9sZSIsInRpdGxlIjoicHViZyIsImFwcCI6ImE3Mzg1MzE1ODItZ21hIn0.ZqMmAbzh-nQbCWUuUuy2I86_CGKqGWyHZvZxVhDe4F0", Shard.PC_AS)


#查询玩家信息
url = "https://api.pubg.com/shards/steam/players?filter[playerNames]=wozuiniuOO"
header = {
  "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJhMmZiNjI1MC0wZDQzLTAxMzgtNzE2NS0yZGY4YzdjNjQ2ZmYiLCJpc3MiOiJnYW1lbG9ja2VyIiwiaWF0IjoxNTc3NzE4Mjg0LCJwdWIiOiJibHVlaG9sZSIsInRpdGxlIjoicHViZyIsImFwcCI6ImE3Mzg1MzE1ODItZ21hIn0.ZqMmAbzh-nQbCWUuUuy2I86_CGKqGWyHZvZxVhDe4F0",
  "Accept": "application/json "

}
Player = requests.get(url, headers=header)

Player_jsondata = json.loads(Player.text)
PlayerID=Player_jsondata['data'][0]['id'] #对中括号部分读取数据需要使用[0]
#print('玩家ID:'+PlayerID)

#获取比赛信息
#根据玩家ID查询比赛的ID
MatchID=[(m['id']) for m in Player_jsondata['data'][0]['relationships']['matches']['data']] #进行for循环
#获得某人批量的匹配URL
MatchURL = [('https://api.pubg.com/shards/steam/matches/' + MatchIDURl) for MatchIDURl in MatchID]
예제 #25
0
    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)
예제 #26
0
from datetime import datetime, timedelta
import logging

logging.basicConfig(filename='debug.log',
                    level=logging.DEBUG,
                    format='%(asctime)s %(message)s')

description = """>>>>>Mr. Pubg-bot<<<<<
This bot will be your go-to pubg information buddy! Look at these neat commands:
All commands begin with "!"

"""
bot = commands.Bot(command_prefix='!', description=description)

DATA = json.load(open('bot_info.json'))
PUBG_CLIENT = PUBG(DATA["PUBG_API_KEY"], Shard.PC_NA)


@bot.event
@asyncio.coroutine
def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')
    # Test server channel, '#general,' will receive the message.
    # Thought this best to not blow people up if the bot isnt working and
    # we need to restart it a lot.
    channel = bot.get_channel('422922120608350210')
    yield from bot.send_message(
        channel,
예제 #27
0
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 = []
예제 #28
0
파일: pubg.py 프로젝트: krmoffett/PLUNK
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
예제 #29
0
from pubg_python import PUBG, Shard
import config
import database
import json
import logging


logging.basicConfig(filename='nemesis.log', level=logging.DEBUG)
api = PUBG(config.api_key, Shard.PC_AS)
d = database.database()


def killtally(players):
    """

    :param players:
    :return:
    """
    l = []
    for a in players[0].matches:
        l.append(a.id)
    for match in l:
        get_match = api.matches().get(match)
        match_asset = get_match.assets[0]
        match_tel = api.telemetry(match_asset.url)
        player_kill_events = match_tel.events_from_type('LogPlayerKill')
        print('======================')
        print('Match ID:' + match)
        for b in player_kill_events:
            if not b.killer.name == '':  # ie blue zone killed them
                d.insert_row(b.killer.name)
예제 #30
0
def on_message(message):
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return
    if message.content.startswith('!players'):
        plist = " et ".join(
            [", ".join(userList['users'][:-1]), userList['users'][-1]] if len(userList['users']) > 2 else userList['users'])
        msg = 'Tracked players : ' + plist.format(message)
        yield from client.send_message(message.channel, msg)


@client.event
@asyncio.coroutine
def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

# *****************
# Init
# *****************
config = json.load(open('config.json'))
api = PUBG(config['api']['key'], Shard.PC_NA)
userList = json.load(open('users.json'))

# Pre-fly
InitMatchesPerUser(api, userList)

client.loop.create_task(background_tasks())
client.run(config['discord']['client_run'])