diff --git a/cloudbot/util/text.py b/cloudbot/util/text.py new file mode 100644 index 000000000..5ff7d00e3 --- /dev/null +++ b/cloudbot/util/text.py @@ -0,0 +1,49 @@ +from typing import Optional + +__all__ = ('parse_bool',) + +_STR_TO_BOOL = { + "yes": True, + "y": True, + "no": False, + "n": False, + "on": True, + "off": False, + "enable": True, + "disable": False, + "allow": True, + "deny": False, + "true": True, + "false": False, +} + + +def parse_bool(s: str, *, fail_on_unknown: bool = True) -> Optional[bool]: + """ + Parse a string to a boolean value + + >>> parse_bool('true') + True + >>> parse_bool('yes') + True + >>> parse_bool('no') + False + >>> parse_bool('maybe', fail_on_unknown=False) + >>> parse_bool('maybe') + Traceback (most recent call last): + [...] + KeyError: 'maybe' + + :param s: The string to parse + :param fail_on_unknown: Whether to raise an error if the input can't + be parsed + :return: The parsed value + """ + + try: + return _STR_TO_BOOL[s.lower()] + except KeyError: + if fail_on_unknown: + raise + + return None diff --git a/plugins/core/optout.py b/plugins/core/optout.py index 846a3c750..fc7334f4d 100644 --- a/plugins/core/optout.py +++ b/plugins/core/optout.py @@ -13,6 +13,7 @@ from cloudbot.util import database, web from cloudbot.util.formatting import gen_markdown_table from cloudbot.util.mapping import DefaultKeyFoldDict +from cloudbot.util.text import parse_bool optout_table = Table( 'optout', @@ -129,20 +130,6 @@ def clear_optout(db, conn, chan=None): return res.rowcount -_STR_TO_BOOL = { - "yes": True, - "y": True, - "no": False, - "n": False, - "on": True, - "off": False, - "enable": True, - "disable": False, - "allow": True, - "deny": False, -} - - @hook.onload def load_cache(db): new_cache = defaultdict(list) @@ -206,7 +193,7 @@ async def optout(text, event, chan, db, conn): if args: allow = args.pop(0) try: - allowed = _STR_TO_BOOL[allow.lower()] + allowed = parse_bool(allow) except KeyError: return "Invalid allow option."