From 2bef9ec611ea004c27769888eabf4a477b36b733 Mon Sep 17 00:00:00 2001 From: Joey Hines Date: Mon, 13 May 2019 13:02:29 -0500 Subject: [PATCH] Formatting commands now scrubs for discord formatting + format_message scrubs for markdown characters and mentions and escapes them --- GeoffreyBot/GeoffreyApiHelper.py | 40 ++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/GeoffreyBot/GeoffreyApiHelper.py b/GeoffreyBot/GeoffreyApiHelper.py index 5d120bc..666a5e6 100644 --- a/GeoffreyBot/GeoffreyApiHelper.py +++ b/GeoffreyBot/GeoffreyApiHelper.py @@ -1,23 +1,43 @@ +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)", "@\u200B", arg) + string_format_args.append(arg) + + msg = msg_format.format(*string_format_args) + + return msg + + def formatted_item_listing(item): - return "{} {} for {}D".format(item["amount"], item["item_name"], item["price"]) + return format_message("{} {} for {}D", item["amount"], item["item_name"], item["price"]) def formatted_location(location): if location["tunnel"] is not None: - tunnel = "**{}** ".format(location["tunnel"]) + return format_message("**{}** @ **{}** **{}** {}", location["name"], formatted_position(location), + location["tunnel"], + formatted_owners(location)) else: - tunnel = "" - - return '**{}** @ **{}** {}{}'.format(location["name"], formatted_position(location), tunnel, - formatted_owners(location)) + return format_message("**{}** @ **{}** {}", location["name"], formatted_position(location), formatted_owners(location)) def formatted_tunnel(tunnel): - return '**{} {}**: {}'.format(tunnel["tunnel_direction"], tunnel["tunnel_number"], tunnel["location_name"]) + return format_message('**{} {}**: {}', tunnel["tunnel_direction"], tunnel["tunnel_number"], tunnel["location_name"]) def formatted_position(location): - return '(x={}, z={})'.format(location["x_coord"], location["z_coord"]) + return format_message('(x={}, z={})', location["x_coord"], location["z_coord"]) def formatted_shop(shop, base_url): @@ -79,10 +99,10 @@ def formatted_owners(location): if "owner" in location: if len(location["owner"]) == 1: - owner_list = 'Owner: **{}**' + owner_list = 'Owner: {}' owner_list = owner_list.format(location["owner"][0]["name"]) else: - owner_list = 'Owners: **{}**' + owner_list = 'Owners: {}' owners = location["owner"][0]["name"] for owner in location["owner"][1:3]: