# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """Which messages count toward the daily tally, and which chats we listen to.""" from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from signal_bot.discovery import GroupDirectory from signal_bot.models import IncomingMessage def watched_group(message: IncomingMessage, directory: GroupDirectory) -> str | None: """Return the canonical id of the watched group a message came from. The bot answers in every group it has been added to, and in nothing else. Direct messages are rejected here by an explicit lookup rather than a falsy check: a DM carries no group id at all, and one must never reach a handler no matter how the surrounding code is later rearranged. It returns the id rather than a bool so that the gate and the reply router are the same decision. Answering "may this run?" and "where does the answer go?" separately is how a bot ends up replying to the wrong group. Args: message: The parsed inbound message. directory: The live set of groups the bot is a member of. Returns: The canonical group id, or None for a direct message or any group the bot is not scoped to. """ if message.group_id is None: return None return directory.resolve(message.group_id) def should_count(message: IncomingMessage) -> bool: """True when a message should be recorded against its sender. A reaction is not a message -- it is an annotation on someone else's -- so it stays out. Everything a person actually sent counts, including a sticker and including a photo posted with no caption. Until 0.1.0 the last clause was ``bool(message.text)``, which silently valued a photo-only message at zero. The bot's own messages never count. ``is_own`` comes from the envelope branch rather than from comparing identities, which is what makes it hold on the frames that carry only one spelling of the account. """ if message.is_reaction or message.is_own: return False return bool(message.text) or bool(message.attachment_types) or message.has_sticker def media_kind(message: IncomingMessage) -> str: """Name the kind of media a message carries, or "" for plain text. Several different kinds in one message collapse to "mixed": the group reads a count of photos, not a taxonomy, and a message carrying a photo and a video is neither. """ if message.has_sticker and not message.attachment_types: return "sticker" kinds = {_kind_of(content_type) for content_type in message.attachment_types} if not kinds: return "" if len(kinds) > 1: return "mixed" return kinds.pop() def _kind_of(content_type: str) -> str: """Map one MIME type onto the coarse kind the group cares about.""" major, _, _ = content_type.partition("/") if major in {"image", "video", "audio"}: return major return "file"