def request_api(team, region, ign):
    offset = 0
    limit = 5
    created_at_start = RETRIEVE_START_DATE
    apiKey = app.config['API_KEY_RANKED']
    match_id_list = []
    while True:
        try:
            app.logger.info(
                'retrieving Gamelocker API data : offset = {}'.format(offset))
            api = gamelocker.Gamelocker(apiKey).Vainglory()
            matches = api.matches(
                {
                    'filter[playerNames]': ign,
                    'filter[createdAt-start]': created_at_start,
                    'page[limit]': limit,
                    'page[offset]': offset
                },
                region=region)
            if matches is not None:
                for match in matches:
                    match_model = process_match(match)
                    if match_model is not None:
                        match_id_list.append(match_model.id)

                offset += limit
            else:
                # 404 Exception will be thrown when there's no data
                pass
        except ConnectionResetError as e:
            # retry
            app.logger.info(e)
            app.logger.info(
                'ConnectionResetError. sleep 10 seconds and continue')
            sleep(10)
            continue

        except HTTPError as e:
            if e.response.status_code == 404:
                app.logger.info('Couldn\'t find match history')
            else:
                app.logger.info(e)
            break

    return match_id_list
Example #2
0
def retrieve_player_match_history(gamemode=None, player_id=None, ign=None):
    offset = 0
    while True:
        try:
            app.logger.info('retrieving Gamelocker API : offset = ' +
                            str(offset))
            api = gamelocker.Gamelocker(app.config['API_KEY']).Vainglory()
            matches = api.matches(
                {
                    'filter[patchVersion]': PATCH_VERSION,
                    'filter[gameMode]': gamemode,
                    'filter[playerIds]': player_id,
                    'page[limit]': LIMIT,
                    'page[offset]': offset
                },
                region='ea')
            if matches is not None:
                process_count = 0
                for match in matches:
                    count = process_match(match)
                    process_count = process_count + count

                if process_count == 0:
                    # 全部処理済だったら、このプレイヤーは終了
                    # 本当は続きがあるかもしれないけど、網羅するよりも高速化を優先する為
                    break

                if LIMIT == len(matches):
                    # 続きがありそう
                    offset = offset + LIMIT
                    continue
            else:
                app.logger.info('no match found')
                break

        except HTTPError as e:
            if e.response.status_code == 404:
                # 最近試合してない、IGNが違う、など
                app.logger.info('Couldn\'t find match history')
            else:
                app.logger.info(e)
            # エラーが発生したら、とりあえずこのプレイヤーは終了
            break
Example #3
0
# VG Module:
# Functions using the VG API. Functions using Discord libraries will be marked by, "!!!DISCORD!!!", in their description.

# IMPORTS
import gamelocker
import datetime
import discord
from discord.ext import commands
import TOOL_module as tools

# VG Variables--
keyVG = ""  # VG_API_TOKEN_HERE
apiVG = gamelocker.Gamelocker(keyVG).Vainglory()  # API OBJECT


# Will CHECK if NAME is VALID. Will RETURNS True or False if TYPE = 0, if TYPE = 1 returns ID or False.
def getIDVG(name, type=0):
    name = str(name)  # Convert NAME to STRING to prevent errors

    # ADD when FETCHING from VG API!!! example: {"filter[createdAt-start]": daterange, "filter[createdAt-end]": datenow, etc...}
    datenow = datetime.datetime.today()
    daterange = str(datenow - datetime.timedelta(days=7)) + "T00:00:00Z"  # Get the DATE RANGE to SEARCH from
    datenow = str(datetime.datetime.today()) + "T00:00:00Z"  # CURRENT DATE

    try:
        matches = apiVG.matches({"filter[createdAt-start]": "2017-02-16T12:00:00Z", "page[limit]": 2, "filter[playerNames]": name})
        for r in matches[0].rosters:
            for p in r.participants:
                if p.player.name == name:
                    if type == 0:  # Returns TRUE when name is FOUND
                        return True
Example #4
0
 def api(self):
     return gamelocker.Gamelocker(
         os.environ["GAMELOCKER_APIKEY"]).Vainglory()
Example #5
0
def data():
    data = cache.get("data")
    if data is not None:
        return render_template("stats.js", stats=data)

    data = dict()
    api = gamelocker.Gamelocker("aaa.bbb.ccc").Vainglory()
    data["number"] = config.batchsize
    matches = api.matches({"page[limit]": data["number"]})

    playersactors = dict()
    gameModes = dict()
    durations = dict()
    players = dict()
    heroes = dict()
    sells = dict()
    minions = 0
    potions = 0
    cs = dict()
    boots = 0
    for match in matches:
        if match.gameMode not in gameModes:
            gameModes[match.gameMode] = 0
            durations[match.gameMode] = []
        gameModes[match.gameMode] += 1
        durations[match.gameMode] += [match.duration / 60]

        for roster in match.rosters:
            for participant in roster.participants:
                if participant.player.name not in players:
                    players[participant.player.name] = 0
                players[participant.player.name] += 1

                if gamelocker.pretty(participant.actor) not in heroes:
                    heroes[gamelocker.pretty(participant.actor)] = 0
                heroes[gamelocker.pretty(participant.actor)] += 1

                # TODO use id instead of name?
                playersactors[participant.player.name] = gamelocker.pretty(
                    participant.actor)
                cs[participant.player.name] = participant.stats[
                    "minionKills"] / match.duration * 60
                minions += participant.stats["minionKills"]

                for item in participant.stats["items"]:
                    if gamelocker.pretty(item) in [
                            "Sprint Boots", "Travel Boots", "Journey Boots",
                            "War Treads", "Halcyon Chargers"
                    ]:
                        boots += 1

                for item in participant.stats["itemUses"]:
                    if gamelocker.pretty(item) == "Halcyon Potion":
                        potions += participant.stats["itemUses"][item]

                for sold in participant.stats["itemSells"]:
                    item = gamelocker.pretty(sold)
                    if not item in sells:
                        sells[item] = 0
                    sells[item] += participant.stats["itemSells"][sold]

    sells = sorted(sells.items(), key=lambda x: x[1], reverse=True)
    data["topsold"] = ", ".join([s[0] for s in sells[0:3]])

    cs = sorted(cs.items(), key=lambda x: x[1], reverse=True)
    data["topcs"] = dict()
    data["topcs"]["player"] = cs[0][0]
    data["topcs"]["cs"] = round(cs[0][1], 2)
    data["topcs"]["actor"] = playersactors[data["topcs"]["player"]]

    data["minions"] = minions
    data["boots"] = boots / len(matches)
    data["potions"] = round(60 * sum(sum(durations.values(), [])) / potions, 2)

    data["gameModes"] = [{"name": k, "y": v} for k, v in gameModes.items()]
    data["durations"] = [{
        "name":
        k,
        "data":
        list(zip([list(durations.keys()).index(k)] * len(v), v))
    } for k, v in durations.items()]

    data["heroes"] = list(heroes.keys())
    heroes = sorted(heroes.items(), key=lambda x: x[1], reverse=True)
    data["picks"] = [{"name": k, "data": [v]} for k, v in heroes]

    players = sorted(players.items(), key=lambda x: x[1], reverse=True)[:5]
    data["players"] = [{"name": k, "data": [v]} for k, v in players]

    cache.set("data", data, timeout=10 * 60)

    return render_template("stats.js", stats=data)
Example #6
0
def get_api():
    APIKEY = "aaa.bbb.ccc"
    return gamelocker.Gamelocker(APIKEY).Vainglory()
Example #7
0
#!/usrz/bin/python

#
#How to access Telemetry using python - gamelocker#
#
import gamelocker
vgApiKey = ''
api = gamelocker.Gamelocker(vgApiKey).Vainglory()


# Get telemetry URL for a particular match played by IGN.
def getTelemetryInfo(IGN):
    try:
        matches = api.matches({
            "sort": "-createdAt",
            "filter[playerNames]": IGN,
            "filter[createdAt-start]": "2017-03-10T00:00:00Z",
            "page[limit]": "1"
        })

        if (matches == False):
            print("No Matches found")
        else:
            match = matches[0]
        print('Time Played: ', match.createdAt)
        print('GameMode: ', match.gameMode)
        print(match.assets[0].name, match.assets[0].url)
    except:
        print("Invalid Name")

Example #8
0
#Modified from Github python-gamelocker/examples/kda.py
# __author__: iAm-Kashif

import gamelocker
from gamelocker.strings import pretty

api = gamelocker.Gamelocker(VG_API_Key).Vainglory()


def getPlayerStats(IGN):

    matches = api.matches({
        "sort": "-createdAt",
        "filter[playerNames]": IGN,
        "filter[createdAt-start]": "2017-03-10T00:00:00Z",
        "page[limit]": "5"
    })

    matches = sorted(matches, key=lambda d: d.createdAt, reverse=True)

    if (matches == False):
        print("No Matches found")

    else:
        match = matches[0]
        print('Time Played: ', match.createdAt)
        print('GameMode: ', match.gameMode)
        print('Telemetry: ', match.assets[0].url)

        for team in range(2):
            print("\nTeam", team + 1)
 def api(self):
     return gamelocker.Gamelocker(self.apikey).Vainglory()
Example #10
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 28 16:12:02 2017

@author: phypoh

https://github.com/schneefux/python-gamelocker
"""
import gamelocker
from gamelocker.strings import pretty

APIKEY = "aaa.bbb.ccc"
api = gamelocker.Gamelocker(APIKEY).Vainglory()

#player_name = input("Player name?")

player_name = "IraqiZorro"

matches = api.matches({"page[limit]": 10, "filter[playerNames]": player_name})

match = matches[0]

for team in range(2):
    print("\nTeam", team + 1)
    for player in range(3):
        name = match.rosters[team].participants[player].player.name
        hero = pretty(match.rosters[team].participants[player].actor)
        kills = match.rosters[team].participants[player].stats["kills"]
        deaths = match.rosters[team].participants[player].stats["deaths"]
        assists = match.rosters[team].participants[player].stats["assists"]
Example #11
0
def retrieve_match_history(gamemode, region, now):
    """
    Gamelocker API から試合履歴を取得し諸々処理して保存する

    createdAt-startを、最新時刻より2時間前
    createdAt-endを、最新時刻より1時間前

    取りきるまで回す
    1時間毎に起動する(試合数が多いと多重起動になってサーバーが落ちるけど、まぁ...。)
    """
    offset = 0

    apikey_index = 'API_KEY_{}'.format(region.upper())
    apiKey = app.config[apikey_index]

    created_at_start = (now -
                        timedelta(minutes=121)).strftime("%Y-%m-%dT%H:%M:%SZ")
    created_at_end = (now -
                      timedelta(minutes=60)).strftime("%Y-%m-%dT%H:%M:%SZ")

    app.logger.info(
        'process started : gamemode = {}, region = {}, createdAt-start = {}'.
        format(gamemode, region, created_at_start))

    while True:
        try:
            app.logger.info(
                'retrieving Gamelocker API data : offset = {}'.format(offset))
            api = gamelocker.Gamelocker(apiKey).Vainglory()
            matches = api.matches(
                {
                    'filter[gameMode]': gamemode,
                    'filter[createdAt-start]': created_at_start,
                    'filter[createdAt-end]': created_at_end,
                    'page[limit]': LIMIT,
                    'page[offset]': offset
                },
                region=region)
            if matches is not None:
                processed_count = 0
                for match in matches:
                    processed_count += process_match(match, now)

                app.logger.info(
                    '{} matches were processed.'.format(processed_count))
                offset += LIMIT
            else:
                # 試合履歴が無い時は 404 Exception になる模様
                pass
        except ConnectionResetError as e:
            # 通信エラー系はリトライ
            app.logger.info(e)
            app.logger.info(
                'ConnectionResetError. sleep 10 seconds and continue')
            sleep(10)
            continue

        except HTTPError as e:
            if e.response.status_code == 404:
                app.logger.info('Couldn\'t find match history')
            else:
                app.logger.info(e)
            break

    app.logger.info(
        'process finished : gamemode = {}, region = {}, createdAt-start = {}'.
        format(gamemode, region, created_at_start))
    return