-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchallonge.py
More file actions
executable file
·186 lines (152 loc) · 6.29 KB
/
challonge.py
File metadata and controls
executable file
·186 lines (152 loc) · 6.29 KB
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#!/usr/bin/env python3
"""This is a thin wrapper for challonge's API."""
import enum
import sys
import uuid
from dataclasses import dataclass
from typing import Tuple, List, Dict
import data
import util
CHALLONGE_API = 'https://api.challonge.com/v1'
class TourneyType(enum.Enum):
SINGLE_ELIM = 'single elimination'
DOUBLE_ELIM = 'double elimination'
ROUND_ROBIN = 'round robin'
SWISS = 'swiss'
@dataclass
class Match:
id: str
p1_id: str
p2_id: str
class Client:
def __init__(self, api_key):
self._api_key = api_key
def create_tournament(self, name, tournament_type=TourneyType.DOUBLE_ELIM, is_unlisted=True) -> Tuple[str, str]:
"""
Creates a tournament with the given name.
Returns the tournament ID and url.
"""
payload = {
'tournament': {
'name': f'{name}',
# We add unique-ish gibberish to the end to make sure that the url is available.
# The TO can always change the URL later.
'url': f'{name}_{str(uuid.uuid1()).replace("-", "_")}',
'tournament_type': tournament_type.value,
'private': is_unlisted,
}
}
resp = util.make_request(CHALLONGE_API,
'/tournaments.json',
params={'api_key': self._api_key},
data=payload,
raise_exception_on_http_error=False)
if 'tournament' not in resp:
raise ValueError(
"Bracket creation unsuccessful. Challonge returned the following error(s): \n * "
+ '\n * '.join(resp['errors']))
return resp['tournament']['id'], resp['tournament']['full_challonge_url']
def add_players(self, tourney_id, names: List[str]) -> Dict[str, str]:
"""
Adds the list of participant names to the tournament with the given tourney_id.
Returns a map of the given names to their challonge participant IDs.
"""
payload = {
'participants': [{"name": n} for n in names],
}
resp = util.make_request(
CHALLONGE_API,
f'/tournaments/{tourney_id}/participants/bulk_add.json',
params={'api_key': self._api_key},
data=payload,
raise_exception_on_http_error=True)
# Response format is a list of dicts, all with one property "participant".
# Convert into dict of players by name.
return {
p['participant']['name']: p['participant']['id']
for p in resp
}
def update_username(self, tourney_id: str, player: data.Player, name: str):
"""
Updates a player's username in challonge.
Returns true iff the user was present in the tournament.
Note that the "username" is not the display name - it is the actual
username of the account, so they can update their own scores.
"""
payload = {
'participant': {
'challonge_username': name,
}
}
util.make_request(
CHALLONGE_API,
f'/tournaments/{tourney_id}/participants/{player.challonge_id}.json',
params={'api_key': self._api_key},
data=payload,
raise_exception_on_http_error=True,
method='PUT',
)
def list_matches(self, tourney_id: str) -> List[Match]:
matches = util.make_request(CHALLONGE_API,
f'/tournaments/{tourney_id}/matches.json',
params={
'api_key': self._api_key,
'state': "open"
},
raise_exception_on_http_error=True)
# Strip out the useless envelope-ish object
# (an abject with 1 property, "match", and that's it.)
return [_to_match(m) for m in matches]
def list_player_names_by_id(self, tourney_id: str) -> Dict[str, str]:
"""
Returns a map of player IDs to player names in challonge.
Uses the official challonge username for a player if it is set.
If the challonge username is not set, returns the nickname used by that player in the bracket.
"""
player_objs = util.make_request(CHALLONGE_API,
f'/tournaments/{tourney_id}/participants.json',
{'api_key': self._api_key},
raise_exception_on_http_error=True)
names_by_id = {}
for p in player_objs:
# Each player object has only one key, 'participant',
# mapped to another object that actually has the info we want.
p = p['participant']
name = p['challonge_username'] if p['challonge_username'] else p['name']
names_by_id[p['id']] = name
return names_by_id
def set_score(self, tourney_id: str, match_id: str, p1_score: int, p2_score: int, winner_id: str):
util.make_request(CHALLONGE_API,
f'/tournaments/{tourney_id}/matches/{match_id}.json',
params={'api_key': self._api_key},
data={
'match': {
'scores_csv': f'{p1_score}-{p2_score}',
'winner_id': winner_id,
}
},
method='PUT',
raise_exception_on_http_error=True)
def _to_match(envelope):
match_obj = envelope['match']
return Match(
match_obj['id'],
match_obj['player1_id'],
match_obj['player2_id'],
)
def _test_creation():
# Create a new tournament, and add 2 dummy players to it.
auth_token = sys.argv[1]
c = Client(api_key=auth_token)
tid, url = c.create_tournament("test_tourney_please_ignore")
print(tid)
print(url)
c.add_players(tid, ["Eve", "Mallory"])
print(c.list_player_names_by_id(tid))
def _sanity_check():
auth_token = sys.argv[1]
tid = sys.argv[2]
c = Client(api_key=auth_token)
print(c.list_player_names_by_id(tid))
if __name__ == '__main__':
_sanity_check()