forked from Kolaru/Kaml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsave_and_load.py
220 lines (154 loc) · 6.03 KB
/
save_and_load.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
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import csv
import json
import re
from collections import OrderedDict
from os.path import isfile
from utils import emit_signal, locking, logger
## Parsing
WIN_PATTERN = re.compile(r":crown: \*\*(.+)\*\* \(.+\) vs \*\*(.+)\*\* \(.+\)")
LOSS_PATTERN = re.compile(r"\*\*(.+)\*\* \(.+\) vs :crown: \*\*(.+)\*\* \(.+\)")
HALF_WIN_PATTERN = re.compile(r":crown: \*\*(.+)\*\* \(.+\) has won a match!")
HALF_LOSS_PATTERN = re.compile(r"\*\*(.+)\*\* \(.+\) has lost a match.")
MENTION_PATTERN = re.compile(r"<@(.+)>")
def clean_name(s):
if s is None:
return None
return s.strip().replace(",", "_").replace("\n", " ")
"""
parse_matchboard_msg(msg)
Parse a message on the matchboard, return the result as the tuple `winner, loser` or `None`
if winner and loser can not be determined (e.g. messages with only one name).
"""
def parse_matchboard_msg(msg):
if len(msg.embeds) == 0:
return None
logger.debug(msg.embeds[0].to_dict())
winner, loser = None, None
result = msg.embeds[0].description
m = re.match(WIN_PATTERN, result)
if m is not None:
winner, loser = m.group(1, 2)
else:
m = re.match(LOSS_PATTERN, result)
if m is not None:
winner, loser = m.group(2, 1)
if winner is None:
m = re.match(HALF_WIN_PATTERN, result)
if m is not None:
winner = m.group(1)
if loser is None:
m = re.match(HALF_LOSS_PATTERN, result)
if m is not None:
loser = m.group(1)
# Strip comma from game names to avoid messing the csv
winner = clean_name(winner)
loser = clean_name(loser)
return OrderedDict(timestamp=msg.created_at.timestamp(),
id=msg.id,
winner=winner,
loser=loser)
def parse_mention_to_id(mention):
m = re.match(MENTION_PATTERN, mention)
if m is None:
return None
return int(m.group(1))
## File reading/writing
async def fetch_game_results(matchboard, after=None):
game_results = []
history = matchboard.history(oldest_first=True,
after=after,
limit=None)
async for msg in history:
game = parse_matchboard_msg(msg)
if game is None:
continue
game_results.append(game)
return game_results
async def get_game_results(matchboard):
# First retrieve saved games.
loaded_results = await load_game_results()
if len(loaded_results) > 0:
last_id = int(loaded_results[-1]["id"])
last_message = await matchboard.fetch_message(last_id)
else:
last_message = None
# Second fetch messages not yet saved from the matchboard.
# New results are directly saved.
logger.info("Fetching missing results from matchboard.")
fetched_game_results = await fetch_game_results(matchboard, after=last_message)
logger.info(f"{len(fetched_game_results)} new results fetched from matchboard.")
await save_games(fetched_game_results)
return loaded_results + fetched_game_results
"""
game_results_writer(file)
Return a `Writer` for game results for a given file.
Using this ensure consistent formatting of the results.
"""
def game_results_writer(file):
return csv.DictWriter(file, fieldnames=["timestamp", "id", "winner", "loser"])
@locking("alias.txt")
async def load_alias_tables():
alias_to_id = dict()
id_to_aliases = dict()
try:
logger.info("Fetching saved alias table.")
with open("aliases.csv", "r", encoding="utf-8") as file:
for line in file:
player_id, *aliases = line.split(",")
player_id = int(player_id)
if isinstance(aliases, str):
aliases = [aliases]
aliases = [alias.strip() for alias in aliases]
id_to_aliases[player_id] = set(aliases)
for alias in aliases:
alias_to_id[alias] = player_id
except FileNotFoundError:
logger.warning("No saved alias table found.")
return dict(), dict()
return alias_to_id, id_to_aliases
@locking("raw_results.csv")
async def load_game_results():
try:
logger.info("Retrieving saved games.")
with open("raw_results.csv", "r", encoding="utf-8", newline="") as file:
game_results = list(csv.DictReader(file))
logger.info( f"{len(game_results)} game results retrieved from save.")
except FileNotFoundError:
logger.warning("File `raw_results.csv` not found, creating a new one.")
with open("raw_results.csv", "w", encoding="utf-8", newline="") as file:
writer = game_results_writer(file)
writer.writeheader()
game_results = []
last_message = None
return game_results
def load_messages():
with open("messages.json", "r", encoding="utf-8") as file:
messages = json.load(file)
return messages
def load_ranking_config(config_name):
with open("ranking_config.json", "r", encoding="utf-8") as file:
configs = json.load(file)
return configs[config_name]
def load_tokens():
with open("tokens.json", "r", encoding="utf-8") as file:
d = json.load(file)
return d
def save_aliases(id_to_aliases):
logger.info("Aliases file overriden.")
with open("aliases.csv", "w", encoding="utf-8") as file:
for discord_id, aliases in id_to_aliases.items():
aliases = [clean_name(aliase) for aliase in aliases]
file.write('{},{}\n'.format(discord_id, ','.join(aliases)))
@locking("raw_results.csv")
async def save_games(games):
with open("raw_results.csv", "a",
encoding="utf-8", newline="") as file:
writer = game_results_writer(file)
for game in games:
writer.writerow(game)
@locking("raw_results.csv")
async def save_single_game(game):
with open("raw_results.csv", "a",
encoding="utf-8", newline="") as file:
writer = game_results_writer(file)
writer.writerow(game)