Beispiel #1
1
class main:

    def __init__(self, _APIkey, _sumName, _matchNo, _region, _rankedType):

        # ==== Definitions
        self._gameType = ''
        if _rankedType == "solo":
            self._gameType = 'RANKED_TEAM_5x5'
        elif _rankedType == "ranked":
            self._gameType = 'RANKED_SOLO_x5'
        self._APIkey = _APIkey                                                              # API key for developers
        self._summoner_name = _sumName                                                      # Name of LoL Summoner
        self._watcherObj = RiotWatcher(self._APIkey)                                        # riotwatcher data
        self._sumObj = self._watcherObj.get_summoner(name=self._summoner_name, region=_region)              # Data on Summoner
        self._sID = self._sumObj['id']                                                      # ID of Summoner
        self._match = _matchNo                                                               # ID of match to work with
        self._sumGames = self._watcherObj.get_match_history(summoner_id=self._sID, region=_region, ranked_queues=self._gameType)
        self._stats1 = json.dumps(self._watcherObj.get_match(self._match, region=_region, include_timeline='true'))
        self._parsed1 = json.loads(self._stats1)
        self._matchId = self._parsed1['matchId']
        self._mapId = self._parsed1['mapId']

    def getPeopleForMatch(self):

        _people = {}                                                                # ID | name

        for a in self._parsed1['participantIdentities']:
            _people[a['player']['summonerId']] = str(a['player']['summonerName'])

        return _people

    def getParticipantsForMatch(self):

        _participants = {}                                                          # number | ID

        for values in self._parsed1['participantIdentities']:
            _participants[values['participantId']] = values['player']['summonerId']

        return _participants

    def getEventsPerPerson(self):

        _eventsPerPerson = {}

        for count in range(10):
            _eventsPerPerson[str(count + 1)] = []

        for items in self._parsed1['timeline']['frames']:     # ignores wards
            try:
                tempList = items['events']
                for vals in tempList:
                    #if "participantId" in str(vals):
                    #    _eventsPerPerson[str(vals['participantId'])] = _eventsPerPerson[str(vals['participantId'])] + [vals]
                    if "killerId" in str(vals) and "BUILDING_KILL" not in str(vals):
                        _eventsPerPerson[str(vals['killerId'])] = _eventsPerPerson[str(vals['killerId'])] + [vals]
            except KeyError:
                continue
                # print "skipped", str(items['participantFrames'])

        return _eventsPerPerson

    def getFramesPerPerson(self):

        _framesPerPerson = {}

        for count in range(10):
            _framesPerPerson[str(count + 1)] = []

        for values in self._parsed1['timeline']['frames']:
            for count in range(1, 11):
                tempDict = dict(values['participantFrames'][str(count)])
                _framesPerPerson[str(count)] = _framesPerPerson[str(count)] + [tempDict]

        return _framesPerPerson

#for key in _eventsPerPerson:
    #    print "Participant:", str(key)
    #    for events in _eventsPerPerson[key]:
    #        temp = json.dumps(events, indent=4, sort_keys=True)
    #        print temp

#match = 1960675310
#run = main('', "StirlingArcher69", match)
#print "==== Match details for", str(match), "===="
#print(json.dumps(run.getEventsPerPerson(), indent=4, sort_keys=True))
Beispiel #2
0
class Request:
    def __init__(self):
        self.riot = RiotWatcher(LoL.API_KEY)
        self.champions = self._getChampions()

    def _getChampions(self):
        champion_list = {}
        champions = self.riot.static_get_champion_list()
        for champion in champions["data"]:
            champion_list[champions["data"][champion]["id"]] = champion
        return champion_list

    def _checkRequestStatus(self):
        return self.riot.can_make_request()

    def retrievePlayerData(self, playerId):
        while not self._checkRequestStatus():
            sleep(2.6)
        else:
            player = {}
            player["id"] = playerId
            player["summoner"] = self.riot.get_summoner(name=playerId)
            player["match_history"] = self.riot.get_match_history(player["summoner"]["id"])
            return player
Beispiel #3
0
                print_data(value,tabCount+1)
            else:
                print '%s : %s' % (key, value)
    elif type(obj) == list:
        for value in obj:
            if hasattr(value, '__iter__'):
                print_data(value,tabCount+1)
            else:
                print_tabs(tabCount)
                print value
    else:
        print obj


print_data(me)
match_history = w.get_match_history(me['id'])
print match_history[0]

# # takes list of summoner ids as argument, supports up to 40 at a time
# # (limit enforced on riot's side, no warning from code)
# my_mastery_pages = w.get_mastery_pages(str(me['id']))
# # returns a dictionary, mapping from summoner_id to mastery pages
# # unfortunately, this dictionary can only have strings as keys,
# # so must convert id from a long to a string
# print(my_mastery_pages)
#
# my_ranked_stats = w.get_ranked_stats(me['id'])
# print(my_ranked_stats)
#
# my_ranked_stats_last_season = w.get_ranked_stats(me['id'], season=5)
# print(my_ranked_stats_last_season)
Beispiel #4
0
class DataStore:
    """
    DataStore is the script that reads json repsonses from the League of Legends API and stores these responses to
    disk in the respective player's folder.
    """

    def __init__(self, api, sumName, region):
        """
        Initialisation function.
        :param api: The API key for the user, this is obtained through Riot's developer site.
        :param sumName: The name of the LoL Summoner that data will be pulled for.
        :param region: The region that the Summoner plays in.
        :return: None
        """

        self.watcherOb = RiotWatcher(api)

        # LolStats
        # The match history is a temporary solution to get this done quick,
        # basically it just dumps a match history file every time instead of
        # adding on to the current one. :(

        self.origDir = os.getcwd()
        self._playerName = sumName
        self._playerRegion = region
        self._playerData = ''
        self._playerID = 0
        self._playerHist = ''
        if self._playerRegion != '':
            self._playerData = self.watcherOb.get_summoner(name=self._playerName, region=self._playerRegion)
            self._playerID = int((self.watcherOb.get_summoner(name=self._playerName, region=self._playerRegion))['id'])
            self._playerHist = self.watcherOb.get_match_history(summoner_id=self._playerID, ranked_queues='RANKED_SOLO_5x5', region=self._playerRegion)
        else:
            self._playerData = self.watcherOb.get_summoner(name=self._playerName)
            self._playerID = int((self.watcherOb.get_summoner(name=self._playerName))['id'])
            self._playerHist = self.watcherOb.get_match_history(summoner_id=self._playerID, ranked_queues='RANKED_SOLO_5x5')

        #print self._playerHist
        self._playerMatches = []
        for allVals in self._playerHist['matches']:
            self._playerMatches.append(allVals['matchId'])

        _dir = str(os.getcwd())+"/static/json/"

        # Dir creation

        def writer(_dir, _file, _data, _json):
            """
            Helper function to write data to the disk.
            :param _dir: The directory to store the data.
            :param _file: The name to call the file that is created.
            :param _data: The data object to write to the file.
            :param _json: Flag to indicate if the data is JSON or not.
            :return: None
            """
            writeFile = open(str(_dir)+"/"+str(_file), "w")
            if _json is True:
                writeFile.write(json.dumps(_data, indent=4))
            else:
                writeFile.write(_data)
            writeFile.close()

        if not os.path.exists(_dir+str(self._playerID)):
            os.makedirs(str(_dir+str(self._playerID)))
            writer((str(_dir+str(self._playerID))), "_playerData.json", self._playerData, True)
            writer((str(_dir+str(self._playerID))), "_playerHist1.json", self._playerHist, True)
        else:
            if not os.path.isfile(str(_dir+str(self._playerID)+"/_playerData.json")):
                writer((str(_dir+str(self._playerID))), "_playerData.json", self._playerData, True)
            if not os.path.isfile(str(_dir+str(self._playerID)+"/_playerHist1.json")):
                writer((str(_dir+str(self._playerID))), "_playerHist1.json", self._playerHist, True)
            elif os.path.isfile(str(_dir+str(self._playerID)+"/_playerHist1.json")):
                os.chdir(_dir+str(self._playerID))
                temp = glob.glob("_playerHist*")
                inc = int(re.search(r'\d+', str(temp[-1])).group()) + 1
                writer((str(_dir+str(self._playerID))), "_playerHist"+str(inc)+".json", self._playerHist, True)
                if filecmp.cmp("_playerHist"+str(inc-1)+".json", "_playerHist"+str(inc)+".json") is True:
                    os.remove("_playerHist"+str(inc)+".json")
                os.chdir(self.origDir)

        if not os.path.exists(_dir+str(self._playerID)+"/matchData"):
            os.makedirs(_dir+str(self._playerID)+"/matchData")

        os.chdir(_dir+str(self._playerID))
        for i in glob.glob("_playerHist*"):
            temp = json.load(open(i, 'r'))
            for vals in temp['matches']:
                if not os.path.isfile(str(_dir+str(self._playerID)+"/matchData/"+str(vals['matchId'])+".json")):
                    writer(str(_dir+str(self._playerID)+"/matchData/"), str(vals['matchId'])+".json", self.watcherOb.get_match(match_id=vals['matchId'], include_timeline=True), True)
        os.chdir(self.origDir)

    def getPlayerID(self):
        return self._playerID
