Added filter for msgtype

This commit is contained in:
2026-09-12 20:08:27 +03:00
parent 31fbcb4697
commit 4f0792b9aa
2 changed files with 37 additions and 1 deletions

View File

@@ -1,11 +1,36 @@
import traceback import traceback
from .base import BaseEventFilter, EventTypeFilter from .base import BaseEventFilter, EventTypeFilter
from ..types import MessageType
from nio import AsyncClient from nio import AsyncClient
from nio import MatrixRoom, Event from nio import MatrixRoom, Event
from nio import RedactionEvent 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): class NewMessageFilter(BaseEventFilter):
""" """
This filter returns True if the event is a new message. Most filters are This filter returns True if the event is a new message. Most filters are

View File

@@ -2,6 +2,7 @@
from pathlib import Path from pathlib import Path
from dataclasses import dataclass from dataclasses import dataclass
from enum import Enum
from nio import MatrixRoom, Event from nio import MatrixRoom, Event
from nio import UploadResponse from nio import UploadResponse
@@ -97,4 +98,14 @@ class UploadResult:
"""Name of the uploaded file""" """Name of the uploaded file"""
filesize: int filesize: int
"""Size of uploaded 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"