import re def format_message(msg_format, *args): chars_to_escape = ['\\', '`', '_', '*', '|', "~"] string_format_args = [] for arg in args: arg = str(arg) for char in chars_to_escape: arg = arg.replace(char, "\\" + char) arg = re.sub(r"@(?!\s)", "\@", arg) string_format_args.append(arg) msg = msg_format.format(*string_format_args) return msg def formatted_item_listing(item): days = int(item["days_since_restock"]) if days == 0: days_stocked = "today" elif days == 1: days_stocked = "yesterday" else: days_stocked = "{} days ago".format(days) return format_message("{} {} for {}D, restocked {}", item["amount"], item["item_name"], item["price"], days_stocked) def formatted_location(location): if location["tunnel"] is not None: return format_message("**{}** @ **{}** **{}** {}", location["name"], formatted_position(location), location["tunnel"], formatted_owners(location)) else: return format_message("**{}** @ **{}** {}", location["name"], formatted_position(location), formatted_owners(location)) def formatted_tunnel(tunnel): return format_message('**{} {}**: {}', tunnel["tunnel_direction"], tunnel["tunnel_number"], tunnel["location_name"]) def formatted_position(location): return format_message('(x={}, z={})', location["x_coord"], location["z_coord"]) def formatted_shop(shop, base_url): shop_info_list = formatted_location_info(shop, base_url) if len(shop["items"]) > 0: shop_info_list.append("**Inventory:**") for item in shop["items"]: shop_info_list.append(formatted_item_listing(item)) return shop_info_list def formatted_farm(farm, base_url): farm_info_list = formatted_location_info(farm, base_url) if len(farm["resources"]) > 0: farm_info_list.append("**Produces:**") for resource in farm["resources"]: farm_info_list.append(resource["name"]) return farm_info_list def formatted_market(market, base_url): market_info_list = formatted_location_info(market, base_url) if len(market["shops"]) > 0: market_info_list.append("**Shops:**") for shop in market["shops"]: market_info_list.append(formatted_location(shop)) return market_info_list def formatted_location_info(location, base_url): info = [] info.append(formatted_location(location)) info.append(get_full_link(base_url, location["link"])) return info def formatted_town(town, base_url): town_info_list = formatted_location_info(town, base_url) if len(town["residents"]) > 0: town_info_list.append("**Residents:**") for resident in town["residents"]: town_info_list.append(resident["name"]) return town_info_list def formatted_owners(location): owner_list = '' if "owner" in location: if len(location["owner"]) == 1: owner_list = 'Owner: {}' owner_list = owner_list.format(location["owner"][0]["name"]) else: owner_list = 'Owners: {}' owners = location["owner"][0]["name"] for owner in location["owner"][1:3]: owners += ", " + owner["name"] owner_list = owner_list.format(owners) return owner_list def get_full_link(base_url, link): return base_url + link