wecom_sync_client.py
2.77 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
73
74
75
76
77
78
79
80
81
from __future__ import annotations
import os
from datetime import datetime
from typing import Any
import httpx
from app.service.wecom_sync_service import WeComSyncClient
class WeComSyncClientError(Exception):
pass
class HttpWeComSyncClient(WeComSyncClient):
def __init__(
self,
base_url: str | None = None,
api_key: str | None = None,
timeout_seconds: float = 30.0,
) -> None:
self.base_url = (base_url or os.getenv("WECOM_SYNC_BASE_URL", "http://yjy.dev.glsx.com.cn/webim")).rstrip("/")
self.api_key = api_key or os.getenv("BUSINESS_API_KEY", "")
self.timeout_seconds = timeout_seconds
def list_bots(self, *, page: int, page_size: int) -> dict[str, Any]:
return self._get("/api/v1/business/bots", {"page": page, "page_size": page_size})
def list_contacts(self, *, bot_id: str, page: int, page_size: int) -> dict[str, Any]:
return self._get(
"/api/v1/business/contacts",
{"bot_id": bot_id, "page": page, "page_size": page_size},
)
def list_groups(self, *, bot_id: str, page: int, page_size: int) -> dict[str, Any]:
return self._get(
"/api/v1/business/groups",
{"bot_id": bot_id, "page": page, "page_size": page_size},
)
def list_messages(
self,
*,
bot_id: str,
start_time: datetime | None,
end_time: datetime | None,
page: int,
page_size: int,
order: str = "asc",
) -> dict[str, Any]:
params: dict[str, Any] = {
"bot_id": bot_id,
"page": page,
"page_size": page_size,
"order": order,
}
if start_time is not None:
params["start_time"] = start_time.isoformat().replace("+00:00", "Z")
if end_time is not None:
params["end_time"] = end_time.isoformat().replace("+00:00", "Z")
return self._get("/api/v1/business/messages", params)
def _get(self, path: str, params: dict[str, Any]) -> dict[str, Any]:
headers = {"Content-Type": "application/json"}
if self.api_key:
headers["X-Api-Key"] = self.api_key
try:
with httpx.Client(timeout=self.timeout_seconds) as client:
response = client.get(f"{self.base_url}{path}", params=params, headers=headers)
response.raise_for_status()
payload = response.json()
except httpx.HTTPError as exc:
raise WeComSyncClientError(str(exc)) from exc
if not isinstance(payload, dict):
raise WeComSyncClientError("Unexpected response payload")
data = payload.get("data", payload)
if not isinstance(data, dict):
raise WeComSyncClientError("Unexpected response data")
return data