Beispiel #5
0
        print game
        game_found = True
    except Exception as e:
        pass

#find which champion they are playing
champion_id = None
for player in game["participants"]:
    if player["summonerId"] == summoner_id:
        champion_id = player["championId"]

wait_for_request()

# find other matches where they played that champion
matches = watcher.get_match_history(summoner_id,
                                    region=region,
                                    chapion_ids=[champion_id])

wait_for_request()

# TO DO
# find matches on the relevant map if possible and add item builds to files.

wait_for_request()
champ_data = watcher.static_get_champion(champion_id, region=region)
print "CHAMP DATA"
print champ_data
champion_key = champ_data["key"]

json_data = get_item_build(champion_key)
Beispiel #6
0
                print_data(value, tabCount + 1)
            else:
                print '%s : %s' % (key, value)
    elif type(obj) == list:
        for value in obj:
            if hasattr(value, '__iter__'):
                print_data(value, tabCount + 1)
            else:
                print_tabs(tabCount)
                print value
    else:
        print obj


print_data(me)
match_history = w.get_match_history(me['id'])
print match_history[0]

# # takes list of summoner ids as argument, supports up to 40 at a time
# # (limit enforced on riot's side, no warning from code)
# my_mastery_pages = w.get_mastery_pages(str(me['id']))
# # returns a dictionary, mapping from summoner_id to mastery pages
# # unfortunately, this dictionary can only have strings as keys,
# # so must convert id from a long to a string
# print(my_mastery_pages)
#
# my_ranked_stats = w.get_ranked_stats(me['id'])
# print(my_ranked_stats)
#
# my_ranked_stats_last_season = w.get_ranked_stats(me['id'], season=5)
# print(my_ranked_stats_last_season)
Beispiel #7
0
 if lastSummonerId != None:
     if sid == lastSummonerId:
         lastSummonerId = None
     else:
         continue
 idx = 0
 inc = 1
 retry = 0
 while True:
     try:
         # Check to make sure we can make a request so that we don't exceede the rate limit
         while not w.can_make_request():
             time.sleep(0)
         matches = w.get_match_history(
             sid,
             region=NORTH_AMERICA,
             ranked_queues=['RANKED_SOLO_5x5'],
             begin_index=idx,
             end_index=idx + inc)
         if "matches" in matches:
             for m in matches["matches"]:
                 print((sid, m["matchId"])),
                 match = get_common_match_data(m)
                 participants = {}
                 for p in m["participants"]:
                     participants[p["participantId"]] = p
                 for p in m["participantIdentities"]:
                     participants[p["participantId"]].update(
                         p["player"])
                 for p in participants:
                     if participants[p]['summonerId'] == sid:
                         participant = get_participant_match_data(
Beispiel #8
0
 # Loop though list of summoners and get their data
 for sid in sids:
     if lastSummonerId != None:
         if sid == lastSummonerId:
             lastSummonerId = None
         else:
             continue
     idx = 0
     inc = 1
     retry = 0
     while True:
         try:
             # Check to make sure we can make a request so that we don't exceede the rate limit
             while not w.can_make_request():
                 time.sleep(0)
             matches = w.get_match_history(sid,region=NORTH_AMERICA,ranked_queues=['RANKED_SOLO_5x5'],begin_index=idx,end_index=idx+inc)
             if "matches" in matches:
                 for m in matches["matches"]:
                     print((sid,m["matchId"])),
                     match = get_common_match_data(m)
                     participants = {}
                     for p in m["participants"]:
                         participants[p["participantId"]] = p
                     for p in m["participantIdentities"]:
                         participants[p["participantId"]].update(p["player"])
                     for p in participants:
                         if participants[p]['summonerId']==sid:
                             participant = get_participant_match_data(participants[p])
                             stats = get_participant_match_stat_data(participants[p]['stats'])
                             d = merge_dicts(match,participant,stats)
                             c = build_insert_call(MATCH_COMMON,MATCH_PARTICIPANT,MATCH_PARTICIPANT_STATS)
Beispiel #9
0
        game = watcher.get_current_game(summoner_id)
        print game
        game_found = True
    except Exception as e:
        pass

# find which champion they are playing
champion_id = None
for player in game["participants"]:
    if player["summonerId"] == summoner_id:
        champion_id = player["championId"]

wait_for_request()

# find other matches where they played that champion
matches = watcher.get_match_history(summoner_id, region=region, chapion_ids=[champion_id])

wait_for_request()

# TO DO
# find matches on the relevant map if possible and add item builds to files.

wait_for_request()
champ_data = watcher.static_get_champion(champion_id, region=region)
print "CHAMP DATA"
print champ_data
champion_key = champ_data["key"]

json_data = get_item_build(champion_key)

# save on a mac