瀏覽統計
Post

Accessing the CR API using Python

GitHub last commit Github Created At GitHub Release GitHub License

Users must obtain the corresponding API key to use. Please go to Official Document
If you like my project, please consider giving it a star. GitHub

Features

  • Search Clan information
  • Search Player information
  • Search local rankings
  • Search player achievement records

Example Usage

Here are some example code samples.

More code can be found on GitHub

DEMO : https://www.youtube.com/watch?v=BKnR_kre6QI&ab_channel=XiangFang

FindClan.py

Search Clan information

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
import requests
import pandas as pd
import time

#Calculate starting time
start_time = time.time()

# Enter your key
# Go to https://developer.clashroyale.com/#/ 

API_KEY = ""
headers = {
    "Authorization": "Bearer {}".format(API_KEY)
}

# GET ClanTag
#ex: %23QCRY22P8

clan_tag = "%23QCRY22P8"


url = "https://api.clashroyale.com/v1/clans/{}".format(clan_tag)
response = requests.get(url, headers=headers)


try:
    if response.status_code == 200:
        clan = response.json()

        df = pd.DataFrame(clan["memberList"])
        df.to_excel("FindClan.xlsx")

        
        end_time = time.time()
        
        print(f"Time:{end_time - start_time}")
    else:
        print(response.status_code)
except Exception as e:
    print(e)

Player.py

Search Player information

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
import openpyxl
import requests
import json
import time
from tqdm import tqdm

#Calculate starting time
start_time = time.time()

# Enter your key
# Go to https://developer.clashroyale.com/#/ 
API_KEY = ""

headers = {
    "Authorization": "Bearer {}".format(API_KEY)
}

# enter your tag
# ex: '%2322R920J00','%2312345678'

player_tags = ["%2322R920J00", "%23V99082R9C"]



wb = openpyxl.Workbook()
ws = wb.active

ws["A1"] = "Tag"
ws["B1"] = "BEST"
ws["C1"] = "LAST"


def clean_result(result):
    if result is None:
        return ""
    return result[result.rfind(" ") + 1:].split("}")[0]
#ex:
#   best = json.dumps(player_data.get("bestPathOfLegendSeasonResult"))
#   回傳值為{"leagueNumber": 10, "trophies": 2416, "rank": 2573}
#
#   另 best2 = clean_result(best)
#   則 best2 = 2573

for player_tag in tqdm(player_tags):

    response = requests.get(f"https://api.clashroyale.com/v1/players/{player_tag}", headers=headers)
    
    player_data = response.json()

    best = json.dumps(player_data.get("bestPathOfLegendSeasonResult"))
    last = json.dumps(player_data.get("lastPathOfLegendSeasonResult"))

    best2 = clean_result(best)
    last2= clean_result(last)

    ws.append([
    player_data["name"],
    best2,
    last2])

wb.save("Player.xlsx")

#Calculate end time
end_time = time.time()
print(f"Time:{end_time - start_time}")

LocalRanking

Search local rankings

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
import requests
import openpyxl
import datetime
import time
from tqdm import tqdm

#Calculate starting time
start_time = time.time()

#Enter your key
#Go to https://developer.clashroyale.com/#/ 

API_KEY = ""
headers = {
    "Authorization": "Bearer {}".format(API_KEY)
}

response = requests.get(
    "https://api.clashroyale.com/v1/locations/57000228/pathoflegend/players",
    headers=headers,
)

#How do I know my area code? ex:57000228
#Check Area Code File

#Get Time
now = datetime.datetime.now()
now_str = now.strftime("%Y-%m-%d")

wb = openpyxl.Workbook() 
ws = wb.active

ws.cell(row=1, column=1).value = "ID"
ws.cell(row=1, column=2).value = "Name"
ws.cell(row=1, column=3).value = "Rating"

row_number = 2
for player in tqdm(response.json()["items"]):
    ws.cell(row=row_number, column=1).value = player["tag"]
    ws.cell(row=row_number, column=2).value = player["name"]
    ws.cell(row=row_number, column=3).value = player["eloRating"]
    row_number += 1

wb.save(now_str+".xlsx")

#Calculate end time
end_time = time.time()
print(f"Time:{end_time - start_time}")

PlayerProfile

Search player achievement records

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
import openpyxl
import requests
import time
from tqdm import tqdm

#Calculate starting time
start_time = time.time()

#Enter your key
#Go to https://developer.clashroyale.com/#/ 

API_KEY = ""
headers = {
    "Authorization": "Bearer {}".format(API_KEY)
}

#Enter your tag
#ex: '%2322R920J00','%2312345678'

player_tags = ['%2322R920J00']
              
wb = openpyxl.Workbook()
ws = wb.active

ws["A1"] = "Tag"
ws["B1"] = "Classic12Wins"
ws["C1"] = "Grand12Wins"
ws["D1"] = "YearsPlayed"
ws["E1"] = "EmoteCollection"
ws["F1"] = "BannerCollection"
ws["G1"] = "starPoints"
ws["H1"] = "totalExpPoints"


for player_tag in tqdm(player_tags):
    response = requests.get(f"https://api.clashroyale.com/v1/players/{player_tag}", headers=headers)
    
    player_data = response.json()

    Classic12WinsCout =0 
    Grand12WinsCout = 0

    starPoints = player_data["starPoints"]
    totalExpPoints = player_data["totalExpPoints"]
    
    for Classic12Wins in player_data["badges"]:
       if Classic12Wins["name"] == "Classic12Wins":
        Classic12WinsCout = Classic12Wins["progress"]

    for Grand12Wins in player_data["badges"]:
       if Grand12Wins["name"] == "Grand12Wins":
        Grand12WinsCout = Grand12Wins["progress"]

    for YearsPlayed in player_data["badges"]:
       if YearsPlayed["name"] == "YearsPlayed":
        YearsPlayedCout = YearsPlayed["progress"]

    for EmoteCollection in player_data["badges"]:
       if EmoteCollection["name"] == "EmoteCollection":
        EmoteCollectionCout = EmoteCollection["progress"]

    for BannerCollection in player_data["badges"]:
       if BannerCollection["name"] == "BannerCollection":
        BannerCollectionCout = BannerCollection["progress"]


    # for PracticewithFriendsCout in player_data["achievements"]:
    #   if PracticewithFriendsCout["name"] == "Practice with Friends":
    #     PracticewithFriendsCoutCout = PracticewithFriendsCout["value"]

    ws.append([
    player_data["name"],Classic12WinsCout,Grand12WinsCout,YearsPlayedCout,EmoteCollectionCout,BannerCollectionCout,starPoints,totalExpPoints
    ])

wb.save("PlayerProfile.xlsx")

#Calculate end time
end_time = time.time()
print(f"Time:{end_time - start_time}")

Under development

Providing a GUI interface for a program. The following is an example.

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
import tkinter as tk
import json
import requests

def get_player_data():
    api_key = api_key_entry.get()
    player_tag = player_tag_entry.get()

    headers = {"Authorization": f"Bearer {api_key}"}
    url = f"https://api.clashroyale.com/v1/players/%23{player_tag}"

    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # Raise an exception for non-200 status codes

        player_data = response.json()
        player_name = player_data['name']
        # player_trophies = player_data['trophies']
        All_data = response.json()

        with open(player_name+".json", "w", encoding="utf-8") as f:
         json.dump(All_data, f, ensure_ascii=False)

        result_label["text"] = "檔案已儲存於預設路徑內:\n"+"檔名為"+f"{player_name}"+".json"
    except requests.exceptions.RequestException as e:
        result_label["text"] = f"Error: {e}"

root = tk.Tk()
root.title("CR Player Data")


api_key_label = tk.Label(root, text="API Key:")
api_key_entry = tk.Entry(root)

player_tag_label = tk.Label(root, text="Player Tag:")
player_tag_entry = tk.Entry(root)

get_data_button = tk.Button(root, text="Get Data", command=get_player_data)

result_label = tk.Label(root, text="")

api_key_label.grid(row=0, column=0,padx=10,sticky=tk.W)
api_key_entry.grid(row=0, column=1,padx=8,pady=10)

player_tag_label.grid(row=1, column=0,sticky=tk.W)
player_tag_entry.grid(row=1, column=1,pady=10)

get_data_button.grid(row=2,pady=10)
result_label.grid(row=3, columnspan=2)

# 2024/2/25新增
doc = tk.Label(root, text="https://developer.clashroyale.com/#/")
doc.grid(row=4, column=1)

# 介面置中以及大小設置
window_width = root.winfo_screenwidth()    # 取得螢幕寬度
window_height = root.winfo_screenheight()  # 取得螢幕高度

width = 300
height = 200
left = int((window_width - width)/2)       # 計算左上 x 座標
top = int((window_height - height)/2)      # 計算左上 y 座標
root.geometry(f'{width}x{height}+{left}+{top}')
root.mainloop()

License

This work is open source under the MIT License.

This post is licensed under CC BY 4.0 by the author.