diff options
| author | Jan Tuomi <jan@jantuomi.fi> | 2025-07-19 10:42:15 +0300 |
|---|---|---|
| committer | Jan Tuomi <jan@jantuomi.fi> | 2025-07-19 10:42:15 +0300 |
| commit | 5a636abf7e98a5687811167917d0e07103599bc8 (patch) | |
| tree | 682f8d70d194c6bf02b750780f05689fcb83ba5a /telepot/filtering.py | |
| parent | e1ae18d1bc9e26f8ab817ca1c1e4e271badf02ad (diff) | |
Vendor the unmaintained telepot dependency
Diffstat (limited to 'telepot/filtering.py')
| -rw-r--r-- | telepot/filtering.py | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/telepot/filtering.py b/telepot/filtering.py new file mode 100644 index 0000000..52ed749 --- /dev/null +++ b/telepot/filtering.py @@ -0,0 +1,34 @@ +def pick(obj, keys): + def pick1(k): + if type(obj) is dict: + return obj[k] + else: + return getattr(obj, k) + + if isinstance(keys, list): + return [pick1(k) for k in keys] + else: + return pick1(keys) + +def match(data, template): + if isinstance(template, dict) and isinstance(data, dict): + def pick_and_match(kv): + template_key, template_value = kv + if hasattr(template_key, 'search'): # regex + data_keys = list(filter(template_key.search, data.keys())) + if not data_keys: + return False + elif template_key in data: + data_keys = [template_key] + else: + return False + return any(map(lambda data_value: match(data_value, template_value), pick(data, data_keys))) + + return all(map(pick_and_match, template.items())) + elif callable(template): + return template(data) + else: + return data == template + +def match_all(msg, templates): + return all(map(lambda t: match(msg, t), templates)) |
