예제 #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
 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)
예제 #5
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))
예제 #6
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)
예제 #7
0
#!/usr/bin/python3
import pprint
import re
from typing import List

import discord
from discord.ext import commands
from discord.ext.commands import Context
from pubg_python import PUBG, Shard

from config import Config
from stat_options import StatOptions
from weapons import Weapons

conf = Config()
pubg_api = PUBG(conf.pubg_api, Shard.PC_NA)
# client = discord.Client()
bot = commands.Bot(command_prefix='$')
_weapons = Weapons()
stat_options = StatOptions()


@bot.command()
async def weapon(ctx: Context, weapon_name: str = '', player_name: str = ''):
    """Look up a specific weapon and print its stats to Discord."""
    print('You are in the weapon function')
    p_name = _player_name(ctx.author, player_name)
    author = ctx.author.name

    pubg_player_id = player_id(p_name)
    if pubg_player_id == -1:
예제 #8
0
import matplotlib.pyplot as plot
import matplotlib.image as image
import datetime
from pubg_python import PUBG, Shard
from pubg_python.domain.telemetry.events import LogParachuteLanding
import seaborn as sns
import threading
import math
import logging
import telemetry_filters as filters
from telemetry_filters import COMMON_COLUMNS, ITEM_COLUMNS, KILL_KNOCK_COLUMNS

logger = logging.getLogger('pubg-agg')
logger.setLevel(logging.DEBUG)
api_key = os.environ.get('API_KEY')
api = PUBG(api_key=api_key, shard=Shard.PC_NA)
#COLUMNS = ['match_id', 'map_name', 'game_mode', 'telemetry_url', "landing_x", "landing_y", "landing_zone", "player", "match_start"]
df = pd.DataFrame(columns=COMMON_COLUMNS + ITEM_COLUMNS + KILL_KNOCK_COLUMNS)
quant = 100


def main(date=None):
    start_time = datetime.datetime.now()
    print(f"script start time: {start_time}")
    ret = api.samples()

    #query string for samples call
    params = {
        'filter[createdAt-start]': f"{date}T12:00:00Z"
    } if date is not None else None
예제 #9
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)
예제 #10
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)
예제 #11
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
예제 #12
0
 def __init__(self, shard):
     Configuration.__init__(self)
     self.api = PUBG(self.API_KEY, shard)
예제 #13
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]
예제 #15
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)
예제 #16
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)
예제 #17
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.')
예제 #18
0
## Mesmo programa, mas apenas para PREMIUMS

from pubg_python import PUBG, Shard
import MySQLdb
from openpyxl import Workbook

KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

con = MySQLdb.connect(host="xxxx", port=xxxx, user='******', passwd='xxx', db='xxx')

cursor = con.cursor()
cursor.execute('SELECT nick_pubg FROM premium')

jogadores = cursor.fetchall()
jogadores = [jogador[0] for jogador in jogadores]
api = PUBG(KEY, Shard.PC_SA)

wb = Workbook(write_only=True)
ws = wb.create_sheet()

ws.append(["Nome", "Mapa", "Modo de Jogo", "Data", "Kills", "Posição Final"])

jogadoresSeparados = []
posFinalConjunto5Array1 = 0
cont = 1
while cont<=(len(jogadores)/5):
    jogs = []
    i=(cont*5)-5
    while i<5*cont:
        jogs.append(jogadores[i])
        i+=1
예제 #19
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'])
예제 #20
0
def start_convert(api_key, shard, match_id):
    print("변환을 시작합니다. 잠시 기다려주세요...")

    api = PUBG(api_key, shard)
    match = api.matches().get(match_id)
    telemetry = api.telemetry(match.assets[0].url)
    replay = dict()

    map_name = match.map_name
    # Erangel remake map (future update)
    if map_name == "Baltic_Main":
        map_name = "Erangel_Main"

    winners = []
    for roster in match.rosters:
        for player in roster.participants:
            if player.stats["winPlace"] == 1:
                winners.append(player.stats["name"])

    info = {
        "canRevive": False,
        "interpolation": True,
        "playerScale": 0.33,
        "speed": 10,
        "map": map_name,
        "win": ", ".join(winners),
        "sortPlayerList": True,
        "teamVS": False
    }
    replay["info"] = info

    player_kill_events = telemetry.events_from_type("LogPlayerKill")
    player_position_events = telemetry.events_from_type("LogPlayerPosition")
    player_creation_events = telemetry.events_from_type("LogPlayerCreate")
    package_events = telemetry.events_from_type("LogCarePackageLand")
    start_event = telemetry.events_from_type("LogMatchStart")[0]
    state_events = telemetry.events_from_type("LogGameStatePeriodic")
    gamestart_timestamp = ISODate2MicroTimestamp(start_event.timestamp)

    id_dict = dict()
    players = []
    for ev in player_creation_events:
        user = ev.character
        id_dict[user.account_id] = str(len(id_dict) + 1)
        players.append({
            "name": re.sub("\\s\\s+", " ", user.name),
            "team": user.team_id,
            "id": id_dict[user.account_id]
        })
    info["players"] = players

    events = []

    for i in state_events:
        state = i.game_state
        timestamp = relativeTimestamp(gamestart_timestamp, i.timestamp)

        if state.safety_zone_radius > 0:
            location = adjustLocation(state.safety_zone_position["x"],
                                      state.safety_zone_position["y"],
                                      map_name)
            events.append(
                GameEvent(
                    "CIRCLE_ON", timestamp, {
                        "id":
                        "S_ZONE",
                        "x":
                        location[0],
                        "y":
                        location[1],
                        "radius":
                        adjustLocation(state.safety_zone_radius, 0,
                                       map_name)[0],
                        "color":
                        "0x0055FF"
                    }))

        if state.poison_gas_warning_radius > 0:
            location = adjustLocation(state.poison_gas_warning_position["x"],
                                      state.poison_gas_warning_position["y"],
                                      map_name)
            events.append(
                GameEvent(
                    "CIRCLE_ON", timestamp, {
                        "id":
                        "W_ZONE",
                        "x":
                        location[0],
                        "y":
                        location[1],
                        "radius":
                        adjustLocation(state.poison_gas_warning_radius, 0,
                                       map_name)[0],
                        "color":
                        "0xFFFFFF"
                    }))

    for n, i in enumerate(package_events):
        location = adjustLocation(i.item_package.location.x,
                                  i.item_package.location.y, map_name)
        timestamp = relativeTimestamp(gamestart_timestamp, i.timestamp)
        events.append(
            GameEvent(
                "CREATE", timestamp, {
                    "id": "PACKAGE_%d" % (n + 1),
                    "x": location[0],
                    "y": location[1],
                    "sprite": "package",
                }))

    for i in player_position_events:
        user = i.character
        location = adjustLocation(user.location.x, user.location.y, map_name)
        timestamp = relativeTimestamp(gamestart_timestamp, i.timestamp)
        if timestamp < 0:
            continue

        events.append(
            GameEvent(
                "MOVE", timestamp, {
                    "id": id_dict[user.account_id],
                    "x": location[0],
                    "y": location[1],
                    "rank": user.ranking,
                }))

    for i in player_kill_events:
        try:
            timestamp = relativeTimestamp(gamestart_timestamp, i.timestamp)
            killer = id_dict.get(i.killer.account_id, None)
            try:
                assists = [id_dict[i._data.store["assistant"]["accountId"]]
                           ] if "assistant" in i._data.store else []
            except:
                assists = []

            gev = GameEvent("KILL", timestamp,
                            {"victimId": id_dict[i.victim.account_id]})
            if killer is not None:
                gev.data["killerId"] = killer
                if assists == [killer]:
                    assists = []
            gev.data["assistIds"] = assists
            events.append(gev)
        except:
            pass

    events.sort()
    replay["timeline"] = events
    result = json.dumps(replay, cls=GameEventJSONEncoder)
    output_file = "pubg_output.json"
    with open(output_file, "w", encoding="utf-8") as f:
        f.write(result)
    print("===========================================")
    print("Complete!", os.path.abspath(output_file), "에 저장되었습니다.")
예제 #21
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
예제 #22
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,
예제 #23
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')
예제 #24
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):
예제 #25
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)
예제 #26
0
 def __init__(self):
     self.api = PUBG(config['tokens']['pubg'], Shard.STEAM)
예제 #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
 def test_unauthorized(self):
     api = PUBG('', Shard.PC_NA)
     self.assertRaises(UnauthorizedError, api.players().get, '')
예제 #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 __init__(self, shard=Shard.PC_OC):
     self.api = PUBG(os.environ['PUBG_API_KEY'], shard)