From 4f0792b9aabdfdb8480e5ad1eacaf18343a57c6e Mon Sep 17 00:00:00 2001 From: nikita Date: Sat, 12 Sep 2026 20:08:27 +0300 Subject: [PATCH] Added filter for `msgtype` --- src/mab/filters/message.py | 25 +++++++++++++++++++++++++ src/mab/types.py | 13 ++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/mab/filters/message.py b/src/mab/filters/message.py index c3f7dee..f3deaa7 100644 --- a/src/mab/filters/message.py +++ b/src/mab/filters/message.py @@ -1,11 +1,36 @@ import traceback from .base import BaseEventFilter, EventTypeFilter +from ..types import MessageType from nio import AsyncClient from nio import MatrixRoom, Event from nio import RedactionEvent +class MessageTypeFilter(BaseEventFilter): + """ + This filter should be used to match specific message types (text-only, + images, videos, files, etc) based on `event.source["content"]["msgtype"]` + value. + + `types` list is stored by reference so you may modify the behavior of this + filter dynamically. + """ + def __init__(self, types: list[MessageType] | MessageType, **kwargs): + super().__init__(**kwargs) + if isinstance(types, MessageType): + types = [types] + self._types = types + + async def __call__(self, room: MatrixRoom, event: Event, client: AsyncClient) -> bool: + if not await super().__call__(room, event, client): + return False + if "msgtype" not in event.source["content"]: + return False + return ( + event.source["content"]["msgtype"] in [t.value for t in self._types] + ) + class NewMessageFilter(BaseEventFilter): """ This filter returns True if the event is a new message. Most filters are diff --git a/src/mab/types.py b/src/mab/types.py index 21ccaf9..4597db4 100644 --- a/src/mab/types.py +++ b/src/mab/types.py @@ -2,6 +2,7 @@ from pathlib import Path from dataclasses import dataclass +from enum import Enum from nio import MatrixRoom, Event from nio import UploadResponse @@ -97,4 +98,14 @@ class UploadResult: """Name of the uploaded file""" filesize: int - """Size of uploaded file""" \ No newline at end of file + """Size of uploaded file""" + +class MessageType(Enum): + TEXT = "m.text" + EMOTE = "m.emote" + NOTICE = "m.notice" + IMAGE = "m.image" + FILE = "m.file" + AUDIO = "m.audio" + LOCATION = "m.location" + VIDEO = "m.video" \ No newline at end of file