From aaa3df20d390f38632bfb73e5b898a7b94eea61f Mon Sep 17 00:00:00 2001 From: David Lev Date: Wed, 29 Nov 2023 00:56:33 +0200 Subject: [PATCH] [filters] adding new filter called `sent_to` to filter updates even if `WhatsApp(..., filter_updates=False)` --- .../source/content/filters/common_filters.rst | 1 + pywa/filters.py | 22 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/docs/source/content/filters/common_filters.rst b/docs/source/content/filters/common_filters.rst index 5045ad55..83bae324 100644 --- a/docs/source/content/filters/common_filters.rst +++ b/docs/source/content/filters/common_filters.rst @@ -6,5 +6,6 @@ Common filters .. autofunction:: all_ .. autofunction:: any_ .. autofunction:: not_ +.. autofunction:: sent_to .. autofunction:: from_users .. autofunction:: from_countries diff --git a/pywa/filters.py b/pywa/filters.py index 8cfe8301..5177ed1c 100644 --- a/pywa/filters.py +++ b/pywa/filters.py @@ -9,6 +9,7 @@ "forwarded_many_times", "reply", "has_referred_product", + "sent_to", "from_users", "from_countries", "text", @@ -109,6 +110,27 @@ def not_(fil: Callable[[_Wa, _T], bool]) -> Callable[[_Wa, _T], bool]: return lambda wa, m: not fil(wa, m) +def sent_to(*, display_phone_number: str = None, phone_number_id: str = None): + """ + Filter for updates that are sent to the given phone number. + + - Use this filter when you choose not filter updates (e.g. ``WhatsApp(..., filter_updates=False)``) so you can still filter for messages that are sent to specific phone numbers. + + + >>> sent_to(display_phone_number="+1 555-555-5555") + >>> sent_to(phone_number_id="123456789") + """ + if not (display_phone_number or phone_number_id): + raise ValueError( + "You must provide either display_phone_number or phone_number_id" + ) + return lambda _, m: ( + m.metadata.display_phone_number == display_phone_number + if display_phone_number + else m.metadata.phone_number_id == phone_number_id + ) + + def from_users( *numbers: str, ) -> _MessageFilterT | _CallbackFilterT | _MessageStatusFilterT: