From d04b3da7d5a8f130ad723e5f8797f314cdc072ca Mon Sep 17 00:00:00 2001 From: Lorenz Diener Date: Mon, 30 Jul 2018 22:09:14 +0200 Subject: Add filter applies function --- docs/index.rst | 1 + mastodon/Mastodon.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/docs/index.rst b/docs/index.rst index e1dc7ac..0cff37e 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -703,6 +703,7 @@ These functions allow you to get information about keyword filters. .. automethod:: Mastodon.filters .. automethod:: Mastodon.filter +.. automethod:: Mastodon.filters_apply Reading data: Follow suggestions -------------------------------- diff --git a/mastodon/Mastodon.py b/mastodon/Mastodon.py index fc5c178..4173c8c 100644 --- a/mastodon/Mastodon.py +++ b/mastodon/Mastodon.py @@ -855,7 +855,43 @@ class Mastodon: id = self.__unpack_id(id) url = '/api/v1/filters/{0}'.format(str(id)) return self.__api_request('GET', url) + + @api_version("2.4.3", "2.4.3", __DICT_VERSION_FILTER) + def filters_apply(self, objects, filters, context): + """ + Helper function: Applies a list of filters to a list of either statuses + or notifications and returns only those matched by none. This function will + apply all filters that match the context provided in `context`, i.e. + if you want to apply only notification-relevant filters, specify + 'notifications'. Valid contexts are 'home', 'notifications', 'public' and 'thread'. + """ + # Build filter regex + filter_strings = [] + for keyword_filter in filters: + if not context in keyword_filter["context"]: + continue + + filter_string = re.escape(keyword_filter["phrase"]) + if keyword_filter["whole_word"] == True: + filter_string = "\\b" + filter_string + "\\b" + filter_strings.append(filter_string) + filter_re = re.compile("|".join(filter_strings)) + return filter_re + + # Apply + filter_results = [] + for filter_object in objects: + filter_status = filter_object + if "status" in filter_object: + filter_status = filter_object["status"] + filter_text = filter_status["content"] + filter_text = re.sub("<.*?>", " ", filter_text) + filter_text = re.sub('\s+', ' ', filter_text).strip() + if not filter_re.match(filter_text): + filter_results.append(filter_object) + return filter_results + ### # Reading data: Follow suggestions ### -- cgit v1.2.3