astrbot_plugin_imagestudio/adapters/wechat_adapter.py

80 行
2.2 KiB
Python

2026-07-05 22:34:54 +08:00
"""WeChat message normalization helpers."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
2026-07-05 22:52:31 +08:00
from adapters.chat_commands import is_workbench_command, parse_chat_command
2026-07-05 22:34:54 +08:00
from backend.services.ui_service import API_BASE
@dataclass(frozen=True)
class WeChatMessage:
user_id: str
room_id: str | None
text: str
raw_event: dict[str, Any]
def to_dict(self) -> dict[str, Any]:
return {
"user_id": self.user_id,
"room_id": self.room_id,
"text": self.text,
}
def normalize_message_event(event: dict[str, Any]) -> WeChatMessage:
return WeChatMessage(
user_id=str(event.get("from_user") or event.get("user_id") or event.get("sender") or "").strip(),
room_id=_optional_text(event.get("room_id") or event.get("chatroom_id")),
text=str(event.get("text") or event.get("content") or "").strip(),
raw_event=dict(event),
)
def match_workbench_command(message: WeChatMessage) -> bool:
2026-07-05 22:48:40 +08:00
return is_workbench_command(message.text)
2026-07-05 22:34:54 +08:00
def workbench_reply(api_base: str = API_BASE) -> dict[str, Any]:
url = f"{api_base.rstrip('/')}/web"
return {
"reply_type": "text",
"text": f"ImageStudio 工作台:{url}",
"url": url,
}
def handle_message_event(event: dict[str, Any], *, api_base: str = API_BASE) -> dict[str, Any] | None:
message = normalize_message_event(event)
2026-07-05 22:52:31 +08:00
command = parse_chat_command(message.text)
if command is None:
2026-07-05 22:34:54 +08:00
return None
2026-07-05 22:52:31 +08:00
if command.action == "quick_profile":
return {
"platform": "wechat",
"action": command.action,
"payload": command.payload,
"source": message.to_dict(),
"reply": quick_profile_reply(command.payload["questionnaire"]["name"]),
}
2026-07-05 22:34:54 +08:00
return {
"platform": "wechat",
"action": "open_workbench",
"source": message.to_dict(),
"reply": workbench_reply(api_base),
}
2026-07-05 22:52:31 +08:00
def quick_profile_reply(profile_name: str) -> dict[str, Any]:
return {
"reply_type": "text",
"text": f"已准备创建角色草稿:{profile_name}",
}
2026-07-05 22:34:54 +08:00
def _optional_text(value: Any) -> str | None:
text = str(value or "").strip()
return text or None