wecom_sync_client.py
6.03 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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
from __future__ import annotations
import logging
import os
from datetime import datetime
from typing import Any
import httpx
from app.config.loader import ConfigLoader
from app.jobs.log_context import format_job_log
from app.service.wecom_sync_service import WeComSyncClient
logger = logging.getLogger(__name__)
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:
settings = ConfigLoader().load_settings()
resolved_base_url = base_url or os.getenv("WECOM_SYNC_BASE_URL") or settings.wecom_sync.base_url
resolved_api_key = api_key or os.getenv("BUSINESS_API_KEY") or settings.wecom_sync.api_key
self.base_url = resolved_base_url.rstrip("/")
self.api_key = resolved_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_customers(
self,
*,
bot_id: str,
start_time: datetime | None,
end_time: datetime | None,
page: int,
page_size: int,
contact_type: str | None = None,
keyword: str | None = None,
) -> 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")
if contact_type:
params["contact_type"] = contact_type
if keyword:
params["keyword"] = keyword
return self._get("/api/v1/business/customers", params)
def list_messages(
self,
*,
bot_id: str,
group_id: str | None,
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 group_id:
params["group_id"] = group_id
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
logger.info(format_job_log(f"正在调用接口 {path}"))
logger.info(format_job_log("请求方式: GET"))
logger.info(format_job_log(f"输入参数: {params}"))
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()
logger.info(format_job_log(f"接口返回状态: {path} {response.status_code}"))
except httpx.HTTPError as exc:
logger.exception(format_job_log(f"接口调用失败 path={path} params={params}"))
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
logger.info(format_job_log(f"正在调用接口 {path}"))
logger.info(format_job_log("请求方式: POST"))
logger.info(format_job_log(f"输入参数: {json_body}"))
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()
logger.info(format_job_log(f"接口返回状态: {path} {response.status_code}"))
except httpx.HTTPError as exc:
logger.exception(format_job_log(f"接口调用失败 path={path} json={json_body}"))
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