/
lol_time_tracker_lambda.py
156 lines (129 loc) · 5.05 KB
/
lol_time_tracker_lambda.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import json
from datetime import datetime, timedelta
import requests, bs4, re, time
import plotly.graph_objects as go
import traceback
API_KEY = "RGAPI-c16c2668-0913-4123-9416-113f700d30f0"
HEADER = {
# "Origin": "https://developer.riotgames.com",
# "Accept-Charset": "application/x-www-form-urlencoded; charset=UTF-8",
"X-Riot-Token": API_KEY,
# "Accept-Language": "en-us",
# "User-Agent": ""
}
def get_account_id(user_name):
response = requests.get("https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" + user_name,
headers=HEADER)
if response.status_code != 200:
raise Exception("Cannot get accountID via API" + str(response.status_code) + json.dumps(response.json()))
return response.json()['accountId']
def get_match_ids(beginTime_stamp, accountId):
beginTime = str("{:.3f}".format(beginTime_stamp)).replace(".", "")
response = requests.get(
"https://na1.api.riotgames.com/lol/match/v4/matchlists/by-account/" + accountId,
params={
"beginTime": beginTime,
},
headers=HEADER)
if response.status_code == 404:
return []
if response.status_code != 200:
raise Exception("API call did not go through " + json.dumps(response.json()))
match_list = response.json()["matches"]
match_ids = [match['gameId'] for match in match_list]
return match_ids
def get_matches_data(match_ids):
resp = dict()
matches_data = {}
for match_id in match_ids:
response = requests.get("https://na1.api.riotgames.com/lol/match/v4/matches/" + str(match_id),
headers=HEADER)
while response.status_code == 429:
print('rate limited')
time.sleep(0.05)
response = requests.get("https://na1.api.riotgames.com/lol/match/v4/matches/" + str(match_id),
headers=HEADER)
resp[match_id] = response
matches_data = {match_id: match.json() for match_id, match in resp.items()}
return matches_data
def get_time_dict(matches_data, beginTime_stamp):
time_data = {}
cur_time = datetime.fromtimestamp(beginTime_stamp)
today_pt = now
while cur_time <= now + timedelta(hours=1):
cur_pt = cur_time.strftime("%Y/%m/%d")
time_data[cur_pt] = 0
cur_time += timedelta(days=1)
for match_id, match in matches_data.items():
cur_pt = datetime.fromtimestamp(match['gameCreation'] / 1000).strftime("%Y/%m/%d")
time_data[cur_pt] += match['gameDuration'] / 3600
for time, duration in time_data.items():
time_data[time] = str("{:.2f}".format(duration))
return time_data
def transform_data(time_data):
total_time_x = []
total_time_list = []
for date, total_time in sorted(time_data.items()):
total_time_x.append(date)
total_time_list.append(total_time)
return total_time_x, total_time_list
def render_data(total_time_x, total_time_list, userName, days):
fig = go.Figure(data=go.Bar(x=total_time_x, y=total_time_list, text=total_time_list,
textposition='auto', ))
fig.update_layout(
title='Amount of Hours "' + userName + '" Spends on League of Legends in the past ' + str(days) + ' days',
xaxis_tickfont_size=14,
yaxis=dict(
title='Hours',
titlefont_size=16,
tickfont_size=14,
),
)
return fig.to_html()
def lambda_handler(event, context):
try:
global user_name, days, beginTime_stamp
user_name = event['queryStringParameters']['user_name']
days = int(event['queryStringParameters']['days'])
beginTime_stamp = datetime.timestamp(now - timedelta(days=days))
print(beginTime_stamp)
except Exception as e:
return {
'statusCode': 400,
'headers': {
'Content-Type': 'text/html',
},
'body': "error in initializing"
}
try:
accountId = get_account_id(user_name)
match_ids = get_match_ids(beginTime_stamp, accountId)
matches_data = get_matches_data(match_ids)
print("here are match data " + json.dumps(matches_data))
time_data = get_time_dict(matches_data, beginTime_stamp)
print("here are the time_data" + json.dumps(time_data))
total_time_x, total_time_list = transform_data(time_data)
html = render_data(total_time_x, total_time_list, user_name, days) or "html broke"
return {
'statusCode': 200,
'headers': {
'Content-Type': 'text/html',
},
'body': html
}
except Exception as e:
return {
'statusCode': 400,
'headers': {
'Content-Type': 'text/html',
},
'body': str(traceback.format_exc())
}
try:
user_name = 'nostest'
days = 0
now = datetime.now()
beginTime_stamp = datetime.timestamp(now - timedelta(days=days))
print(beginTime_stamp)
except Exception as e:
print("error outside of main handler")