ForcePilot/backend/package/yuxi/channel/extensions/rocketchat/gating.py

73 lines
2.2 KiB
Python
Raw Normal View History

from __future__ import annotations
import logging
logger = logging.getLogger(__name__)
class RocketChatGating:
def __init__(self, account: dict):
self.chatmode = account.get("chatmode", "oncall")
self.onchar_prefixes = account.get("onchar_prefixes", [">", "!"])
self.require_mention = account.get("require_mention", True)
def should_respond(
self,
chat_type: str,
message_text: str,
was_mentioned: bool,
) -> tuple[bool, str]:
if chat_type == "direct":
return True, "dm_always"
if self.chatmode == "onmessage":
return True, "onmessage"
if self.chatmode == "onchar":
return self._check_onchar(message_text)
if self.chatmode == "oncall":
if was_mentioned:
return True, "mentioned"
return self._check_onchar_fallback(message_text)
return False, "unknown_chatmode"
def _check_onchar(self, text: str) -> tuple[bool, str]:
stripped = text.strip()
for prefix in self.onchar_prefixes:
if stripped.startswith(prefix):
return True, "onchar_triggered"
return False, "onchar_not_triggered"
def _check_onchar_fallback(self, text: str) -> tuple[bool, str]:
if not self.require_mention:
return True, "mention_not_required"
for prefix in self.onchar_prefixes:
if text.strip().startswith(prefix):
return True, "onchar_fallback"
return False, "missing_mention"
def was_mentioned(self, text: str, bot_user_id: str, bot_username: str | None = None) -> bool:
if bot_username:
if f"@{bot_username}" in text or bot_username in text:
return True
if bot_user_id and bot_user_id in text:
return True
return False
def extract_mentions(self, text: str) -> list[str]:
import re
usernames = re.findall(r"@(\w+)", text)
return usernames
def strip_onchar_prefix(self, text: str) -> str:
stripped = text.strip()
for prefix in self.onchar_prefixes:
if stripped.startswith(prefix):
return stripped[len(prefix) :].strip()
return text