wecom_sync_client.py
4.92 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
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_customers(
self,
*,
bot_id: str,
start_time: datetime | None,
end_time: datetime | None,
page: int,
page_size: int,
) -> dict[str, Any]:
params: dict[str, Any] = {
"bot_id": bot_id,
"page": page,
"page_size": page_size,
}
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/customers", params)
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 create_group(
self,
*,
bot_code: str,
group_name: str,
member_list: list[str],
group_announcement: str | None,
biz_rela_no: str,
) -> dict[str, Any]:
payload: dict[str, Any] = {
"bot_code": bot_code,
"group_name": group_name,
"member_list": member_list,
"biz_rela_no": biz_rela_no,
}
if group_announcement:
payload["group_announcement"] = group_announcement
return self._post("/api/v1/business/groups/create", payload)
def get_task(self, *, task_id: str) -> dict[str, Any]:
return self._get(f"/api/v1/business/tasks/{task_id}", {})
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
def _post(self, path: str, json_body: 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.post(f"{self.base_url}{path}", json=json_body, 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