im_service.py
2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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