im_service.py 2.16 KB
from typing import Dict, Any, Optional
import httpx


class IMServiceError(Exception):
    """Raised when IM service API call fails."""
    pass


class IMService:
    """Service for sending messages via IM business API (机器人对接说明)

    Calls: POST {base_url}/api/v1/business/messages/send
    Auth:  X-Api-Key header
    """

    def __init__(self, base_url: str, api_key: Optional[str] = None):
        self.base_url = base_url.rstrip("/")
        self.api_key = api_key
        self._client: Optional[httpx.AsyncClient] = None

    @property
    def client(self) -> httpx.AsyncClient:
        if self._client is None:
            self._client = httpx.AsyncClient(timeout=30.0)
        return self._client

    async def send_message(
        self,
        bot_id: str,
        content: str,
        contact_id: str,
        at_list: str = "",
    ) -> Dict[str, Any]:
        """Send a text message via IM business API.

        Args:
            bot_id: 机器人账号 (e.g. wt_ww:RBT001)
            content: 消息正文
            contact_id: 目标群/联系人 ID (c_contacts.contact_id)
            at_list: @列表,逗号分隔成员昵称 (群聊有效)
        """
        payload = {
            "contact_id": contact_id,
            "content": content,
            "bot_id": bot_id,
            "msg_type": "text",
        }
        if at_list:
            payload["at_list"] = at_list

        headers = {"Content-Type": "application/json"}
        if self.api_key:
            headers["X-Api-Key"] = self.api_key

        try:
            response = await self.client.post(
                f"{self.base_url}/api/v1/business/messages/send",
                json=payload,
                headers=headers
            )
            response.raise_for_status()
            return response.json()
        except httpx.HTTPStatusError as e:
            raise IMServiceError(f"IM服务返回错误: {e.response.status_code} - {e.response.text}")
        except httpx.RequestError as e:
            raise IMServiceError(f"IM服务请求失败: {e}")

    async def close(self):
        if self._client is not None:
            await self._client.aclose()
            self._client = None