Skip to content
Snippets Groups Projects
Verified Commit 50a8dfa1 authored by Nik | Klampfradler's avatar Nik | Klampfradler
Browse files

Allow passing regular expressions as match keys to react_room_messages

Also, make string matches case-insensitive
parent 704b37e7
No related branches found
No related tags found
No related merge requests found
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
# limitations under the License. # limitations under the License.
import ntptime import ntptime
import re
import urequests import urequests
from urllib.parse import urljoin from urllib.parse import urljoin
...@@ -133,23 +134,32 @@ class Matrix: ...@@ -133,23 +134,32 @@ class Matrix:
def react_room_messages(self, room, cases): def react_room_messages(self, room, cases):
"""Get room messages and trigger callbacks. """Get room messages and trigger callbacks.
The cases argument takes a dictionary mapping strings to callables. All received messages The cases argument takes a dictionary mapping strings or compiled regexs to callables.
are compared to the keys, and on match, the respective callable is called. All received messages are compared to the keys, and on match, the respective callable
is called. The callback is passed the matching message as only argument.
The get_room_messages method is called with default values, resulting in this method always The get_room_messages method is called with default values, resulting in this method always
reacting to new messages since its last call. reacting to new messages since its last call.
The method returns True if any case matched; False if not. The method returns a list of all matched messages.
""" """
data = self.get_room_messages(room) data = self.get_room_messages(room)
matches = []
for event in data.get("chunk", []): for event in data.get("chunk", []):
if event["type"] == "m.room.message" and event["content"]["msgtype"] == "m.text": if event["type"] == "m.room.message" and event["content"]["msgtype"] == "m.text":
f = cases.get(event["content"]["body"], None) message = event["content"]["body"]
if f is not None: for key_, func in cases.items():
f() if isinstance(key_, str):
return True if message.lower().strip() == key_.lower().strip():
return False matches.append(message)
func(message)
elif isinstance(key_, re.Pattern):
if key_.match(message):
matches.append(message)
func(message)
return matches
def react_dm_messages(self, mxid, cases): def react_dm_messages(self, mxid, cases):
"""Get DM messages and trigger callbacks.""" """Get DM messages and trigger callbacks."""
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment