Riot API를 활용하여 랭크 게임 데이터 수집
라이엇에서는 리그 오브 레전드, 발로란트, 리그 오브 룬테라 등 다양한 API가 제공되고 있으며, 이번 글에서는 Riot API를 이용하여 리그 오브 레전드의 랭크 게임 데이터를 수집하려고 합니다. 파이썬을 이용하여 Riot API로 리그 오브 레전드의 랭크 게임 데이터를 수집해 보겠습니다.
API Key
라이엇 개발자 페이지에 접속하여 관련 내용을 볼 수 있습니다. 개발 API Key를 이용하여 간단하게 진행할 예정이며, 개발 API Key의 경우 1초 20회, 2분 100회 제한이 있습니다.
Riot Developer Portal
About the Riot Games API With this site we hope to provide the League of Legends developer community with access to game data in a secure and reliable way. This is just part of our ongoing effort to respond to players' and developers' requests for data and
developer.riotgames.com
계획
최근(2023.06.14) 13.12.x 버전으로 패치가 있었으며, 해당 버전을 기준으로 랭크 게임 데이터를 수집하려고 합니다. 모든 유저를 수집하기보단 최상위 유저를 기준으로 데이터를 수집할 예정이며, 기간은 6.14 11:00 ~ 6.20 00:00으로 수집했습니다.
다이아 ~ 플레 유저를 하려고 했지만, 개발 API Key의 한계로 최상위권 유저로 변경
매치 데이터를 가져오기 위해서는 각 단계의 작업이 필요하며, 필요한 API는 아래에 정리하였습니다.
① 리그별 소환사 목록(LEAGUE-V4)
- 챌린저 : https://kr.api.riotgames.com/lol/league/v4/challengerleagues/by-queue/{queue}
- 그랜드 마스터 : https://kr.api.riotgames.com/lol/league/v4/grandmasterleagues/by-queue/{queue}
- 마스터 : https://kr.api.riotgames.com/lol/league/v4/masterleagues/by-queue/{queue}
② 소환사 정보(SUMMONER-V4)
- https://kr.api.riotgames.com/lol/summoner/v4/summoners/{SummonerId}
③ 소환사별 매치 목록(MATCH-V5)
- https://asia.api.riotgames.com/lol/match/v5/matches/by-puuid/{puuid}/ids
④ 매치 데이터(MATCH-V5)
- https://asia.api.riotgames.com/lol/match/v5/matches/{matchId}
소환사 목록
최상위 티어의 경우 API가 나눠져 있으며, 각 티어별 API를 호출 할 수 있게 합니다. 챌린저, 그랜드 마스터, 마스터 소환사 목록을 가져옵니다.
import requests
api_key = "API Key"
header = {"X-Riot-Token" : api_key}
def league_v4_tier(tier):
# 솔랭 기준
queue = 'RANKED_SOLO_5x5'
if tier == 'challenger' :
url = f"https://kr.api.riotgames.com/lol/league/v4/challengerleagues/by-queue/{queue}"
elif tier == 'grandmaster':
url = f"https://kr.api.riotgames.com/lol/league/v4/grandmasterleagues/by-queue/{queue}"
else:
url = f"https://kr.api.riotgames.com/lol/league/v4/masterleagues/by-queue/{queue}"
return requests.get(url, headers=header)
반환되는 값에서 소환사명, 소환사 ID, 포인트 정보를 가져옵니다. 실제로 사용할 값은 summonerId이며, summonerId만 가져와도 됩니다.
req = league_v4_tier(tier)
if req.status_code == 200:
data = req.json()['entries']
for item in data:
summonerName = item['summonerName']
summonerId = item['summonerId']
leaguePoints = item['leaguePoints']
소환사 정보
앞에서 가져온 summonerId를 이용하여 소환사 정보를 가져오는 API입니다.
import requests
api_key = "API Key"
header = {"X-Riot-Token" : api_key}
def summoners(encryptedSummonerId):
url = f"https://kr.api.riotgames.com/lol/summoner/v4/summoners/{encryptedSummonerId}"
return requests.get(url, headers=header)
반환되는 값에서 puuid, name 정보를 가져옵니다. 실제로 사용할 값은 puuid이며, puuid만 가져와도 됩니다.
req = summoners(summoner_id)
if req.status_code == 200:
data = req.json()
puuid = data['puuid']
name = data['name']
소환사별 매치 목록
앞에서 가져온 puuid를 이용하여 소환사별 매치 목록을 가져오는 API이며 몇 가지 조건을 추가하였습니다.
날짜 : 2023.06.14 11:00 ~ 2023.06.20 00:00 / 타입 : 랭크 게임
start(defalut: 0) : 시작 인덱스
count(defalut: 20) : 가져올 매치 id 개수로 0 ~100
import requests
api_key = "API Key"
header = {"X-Riot-Token" : api_key}
def match_list(puuid, start):
url = f"https://asia.api.riotgames.com/lol/match/v5/matches/by-puuid/{puuid}/ids?startTime=1686708000&endTime=1687186800&type=ranked&start={start}&count={count}"
return requests.get(url, headers=header)
반환되는 값은 matchId로 이루어진 리스트만 반환되며, 해당 리스트를 그대로 가져오면 됩니다.
req = match_list(puuid, start)
if req.status_code == 200:
data = req.json()
data_cnt = len(data)
for item in data:
print(item)
매치 데이터
matchId를 모아서 중복을 제거해줍니다.(최대 10개의 중복이 있을 수 있습니다. 251,324건 → 59,464건으로 중복 제거 됨) 해당 matchId를 이용하여 매치 데이터를 가져옵니다.
import requests
api_key = "API Key"
header = {"X-Riot-Token" : api_key}
def match(matchId):
url = f"https://asia.api.riotgames.com/lol/match/v5/matches/{matchId}"
return requests.get(url, headers=header)
해당 API에는 다양한 데이터들이 존재하고 있으며, 필요에 맞게 데이터를 가져오면 됩니다. 이외에도 다양한 데이터가 존재하며, 공식 페이지를 참고하여 수정하시면 되겠습니다.
req = match(match_id)
if req.status_code == 200:
data = req.json()
queue_id = data['info']['queueId'] # 큐 id
game_duration = data['info']['gameDuration'] # 게임 진행 시간
game_start_timestamp = data['info']['gameStartTimestamp'] # 게임 시작 시간
game_end_timestamp = data['info']['gameEndTimestamp'] # 게임 종료 시간
# 매치 데이터(포지션/챔피언/킬/데스/어시/CS 등)
participants = data['info']['participants']
for participant in participants:
team_id = participant['teamId'] # 팀 id
summoner_id = participant['summonerId'] # 소환사 id
summoner_name = participant['summonerName'] # 소환사명
summoner_1_id = participant['summoner1Id'] # 소환사 주문1
summoner_2_id = participant['summoner2Id'] # 소환사 주문2
team_position = participant['teamPosition'] # 포지션
champion_id = participant['championId'] # 챔피언 id
kills = participant['kills'] # 킬
deaths = participant['deaths'] # 데스
assists = participant['assists'] # 어시스트
kda = participant['challenges']['kda'] # kda
neutral_minions_killed = participant['neutralMinionsKilled'] # 중립 미니언 처치(정글몹)
total_minions_killed = participant['totalMinionsKilled'] # 미니언 처치
if team_position == 'UTILITY':
team_position = 'SUPPORT'
# 팀 데이터
teams = data['info']['teams']
for team in teams:
team_id = team['teamId'] # 팀 id
first_blood = team['objectives']['champion']['first'] # 첫 킬
first_tower = team['objectives']['tower']['first'] # 첫 타워
first_inhibitor = team['objectives']['inhibitor']['first'] # 첫 억제기
first_baron = team['objectives']['baron']['first'] # 첫 바론
first_dragon = team['objectives']['dragon']['first'] # 첫 드래곤
first_rift_herald = team['objectives']['riftHerald']['first'] # 첫 전령
win = team['win'] # 승패
# bans = team['bans']['championId']
bans = team['bans'] # 밴 목록
bans_lst = []
for ban in bans:
if ban['championId'] != -1:
bans_lst.append(ban['championId'])
해당 데이터는 아래 이미지처럼 데이터 생성될 예정입니다.
챔피언 이름
매치 데이터에는 챔피언 이름을 영어로 제공하고 있으며 아래 링크의 데이터를 이용하여 id별 챔피언 이름 데이터를 생성하였습니다.
https://ddragon.leagueoflegends.com/cdn/13.12.1/data/ko_KR/champion.json
개발 API Key를 이용하여 데이터 수집 중이라 제한이 있는 상태입니다. 딜레이 1.5초로 1분에 최대 40건(2분 최대 80건)씩 호출할 수 있게 했습니다. matchId가 약 6만 건이 생성되었으며, 매치 데이터를 수집하기 위해서는 약 25시간이 소요될 것으로 보입니다.
참고
Riot Developer Portal
About the Riot Games API With this site we hope to provide the League of Legends developer community with access to game data in a secure and reliable way. This is just part of our ongoing effort to respond to players' and developers' requests for data and
developer.riotgames.com
함께 보면 좋은 글
AWS Athena 개념 및 예제
AWS Athena AWS Athena는 서버리스 쿼리 서비스로, 대량의 데이터를 신속하고 간편하게 분석할 수 있는 도구입니다. 이 서비스를 통해 서버 설정이나 관리 없이 데이터를 쉽게 탐색하고 분석할 수 있
dev-records.tistory.com
'Language > Python' 카테고리의 다른 글
[Python] 파이썬 csv 파일 parquet 파일로 변환 (2) | 2023.06.18 |
---|---|
[Python] 파이썬의 제어문(if문, for문, ...) (0) | 2023.05.12 |
[Python] 파이썬 가상환경 (0) | 2023.05.11 |
[Python] 파이썬 3.10 새로운 기능 (0) | 2023.05.10 |
[Python] 딕셔너리(Dictionary) 자료형 (0) | 2023.05.08 |
댓글