Skip to content

Instantly share code, notes, and snippets.

@Yasuhisa
Created January 5, 2019 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yasuhisa/c29fb536bda48bc4f7f94dbd2a8fcf44 to your computer and use it in GitHub Desktop.
Save Yasuhisa/c29fb536bda48bc4f7f94dbd2a8fcf44 to your computer and use it in GitHub Desktop.
Python Code: Record clan war log to Google SpreadSheet from Clash Royale API.
import requests
import json
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
TOKEN = '{Your Clash Royale API Key}' # クラロワ API キー
URL = 'https://api.clashroyale.com/v1'
SCOPES = 'https://www.googleapis.com/auth/spreadsheets' # read/write
SPREADSHEET_ID = '{Your Spreadsheet ID}' # スプレッドシートの ID
DEFAULT_RANGE = '{Your Spreadsheet target rect}' # セルの集計対象範囲(「:」前後の矩形選択)
LAST_LOGGED_CELL = '{Your Spreadsheet CreatedDate cell identity}' # 最終更新日時セル
VALUE_INPUT_OPTION = 'RAW' # RAW 固定
NAME_COL = 0 # スプレッドシート A 列
WIN_COL = 1 # スプレッドシート B 列
LOSE_COL = 2 # スプレッドシート C 列
sheet = None
def get_current_clan_battle_results():
"""クラロワ API クラン対戦データを取得
実行するためには事前にクラロワ API の API キーを `TOKEN` にセットする必要があります。
Returns:
List -- クラン対戦結果
See Also:
My Keys -- https://developer.clashroyale.com/#/account
GET /clans/{clanTag}/warlog -- https://developer.clashroyale.com/#/documentation
"""
endpoint = URL + "/clans/{your_clan_tag(need '#' to encode URL string '%23'}/warlog"
headers = {
"content-type": "application/json; charset=utf-8",
"cache-control": "max-age=60",
"authorization": "Bearer %s" % TOKEN
}
response = requests.get(endpoint, headers=headers)
results = response.json()
return results
def get_spreadsheet():
"""Google スプレッドシートを取得
実行するためには事前に実行環境のルートディレクトリに「token.json」、および「credentials.json」を配置する必要があります。
Raises:
Exception -- スプレッドシートが取得できない場合
Returns:
Spreadsheet -- https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets?hl=ja#Spreadsheet
See Also:
Python Quickstart -- https://developers.google.com/sheets/api/quickstart/python
"""
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))
sheet = service.spreadsheets()
if not sheet:
raise Exception('スプレッドシートが正常に取得できませんでした。')
return sheet
def get_sheetvalues_by_range(range):
"""スプレッドシートの指定した範囲を取得
Parameters:
range {string} -- セルの取得範囲。指定のセル番号(ex, A1)もしくは、「:」区切りのセル範囲(ex, A1:B2、矩形選択)を指定する。
Raises:
ValueError -- range の指定がない場合
Returns:
spreadsheets.values -- https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values?hl=ja
"""
if not range:
raise ValueError('範囲を設定してください')
return sheet.values().get(spreadsheetId=SPREADSHEET_ID, range=range).execute()
def update_area(batch_update_values_request):
"""スプレッドシートの範囲を更新する
Arguments:
batch_update_values_request {BatchUpdateValuesRequest} -- https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/batchUpdate?hl=ja#request-body
Raises:
ValueError -- batch_update_values_request の指定がない場合
See Also:
POST spreadsheets.values.batchUpdate -- https://developers.google.com/sheets/guides/values?hl=ja#_8
"""
if not batch_update_values_request:
raise ValueError('batch_update_values_request を指定してください')
body = {
'valueInputOption': VALUE_INPUT_OPTION,
'data': batch_update_values_request
}
sheet.values().batchUpdate(spreadsheetId=SPREADSHEET_ID, body=body).execute()
def update_battle_resutls():
"""
クラロワ API のクラン対戦取得結果でスプレッドシートの最終更新日時より新しい記録があれば、スプレッドシートの戦績を更新する。
"""
global sheet
sheet = get_spreadsheet()
# スプレッドシート情報を取得
last_logged_cell = get_sheetvalues_by_range(range=LAST_LOGGED_CELL)
# 最終記録時間を取得
last_logged_date = last_logged_cell['values'][0][0]
# クラン対戦結果を取得
battle_results = get_current_clan_battle_results()
items = battle_results['items']
# クラン対戦結果を createdDate(対戦履歴)順に昇順ソート
sorted_items = sorted(items, key=lambda items: items['createdDate'])
for item in sorted_items:
created_date = item['createdDate']
# クラロワ API で取得した最終更新日時(createdDate)がスプレッドシートの記録以前のものであったら処理しない
if created_date <= last_logged_date:
continue
# クラロワ API クラン対戦参加者情報
participants = item['participants']
# スプレッドシートセル情報
values = get_sheetvalues_by_range(range=DEFAULT_RANGE)['values']
for participant in participants:
participant_name = participant['name']
for value in values:
cell_name = value[NAME_COL]
# クラン対戦参加者名とスプレッドシートの名前列が一致するかどうか
if participant_name == cell_name:
win_count = participant['wins']
# 対戦結果勝ち数を追加
value[WIN_COL] = str(int(value[WIN_COL]) + win_count)
# 対戦結果負け数を追加 (試合数 - 勝数)
value[LOSE_COL] = str(int(value[LOSE_COL]) + participant['battlesPlayed'] - win_count)
# スプレッドシート API の `BatchUpdateValuesRequest` オブジェクト
batch_update_values_request = [
{
'range': LAST_LOGGED_CELL,
'values': [[created_date]]
},
{
'range': DEFAULT_RANGE,
'values': values
},
]
# LAST_LOGGED_CELL の最終更新日時(createdDate)、クラン対戦結果を更新
update_area(batch_update_values_request)
if __name__ == '__main__':
update_battle_resutls()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment