ForcePilot/backend/package/yuxi/channels/adapters/whatsapp/accounts/accounts.py
Kris e9b57546ea feat(whatsapp): 新增WhatsApp适配器完整功能模块
新增大量WhatsApp适配器相关代码,包括账号管理、会话处理、消息收发、验证授权、媒体处理、互动命令、审批流程、健康检测等完整功能模块,搭建基础的Baileys协议WhatsApp接入能力
2026-05-12 00:51:58 +08:00

92 lines
3.1 KiB
Python

from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from yuxi.utils.logging_config import logger
from .account_config import merge_account_config
from .account_selection import resolve_default_account
@dataclass
class AccountState:
account_id: str
config: dict[str, Any]
auth_dir: str = ""
bridge_port: int = 0
class MultiAccountManager:
def __init__(self, config: dict[str, Any] | None = None):
cfg = config or {}
self._accounts: dict[str, AccountState] = {}
self._default_account_id: str | None = None
self._build_from_config(cfg)
def _build_from_config(self, config: dict) -> None:
accounts_cfg = config.get("accounts", {})
if not accounts_cfg:
base_account = AccountState(
account_id="default",
config=config,
)
self._accounts["default"] = base_account
self._default_account_id = "default"
return
default_id = config.get("defaultAccount", "")
for acc_id, acc_cfg in accounts_cfg.items():
if isinstance(acc_cfg, dict):
merged = merge_account_config(config, acc_cfg)
else:
merged = config
self._accounts[acc_id] = AccountState(
account_id=acc_id,
config=merged,
)
if acc_id == default_id:
self._default_account_id = acc_id
if not self._default_account_id and self._accounts:
self._default_account_id = resolve_default_account(list(self._accounts.keys()))
logger.info(f"MultiAccount: {len(self._accounts)} accounts, default={self._default_account_id}")
@property
def account_count(self) -> int:
return len(self._accounts)
@property
def default_account_id(self) -> str | None:
return self._default_account_id
def get_account(self, account_id: str | None = None) -> AccountState | None:
aid = account_id or self._default_account_id
return self._accounts.get(aid) if aid else None
def get_config(self, account_id: str | None = None) -> dict[str, Any]:
account = self.get_account(account_id)
return account.config if account else {}
def list_account_ids(self) -> list[str]:
return list(self._accounts.keys())
def add_account(self, account_id: str, config: dict[str, Any]) -> None:
base = self.get_config(self._default_account_id) if self._default_account_id else {}
merged = merge_account_config(base, config)
self._accounts[account_id] = AccountState(
account_id=account_id,
config=merged,
)
logger.info(f"MultiAccount: added account '{account_id}'")
def remove_account(self, account_id: str) -> bool:
if account_id in self._accounts:
del self._accounts[account_id]
if self._default_account_id == account_id and self._accounts:
self._default_account_id = next(iter(self._accounts))
logger.info(f"MultiAccount: removed account '{account_id}'")
return True
return False