From 269d86e89c8611cf88a098762d1f3552c87360bb Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Fri, 15 Mar 2019 14:38:16 +0100 Subject: [PATCH] Tweak a bit the ship command --- royalnet/commands/ship.py | 15 +++++++++------ royalnet/utils/__init__.py | 3 ++- royalnet/utils/safeformat.py | 13 +++++++++++++ 3 files changed, 24 insertions(+), 7 deletions(-) create mode 100644 royalnet/utils/safeformat.py diff --git a/royalnet/commands/ship.py b/royalnet/commands/ship.py index d0451a66..dc5e06d2 100644 --- a/royalnet/commands/ship.py +++ b/royalnet/commands/ship.py @@ -1,6 +1,5 @@ import re -from ..utils import Command, Call - +from ..utils import Command, Call, safeformat SHIP_RESULT = "💕 {one} + {two} = {result}" @@ -17,17 +16,21 @@ class ShipCommand(Command): name_two = args[2] name_one = name_one.lower() name_two = name_two.lower() + # Get all letters until the first vowel, included match_one = re.search(r"^[A-Za-z][^aeiouAEIOU]*[aeiouAEIOU]?", name_one) if match_one is None: part_one = name_one[:int(len(name_one) / 2)] else: part_one = match_one.group(0) + # Get all letters from the second to last vowel, excluded match_two = re.search(r"[^aeiouAEIOU]*[aeiouAEIOU]?[A-Za-z]$", name_two) if match_two is None: part_two = name_two[int(len(name_two) / 2):] else: part_two = match_two.group(0) - mixed = part_one + part_two # TODO: find out what exceptions this could possibly raise - await call.reply(SHIP_RESULT.format(one=name_one.capitalize(), - two=name_two.capitalize(), - result=mixed.capitalize())) + # Combine the two name parts + mixed = part_one + part_two + await call.reply(safeformat(SHIP_RESULT, + one=name_one.capitalize(), + two=name_two.capitalize(), + result=mixed.capitalize())) diff --git a/royalnet/utils/__init__.py b/royalnet/utils/__init__.py index d55b5717..f752aa98 100644 --- a/royalnet/utils/__init__.py +++ b/royalnet/utils/__init__.py @@ -1,5 +1,6 @@ from .asyncify import asyncify from .call import Call from .command import Command +from .safeformat import safeformat -__all__ = ["asyncify", "Call", "Command"] +__all__ = ["asyncify", "Call", "Command", "safeformat"] diff --git a/royalnet/utils/safeformat.py b/royalnet/utils/safeformat.py new file mode 100644 index 00000000..4c4ff921 --- /dev/null +++ b/royalnet/utils/safeformat.py @@ -0,0 +1,13 @@ +class SafeDict(dict): + def __missing__(self, key): + return "{" + key + "}" + + +def safeformat(string: str, ignore_escaping: bool = False, **words: str) -> str: + if ignore_escaping: + escaped = words + else: + escaped = {} + for key in words: + escaped[key] = str(words[key]).replace("<", "<").replace(">", ">") + return string.format_map(SafeDict(**escaped))