Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions src/botc_tokens/commands/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ def run():
overall_task = overall_progress.add_task("Creating Tokens...", total=len(roles))
step_task = step_progress.add_task("Reading roles...")
for role in roles:
role_slug = ''.join(e for e in role.name.lower() if e.isalnum())
role_base = role.id if role.id is not None else role.name
role_slug = ''.join(e for e in role_base.lower() if e.isalnum())
step_progress.update(step_task, description=f"Creating Token for: {role.name}")
# Make sure our target directory exists
role_output_path = output_path / str(role.home_script) / str(role.type)
Expand All @@ -98,7 +99,7 @@ def run():
reminder_icon.transform(resize=f"{target_width}x{target_height}")
for reminder_text in role.reminders:
step_progress.update(step_task, description=f"Creating Token for: {role.name}")
reminder_name = format_filename(f"{role_slug}-Reminder-{reminder_text}")
reminder_name = role_slug + format_filename(f"-Reminder-{reminder_text}")
reminder_output_path = role_output_path / f"{reminder_name}.png"
duplicate_counter = 1
while reminder_output_path.exists():
Expand Down Expand Up @@ -135,8 +136,8 @@ def load_components(component_package):
print(f"\n[red]Error:[/][bold] Could not load component: {str(e)}[/]")
return None
except BadZipFile:
print(f"\n[red]Error:[/][bold] Could not load components from '{component_package}' it does not appear to be a "
"valid components package.[/]")
print(f"\n[red]Error:[/][bold] Could not load components from '{component_package}' it does not appear"
" to be a \nvalid components package.[/]")
return None
except FileNotFoundError as e:
print(f"\n[red]Error:[/][bold] Unable to load components from '{component_package}': {str(e)}")
Expand All @@ -155,7 +156,7 @@ def find_roles_from_json(json_files):
icon = data.get('icon')
if icon:
data['icon'] = str(json_file.parent / str(data.get('icon')))
role = Role(data.get('name', "Unknown"))
role = Role(id=data.get('id'), name=data.get('name', "Unknown"))
for att in dir(role):
if att in data:
setattr(role, att, data[att])
Expand Down
53 changes: 34 additions & 19 deletions src/botc_tokens/commands/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def _parse_args():
parser.add_argument('--reminders', type=str,
help="JSON file to override reminder guesses from the wiki.")
parser.add_argument('-c', '--custom-list', type=str, default=None,
help="JSON file with a custom list of roles to update.")
help="Local or web hosted JSON file with a custom list of roles to update.")
parser.add_argument('--use-playtest', action='store_true',
help="Use the playtest icon source instead of the wiki.")
args = parser.parse_args(sys.argv[2:])
Expand Down Expand Up @@ -127,7 +127,7 @@ def run():

if found_role is not None:
# Check if the role is in our forced_setup list
if found_role.name.lower() in forced_setup:
if found_role.id.lower() in forced_setup:
found_role.affects_setup = True

# Write it out
Expand All @@ -150,19 +150,22 @@ def prep_wiki(script_filter, custom_list=None):
# Gather the requested role data
wiki = WikiSoup(script_filter)
if custom_list:
custom_list_path = Path(custom_list)
if not custom_list_path.exists():
print(f"[red]Error:[/] Could not find '{custom_list}'")
return None
with open(custom_list_path, "r") as f:
custom_list = json.load(f)
try:
validate(custom_list, json.load(open(data_dir / "role_schema.json")))
except ValidationError as e:
print(f"[yellow]Warning:[/] The custom json specified does not fit the copy of the TPI schema that I "
f"have. Specifically: {e}"
f"\n\nI will continue, but [yellow]be warned that it might not work[/].")
wiki.role_data = custom_list
if custom_list.startswith("https://"):
wiki.load_from_web_json(custom_list)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should still apply validation whether using local files or URLs. Right now it is being bypassed when using URLs.

else:
custom_list_path = Path(custom_list)
if not custom_list_path.exists():
print(f"[red]Error:[/] Could not find '{custom_list}'")
return None
with open(custom_list_path, "r") as f:
custom_list = json.load(f)
wiki.role_data = custom_list
try:
validate(wiki.role_data, json.load(open(data_dir / "role_schema.json")))
except ValidationError as e:
print(f"[yellow]Warning:[/] The custom json specified does not fit the copy of the TPI schema that I "
f"have. Specifically: {e}"
f"\n\nI will continue, but [yellow]be warned that it might not work[/].")
else:
# Download the official lists from the script tool
wiki.load_from_web()
Expand All @@ -182,7 +185,8 @@ def process_role(role, file, wiki, step_progress, step_task, role_output_path, u
use_playtest (bool): Whether to use the playtest icon source instead of the wiki.
"""
name = role['name']
found_role = Role(name=name)
role_id = role['id']
found_role = Role(id=role_id, name=name)

# Check if we have a json file for the role
if file.exists():
Expand All @@ -208,12 +212,12 @@ def process_role(role, file, wiki, step_progress, step_task, role_output_path, u
found_role.reminders = get_role_reminders(name, wiki)

# Determine night actions
if role.get("firstNight"):
if role.get("firstNight") or has_value(role.get("firstNightReminder")):
found_role.first_night = True
else:
found_role.first_night = True if role['id'] in wiki.night_data['firstNight'] else False

if role.get("otherNight"):
if role.get("otherNight") or has_value(role.get("otherNightReminder")):
found_role.other_nights = True
else:
found_role.other_nights = True if role['id'] in wiki.night_data['otherNight'] else False
Expand All @@ -240,6 +244,17 @@ def process_role(role, file, wiki, step_progress, step_task, role_output_path, u
return found_role


def has_value(value):
"""Checks if the provided value is a non-empty string.

Args:
value (str): The value to be checked.
"""
if isinstance(value, str):
return len(value) > 0
return False


def get_role_icon(found_role, role, role_output_path, wiki, use_playtest=False):
"""Get the icon for a role, using the wiki if needed.

Expand Down Expand Up @@ -274,7 +289,7 @@ def get_role_icon(found_role, role, role_output_path, wiki, use_playtest=False):
print(f"[red]Error:[/] No icon found for {found_role.name}: {str(e)}")
return
icon_url = urllib.parse.urljoin("https://wiki.bloodontheclocktower.com", icon_url)
icon_path = role_output_path / f"{format_filename(found_role.name)}{Path(icon_url).suffix}"
icon_path = role_output_path / f"{format_filename(found_role.id)}{Path(icon_url).suffix}"
icon_path.parent.mkdir(parents=True, exist_ok=True)
if not save_icon(found_role, icon_path, icon_url):
return
Expand Down
2 changes: 2 additions & 0 deletions src/botc_tokens/helpers/role.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ class Role:
"""A role in a script.

Attributes:
id: The id of the role.
name: The name of the role.
ability: The description of the role.
type: The type of the role (Townsfolk, Outsider, Minion, Demon, or Traveller).
Expand All @@ -16,6 +17,7 @@ class Role:
icon: The filename of the icon.
home_script: The name of the script in which the role is found.
"""
id: str
name: str
ability: str = None
type: str = None
Expand Down
17 changes: 17 additions & 0 deletions src/botc_tokens/helpers/wiki_soup.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,23 @@ def load_from_web(self):
night_from_web = urlopen("https://script.bloodontheclocktower.com/data/nightsheet.json").read().decode('utf-8')
self.night_data = json.loads(night_from_web)

def load_from_web_json(self, custom_url):
"""Load the role data from the provided web hosted JSON file."""
roles_from_web_json = json.loads(urlopen(custom_url).read().decode('utf-8'))
meta_data = next((item for item in roles_from_web_json if item.get('id') == '_meta'), None)
version_name = None
if meta_data:
version_name = meta_data.get('name')
# Filter and convert the roles
roles_with_version = []
for role in roles_from_web_json:
if role.get('id') != '_meta':
role['version'] = version_name if role.get('version') is None else role['version']
role['name'] = role['name']
role['ability'] = role.get('ability')
roles_with_version.append(role)
self.role_data = roles_with_version

def _get_wiki_soup(self, role_name):
"""Take a role name and return a BeautifulSoup object for the role's wiki page."""
# Check if we have already seen this role
Expand Down
Loading
Loading