Coding/Riot API를 사용하여 lolchess.gg 클론 코딩

라이엇 api를 사용하여 TFT(롤토체스) 데이터 수집 -2

zaraxxus 2023. 2. 2. 18:45

1.한국 챌린져 큐의 최근  게임 정보 가져오기

1-2) 한국 TFT 챌린져 명단 데이터로 puuid, name 다시 구해오기

 

MatchID를 가져오기 위해선 각 챌린져의 puuid가 필요하고,

또 챌린져에 저장된 데이터에서 닉변을 한 유저가 생겨 name역시 새로 가져오는 작업을 추가했습니다.

(특히 시즌 말에 닉변을 하는 경우가 많음)

 

작업이 끝나면 파일을 data/challenger.json 으로 저장하는 코드입니다.

 

def challenger_data():
    data = league_v1_get_challenger()
    # add name, puuid가 아직 안되어있는 데이터다
    summ_data = data.copy().set_index("summonerName")
    if os.path.isfile("data/challenger.json"):
        challenger_hx_df = pd.read_json("data/challenger.json", orient="index")
        idx1 = summ_data.index
        idx2 = challenger_hx_df.index
        idx3 = idx1.difference(idx2)
        new_df = summ_data.loc[idx3].copy()
        new_df["summonerName"] = new_df.index
        # 그중에 data->summdata로 여기서 new_df를 추출후 다시 add name과, puuid 추가
        # ( index를 summnerName으로 바꾼상태라 다시 reset 후 함수)
        new_df.reset_index(drop=True, inplace=True)
        new_add_df = add_name_puuid(new_df).set_index("summonerName")
        final_df = pd.concat([challenger_hx_df, new_add_df])
    else:
        challenger_hx_df = data
        new_data = add_name_puuid(challenger_hx_df)
        final_df = new_data
        final_df.set_index("summonerName", inplace=True)
    final_df.to_json("data/challenger.json", orient="index", force_ascii=False)
    idx4 = final_df.index
    idx5 = summ_data.index
    data = final_df.loc[idx4.isin(idx5)]
    return data

 

-> 처음에 else문 부터 돌아가게 될 것 이고, 그 경우에 name, puuid를 가져옵니다

한번 가져온 후 중복 작업을 없애기 위해 if, else문을 작성하였습니다.

def add_name_puuid(df):
    print("start - add name and puuid")
    print(df)
    start = time.time()
    df2 = df.copy()

    for i, Id in enumerate(df2["summonerId"]):
        try:
            summonerId_data = summoner_v1_get_summoner_new_name_puuid(Id)
            new_name = summonerId_data[0]
            puuid = summonerId_data[1]
            df2.loc[i, "newName"] = new_name
            df2.loc[i, "puuid"] = puuid
            print(f"success new_name,puuid - location : {i}")

        except Exception as e:
            print(f"error - location : {i, Id}")
            print(e)
            pass
    end = time.time()
    print(f"success - c_df2 (add name, puuid): {end - start:.2f} sec")
    return df2

 

위에 쓰인 name, puuid 가져오는 함수입니다 

def summoner_v1_get_summoner_new_name_puuid(SummonerId):

    url = f"https://kr.api.riotgames.com/tft/summoner/v1/summoners/{SummonerId}"
    r = get_r(url)

    if r.status_code == 200:
        pass

    elif r.status_code == 429 or r.status_code == 502:
        if r.status_code == 429:
            print("api cost full : infinite loop start")
        elif r.status_code == 502:
            print(" 502 error : infinite loop start")
        start_time = time.time()
        i = 1
        while True:
            if r.status_code == 429 or r.status_code == 502:
                print(f"try 10 seconds wait time: {i}  loops")
                time.sleep(10)
                i = i + 1
                r = get_r(url)

            elif r.status_code == 200:
                print("total wait time :", time.time() - start_time)
                break
    else:
        print(r.status_code)

    rJson = r.json()
    new_name = rJson["name"]
    puuid = rJson["puuid"]

    return new_name, puuid

 

data = challenger_data()

data

 

로 작성하여 주피터 노트북에서  02.06에 실행 확인한 파일입니다.

제가 기존에 가지고 있던 데이터에서 38명이 새롭게 챌린져 데이터에 추가 되었으며

아래는 그 데이터중 일부입니다

 

-> 챌린져 들의 newName, puuid까지 가져온 데이터를 얻었습니다! 

닉변하신 분은 없네요 :)