katcloud 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- katcloud/__init__.py +19 -0
- katcloud/client.py +387 -0
- katcloud/errors.py +54 -0
- katcloud/py.typed +0 -0
- katcloud/types.py +169 -0
- katcloud/webhook.py +108 -0
- katcloud-0.1.0.dist-info/METADATA +70 -0
- katcloud-0.1.0.dist-info/RECORD +10 -0
- katcloud-0.1.0.dist-info/WHEEL +5 -0
- katcloud-0.1.0.dist-info/top_level.txt +1 -0
katcloud/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""KAT Cloud (한국에이아이통신) Python SDK. Docs: https://katcloud.kr/docs/api"""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from .client import DEFAULT_BASE_URL, Client, urllib_transport # noqa: E402
|
|
6
|
+
from .errors import KatError, WebhookSignatureError # noqa: E402
|
|
7
|
+
from .webhook import compute_signature, construct_event, verify_signature # noqa: E402
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"Client",
|
|
11
|
+
"DEFAULT_BASE_URL",
|
|
12
|
+
"KatError",
|
|
13
|
+
"WebhookSignatureError",
|
|
14
|
+
"compute_signature",
|
|
15
|
+
"construct_event",
|
|
16
|
+
"urllib_transport",
|
|
17
|
+
"verify_signature",
|
|
18
|
+
"__version__",
|
|
19
|
+
]
|
katcloud/client.py
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
"""KAT Cloud API client (stdlib only).
|
|
2
|
+
|
|
3
|
+
Endpoints come from https://katcloud.kr/docs/api and the Studio API doc
|
|
4
|
+
(``apps/studio-api/API_DOCUMENTATION.md``). Nothing here is guessed: where the
|
|
5
|
+
docs do not spell out a request body, the method takes a plain ``dict`` and
|
|
6
|
+
passes it through (marked TODO).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import mimetypes
|
|
11
|
+
import os
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.parse
|
|
14
|
+
import urllib.request
|
|
15
|
+
import uuid
|
|
16
|
+
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Union, cast
|
|
17
|
+
|
|
18
|
+
from . import __version__
|
|
19
|
+
from .errors import KatError
|
|
20
|
+
from .types import (
|
|
21
|
+
Agent,
|
|
22
|
+
AiOutboundCall,
|
|
23
|
+
AuthCheck,
|
|
24
|
+
AvailableNumber,
|
|
25
|
+
CallHistory,
|
|
26
|
+
CallHistoryPage,
|
|
27
|
+
Channel,
|
|
28
|
+
Group,
|
|
29
|
+
MessageSendResult,
|
|
30
|
+
Webhook,
|
|
31
|
+
WebhookSecret,
|
|
32
|
+
WebhookTestResult,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
DEFAULT_BASE_URL = "https://studio-gateway.zerocall.kr"
|
|
36
|
+
|
|
37
|
+
# (method, url, headers, body, timeout) -> (status, headers, body)
|
|
38
|
+
Transport = Callable[[str, str, Dict[str, str], Optional[bytes], float], Tuple[int, Mapping[str, str], bytes]]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def urllib_transport(
|
|
42
|
+
method: str, url: str, headers: Dict[str, str], body: Optional[bytes], timeout: float
|
|
43
|
+
) -> Tuple[int, Mapping[str, str], bytes]:
|
|
44
|
+
"""Default transport using ``urllib.request``."""
|
|
45
|
+
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
|
46
|
+
try:
|
|
47
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
48
|
+
return resp.status, dict(resp.headers.items()), resp.read()
|
|
49
|
+
except urllib.error.HTTPError as e:
|
|
50
|
+
return e.code, dict(e.headers.items()) if e.headers else {}, e.read() or b""
|
|
51
|
+
except (urllib.error.URLError, OSError) as e:
|
|
52
|
+
raise KatError(0, "NETWORK_ERROR", f"{method} {url} failed: {e}") from e
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _clean(params: Mapping[str, Any]) -> Dict[str, Any]:
|
|
56
|
+
return {k: v for k, v in params.items() if v is not None}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _unwrap(body: Any) -> Any:
|
|
60
|
+
"""Strip the documented success envelope ``{"code": "0", "message", "result"}``.
|
|
61
|
+
|
|
62
|
+
The docs say examples "may show only result", so some endpoints may answer
|
|
63
|
+
without the envelope; in that case the body is returned as is.
|
|
64
|
+
"""
|
|
65
|
+
if isinstance(body, dict) and "result" in body and "code" in body:
|
|
66
|
+
return body["result"]
|
|
67
|
+
return body
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Client:
|
|
71
|
+
"""KAT Cloud API client.
|
|
72
|
+
|
|
73
|
+
>>> kat = Client(api_key="zpa.123.secret")
|
|
74
|
+
>>> kat.list_groups()
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
def __init__(
|
|
78
|
+
self,
|
|
79
|
+
api_key: Optional[str] = None,
|
|
80
|
+
base_url: Optional[str] = None,
|
|
81
|
+
timeout: float = 30.0,
|
|
82
|
+
transport: Optional[Transport] = None,
|
|
83
|
+
) -> None:
|
|
84
|
+
api_key = api_key or os.environ.get("KATCLOUD_API_KEY")
|
|
85
|
+
if not api_key:
|
|
86
|
+
raise ValueError("api_key is required (or set KATCLOUD_API_KEY)")
|
|
87
|
+
self.api_key = api_key
|
|
88
|
+
self.base_url = (base_url or os.environ.get("KATCLOUD_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
89
|
+
self.timeout = timeout
|
|
90
|
+
self._transport: Transport = transport or urllib_transport
|
|
91
|
+
|
|
92
|
+
# ------------------------------------------------------------------ core
|
|
93
|
+
|
|
94
|
+
def request(
|
|
95
|
+
self,
|
|
96
|
+
method: str,
|
|
97
|
+
path: str,
|
|
98
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
99
|
+
body: Any = None,
|
|
100
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
101
|
+
raw_body: Optional[bytes] = None,
|
|
102
|
+
) -> Any:
|
|
103
|
+
"""Send a request and return the parsed (unwrapped) JSON, or None for 204.
|
|
104
|
+
|
|
105
|
+
Use this for documented endpoints that have no dedicated method yet
|
|
106
|
+
(chat rooms, agent manuals/tools, payments, ...).
|
|
107
|
+
"""
|
|
108
|
+
url = self.base_url + path
|
|
109
|
+
if query:
|
|
110
|
+
q = {k: ("true" if v is True else "false" if v is False else v) for k, v in _clean(query).items()}
|
|
111
|
+
if q:
|
|
112
|
+
url += "?" + urllib.parse.urlencode(q)
|
|
113
|
+
h = {
|
|
114
|
+
"x-api-key": self.api_key,
|
|
115
|
+
"Accept": "application/json",
|
|
116
|
+
"User-Agent": f"katcloud-python/{__version__}",
|
|
117
|
+
}
|
|
118
|
+
data: Optional[bytes] = raw_body
|
|
119
|
+
if body is not None and raw_body is None:
|
|
120
|
+
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
|
121
|
+
h["Content-Type"] = "application/json"
|
|
122
|
+
if headers:
|
|
123
|
+
h.update(headers)
|
|
124
|
+
|
|
125
|
+
status, _resp_headers, content = self._transport(method, url, h, data, self.timeout)
|
|
126
|
+
parsed: Any = None
|
|
127
|
+
if content:
|
|
128
|
+
text = content.decode("utf-8", errors="replace")
|
|
129
|
+
try:
|
|
130
|
+
parsed = json.loads(text)
|
|
131
|
+
except ValueError:
|
|
132
|
+
parsed = text
|
|
133
|
+
if status < 200 or status >= 300:
|
|
134
|
+
raise KatError.from_response(status, parsed)
|
|
135
|
+
return _unwrap(parsed)
|
|
136
|
+
|
|
137
|
+
@staticmethod
|
|
138
|
+
def _seg(value: Union[int, str]) -> str:
|
|
139
|
+
return urllib.parse.quote(str(value), safe="")
|
|
140
|
+
|
|
141
|
+
# ------------------------------------------------------------------ auth
|
|
142
|
+
|
|
143
|
+
def auth_check(self) -> AuthCheck:
|
|
144
|
+
"""``GET /auth-check``: validate the API key and list its groups."""
|
|
145
|
+
return cast(AuthCheck, self.request("GET", "/auth-check"))
|
|
146
|
+
|
|
147
|
+
# ------------------------------------------------------------- groups / numbers
|
|
148
|
+
|
|
149
|
+
def list_groups(self) -> List[Group]:
|
|
150
|
+
"""``GET /group``: groups (each with its phone number) this key can access."""
|
|
151
|
+
return cast(List[Group], self.request("GET", "/group"))
|
|
152
|
+
|
|
153
|
+
def create_group(
|
|
154
|
+
self,
|
|
155
|
+
group_title: Optional[str] = None,
|
|
156
|
+
phone_number: Optional[str] = None,
|
|
157
|
+
plan: Optional[str] = None,
|
|
158
|
+
) -> Any:
|
|
159
|
+
"""``POST /group``: create a group and issue a phone number.
|
|
160
|
+
|
|
161
|
+
``plan`` is one of ECHO, BASIC (default), BUSINESS, PRO.
|
|
162
|
+
Returns the new group id as a bare number (``123``), as the server does
|
|
163
|
+
(studio-api ``group.controller.ts`` ``issue(): Promise<number>``).
|
|
164
|
+
403 ``GR047`` means the key owner has not completed identity verification.
|
|
165
|
+
"""
|
|
166
|
+
body = _clean({"groupTitle": group_title, "phoneNumber": phone_number, "plan": plan})
|
|
167
|
+
return self.request("POST", "/group", body=body)
|
|
168
|
+
|
|
169
|
+
def delete_group(self, group_id: int) -> None:
|
|
170
|
+
"""``DELETE /group/{groupId}``: delete the group and release its number."""
|
|
171
|
+
self.request("DELETE", f"/group/{self._seg(group_id)}")
|
|
172
|
+
|
|
173
|
+
def check_available_number(self) -> AvailableNumber:
|
|
174
|
+
"""``GET /phone-number-pool/available``."""
|
|
175
|
+
return cast(AvailableNumber, self.request("GET", "/phone-number-pool/available"))
|
|
176
|
+
|
|
177
|
+
def list_channels(self, group_id: int) -> List[Channel]:
|
|
178
|
+
"""``GET /group/{groupId}/channel``: the group's phone numbers (primary first).
|
|
179
|
+
|
|
180
|
+
Documented under AI agents; may require the AI agent feature (403 AG002).
|
|
181
|
+
"""
|
|
182
|
+
return cast(List[Channel], self.request("GET", f"/group/{self._seg(group_id)}/channel"))
|
|
183
|
+
|
|
184
|
+
# ------------------------------------------------------------- messages
|
|
185
|
+
|
|
186
|
+
def send_message(
|
|
187
|
+
self,
|
|
188
|
+
to: str,
|
|
189
|
+
content: str,
|
|
190
|
+
from_number: str,
|
|
191
|
+
subject: Optional[str] = None,
|
|
192
|
+
image_list: Optional[Sequence[str]] = None,
|
|
193
|
+
) -> Any:
|
|
194
|
+
"""``POST /message/send``: SMS/LMS/MMS (type decided by the server).
|
|
195
|
+
|
|
196
|
+
``from_number`` is required per the KAT doc (400 if missing).
|
|
197
|
+
Returns the 32-char ``chatId`` as a bare string, as the server does
|
|
198
|
+
(studio-api ``message.controller.ts`` returns ``chat.id``).
|
|
199
|
+
Note: KAT doc marks this API "Deprecated" in favour of the chat API.
|
|
200
|
+
"""
|
|
201
|
+
body = _clean(
|
|
202
|
+
{
|
|
203
|
+
"toPhoneNumber": to,
|
|
204
|
+
"content": content,
|
|
205
|
+
"fromPhoneNumber": from_number,
|
|
206
|
+
"subject": subject,
|
|
207
|
+
"imageList": list(image_list) if image_list else None,
|
|
208
|
+
}
|
|
209
|
+
)
|
|
210
|
+
return self.request("POST", "/message/send", body=body)
|
|
211
|
+
|
|
212
|
+
def get_message_result(self, chat_id: str) -> MessageSendResult:
|
|
213
|
+
"""``GET /message/send-result/{chatId}``."""
|
|
214
|
+
return cast(MessageSendResult, self.request("GET", f"/message/send-result/{self._seg(chat_id)}"))
|
|
215
|
+
|
|
216
|
+
def upload_media(self, paths: Sequence[str]) -> Any:
|
|
217
|
+
"""``POST /message/media/upload`` (multipart, field ``files``, up to 3).
|
|
218
|
+
|
|
219
|
+
Returns ``{"urls": [...]}``; pass the urls as ``image_list`` to send MMS.
|
|
220
|
+
"""
|
|
221
|
+
if not 1 <= len(paths) <= 3:
|
|
222
|
+
raise ValueError("upload 1 to 3 files")
|
|
223
|
+
boundary = "----katcloud" + uuid.uuid4().hex
|
|
224
|
+
parts: List[bytes] = []
|
|
225
|
+
for p in paths:
|
|
226
|
+
name = os.path.basename(p)
|
|
227
|
+
ctype = mimetypes.guess_type(name)[0] or "application/octet-stream"
|
|
228
|
+
with open(p, "rb") as f:
|
|
229
|
+
content = f.read()
|
|
230
|
+
parts.append(
|
|
231
|
+
(
|
|
232
|
+
f"--{boundary}\r\n"
|
|
233
|
+
f'Content-Disposition: form-data; name="files"; filename="{name}"\r\n'
|
|
234
|
+
f"Content-Type: {ctype}\r\n\r\n"
|
|
235
|
+
).encode("utf-8")
|
|
236
|
+
+ content
|
|
237
|
+
+ b"\r\n"
|
|
238
|
+
)
|
|
239
|
+
parts.append(f"--{boundary}--\r\n".encode("utf-8"))
|
|
240
|
+
return self.request(
|
|
241
|
+
"POST",
|
|
242
|
+
"/message/media/upload",
|
|
243
|
+
raw_body=b"".join(parts),
|
|
244
|
+
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
# ------------------------------------------------------------- call history
|
|
248
|
+
|
|
249
|
+
def list_call_history(
|
|
250
|
+
self,
|
|
251
|
+
group_id: int,
|
|
252
|
+
channel_id: Optional[int] = None,
|
|
253
|
+
phone_number: Optional[str] = None,
|
|
254
|
+
keyword: Optional[str] = None,
|
|
255
|
+
updated_after: Optional[str] = None,
|
|
256
|
+
offset: Optional[int] = None,
|
|
257
|
+
limit: Optional[int] = None,
|
|
258
|
+
) -> CallHistoryPage:
|
|
259
|
+
"""``GET /call-history``. ``limit`` max 100.
|
|
260
|
+
|
|
261
|
+
For polling, pass ``updated_after`` (ISO 8601) and feed the last item's
|
|
262
|
+
``updatedAt`` back in; do not combine with ``offset``.
|
|
263
|
+
"""
|
|
264
|
+
q = {
|
|
265
|
+
"groupId": group_id,
|
|
266
|
+
"channelId": channel_id,
|
|
267
|
+
"phoneNumber": phone_number,
|
|
268
|
+
"keyword": keyword,
|
|
269
|
+
"updatedAfter": updated_after,
|
|
270
|
+
"offset": offset,
|
|
271
|
+
"limit": limit,
|
|
272
|
+
}
|
|
273
|
+
return cast(CallHistoryPage, self.request("GET", "/call-history", query=q))
|
|
274
|
+
|
|
275
|
+
def get_call_history(self, call_history_id: str, group_id: int) -> CallHistory:
|
|
276
|
+
"""``GET /call-history/{callHistoryId}?groupId=``."""
|
|
277
|
+
return cast(
|
|
278
|
+
CallHistory,
|
|
279
|
+
self.request("GET", f"/call-history/{self._seg(call_history_id)}", query={"groupId": group_id}),
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
# ------------------------------------------------------------- agents
|
|
283
|
+
|
|
284
|
+
def list_agents(
|
|
285
|
+
self, group_id: int, direction: Optional[str] = None, status: Optional[str] = None
|
|
286
|
+
) -> List[Agent]:
|
|
287
|
+
"""``GET /group/{groupId}/agent?direction=&status=``.
|
|
288
|
+
|
|
289
|
+
``direction``: INBOUND | OUTBOUND, ``status``: ACTIVE | DISABLED.
|
|
290
|
+
"""
|
|
291
|
+
return cast(
|
|
292
|
+
List[Agent],
|
|
293
|
+
self.request(
|
|
294
|
+
"GET", f"/group/{self._seg(group_id)}/agent", query={"direction": direction, "status": status}
|
|
295
|
+
),
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
def get_agent(self, group_id: int, agent_id: int) -> Agent:
|
|
299
|
+
"""``GET /group/{groupId}/agent/{agentId}``."""
|
|
300
|
+
return cast(Agent, self.request("GET", f"/group/{self._seg(group_id)}/agent/{self._seg(agent_id)}"))
|
|
301
|
+
|
|
302
|
+
# ------------------------------------------------------------- AI outbound
|
|
303
|
+
|
|
304
|
+
def create_ai_outbound_call(
|
|
305
|
+
self, group_id: int, body: Mapping[str, Any], idempotency_key: Optional[str] = None
|
|
306
|
+
) -> Any:
|
|
307
|
+
"""``POST /group/{groupId}/ai-outbound/calls`` with ``Idempotency-Key``.
|
|
308
|
+
|
|
309
|
+
Places a real phone call (may be billed). Returns ``requestId`` and the
|
|
310
|
+
accepted status; results arrive via ``get_ai_outbound_call`` or the
|
|
311
|
+
``AI_OUTBOUND`` webhook. Reuse the same ``idempotency_key`` on retry
|
|
312
|
+
(a random UUID is generated if omitted).
|
|
313
|
+
|
|
314
|
+
``body`` fields (server ``CreateAiOutboundCallRequest``): ``agentId`` (int),
|
|
315
|
+
``callerChannelId`` (int), ``destination`` (str), ``inputs`` (dict, ``{}`` when
|
|
316
|
+
the agent has no input fields), optional ``timeLimit``, ``queueWhenBusy``,
|
|
317
|
+
``queueTimeout``, ``record``. ``body`` is passed through unchanged.
|
|
318
|
+
"""
|
|
319
|
+
key = idempotency_key or str(uuid.uuid4())
|
|
320
|
+
return self.request(
|
|
321
|
+
"POST",
|
|
322
|
+
f"/group/{self._seg(group_id)}/ai-outbound/calls",
|
|
323
|
+
body=dict(body),
|
|
324
|
+
headers={"Idempotency-Key": key},
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
def get_ai_outbound_call(self, group_id: int, request_id: str) -> AiOutboundCall:
|
|
328
|
+
"""``GET /group/{groupId}/ai-outbound/calls/{requestId}``: call/analysis/settlement status."""
|
|
329
|
+
return cast(
|
|
330
|
+
AiOutboundCall,
|
|
331
|
+
self.request("GET", f"/group/{self._seg(group_id)}/ai-outbound/calls/{self._seg(request_id)}"),
|
|
332
|
+
)
|
|
333
|
+
|
|
334
|
+
def list_ai_outbound_calls(
|
|
335
|
+
self, group_id: int, cursor: Optional[str] = None, limit: Optional[int] = None
|
|
336
|
+
) -> Any:
|
|
337
|
+
"""``GET /group/{groupId}/ai-outbound/calls?cursor=&limit=``.
|
|
338
|
+
|
|
339
|
+
TODO: response shape (items / next cursor key) is not documented; raw JSON is returned.
|
|
340
|
+
"""
|
|
341
|
+
return self.request(
|
|
342
|
+
"GET", f"/group/{self._seg(group_id)}/ai-outbound/calls", query={"cursor": cursor, "limit": limit}
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
def terminate_ai_outbound_call(
|
|
346
|
+
self, group_id: int, request_id: str, body: Optional[Mapping[str, Any]] = None
|
|
347
|
+
) -> Any:
|
|
348
|
+
"""``POST /group/{groupId}/ai-outbound/calls/{requestId}/termination``.
|
|
349
|
+
|
|
350
|
+
Cancels a call not yet placed, or asks to end one in progress.
|
|
351
|
+
TODO: request body (e.g. a reason) is not documented; ``body`` is passed through.
|
|
352
|
+
"""
|
|
353
|
+
return self.request(
|
|
354
|
+
"POST",
|
|
355
|
+
f"/group/{self._seg(group_id)}/ai-outbound/calls/{self._seg(request_id)}/termination",
|
|
356
|
+
body=dict(body) if body is not None else {},
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
# ------------------------------------------------------------- webhooks
|
|
360
|
+
|
|
361
|
+
def list_webhooks(self) -> List[Webhook]:
|
|
362
|
+
"""``GET /webhook``."""
|
|
363
|
+
return cast(List[Webhook], self.request("GET", "/webhook"))
|
|
364
|
+
|
|
365
|
+
def create_webhook(self, event_type: str, url: str) -> Webhook:
|
|
366
|
+
"""``POST /webhook``: one URL per event type per account."""
|
|
367
|
+
return cast(Webhook, self.request("POST", "/webhook", body={"eventType": event_type, "url": url}))
|
|
368
|
+
|
|
369
|
+
def update_webhook(self, webhook_id: int, url: str) -> Any:
|
|
370
|
+
"""``PATCH /webhook/{webhookId}``."""
|
|
371
|
+
return self.request("PATCH", f"/webhook/{self._seg(webhook_id)}", body={"url": url})
|
|
372
|
+
|
|
373
|
+
def delete_webhook(self, webhook_id: int) -> None:
|
|
374
|
+
"""``DELETE /webhook/{webhookId}``."""
|
|
375
|
+
self.request("DELETE", f"/webhook/{self._seg(webhook_id)}")
|
|
376
|
+
|
|
377
|
+
def test_webhook(self, webhook_id: int) -> WebhookTestResult:
|
|
378
|
+
"""``POST /webhook/{webhookId}/test``: sends a signed payload with ``isTest: true``."""
|
|
379
|
+
return cast(WebhookTestResult, self.request("POST", f"/webhook/{self._seg(webhook_id)}/test"))
|
|
380
|
+
|
|
381
|
+
def get_webhook_secret(self) -> WebhookSecret:
|
|
382
|
+
"""``GET /webhook/secret`` (created on first call)."""
|
|
383
|
+
return cast(WebhookSecret, self.request("GET", "/webhook/secret"))
|
|
384
|
+
|
|
385
|
+
def rotate_webhook_secret(self) -> WebhookSecret:
|
|
386
|
+
"""``POST /webhook/secret/rotate``: later deliveries are signed with the new secret."""
|
|
387
|
+
return cast(WebhookSecret, self.request("POST", "/webhook/secret/rotate"))
|
katcloud/errors.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""KAT Cloud error types."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, List, Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class KatError(Exception):
|
|
7
|
+
"""An API error.
|
|
8
|
+
|
|
9
|
+
The KAT Cloud docs describe the error body as
|
|
10
|
+
``{"status": 401, "code": "AU002", "message": "...", "errors": [...]}``.
|
|
11
|
+
The older Studio API doc shows ``{"statusCode", "message", "error"}``; both
|
|
12
|
+
shapes are accepted here.
|
|
13
|
+
|
|
14
|
+
``status`` is the HTTP status (0 for network failures), ``code`` the KAT
|
|
15
|
+
error code such as ``AU017`` or ``AG011`` (may be None), ``message`` the
|
|
16
|
+
human-readable text, ``errors`` the optional per-field reasons and ``body``
|
|
17
|
+
the parsed response body (or raw text) for debugging.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
status: int,
|
|
23
|
+
code: Optional[str],
|
|
24
|
+
message: str,
|
|
25
|
+
errors: Optional[List[Any]] = None,
|
|
26
|
+
body: Any = None,
|
|
27
|
+
) -> None:
|
|
28
|
+
super().__init__(f"[{status}{' ' + code if code else ''}] {message}")
|
|
29
|
+
self.status = status
|
|
30
|
+
self.code = code
|
|
31
|
+
self.message = message
|
|
32
|
+
self.errors = errors or []
|
|
33
|
+
self.body = body
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def from_response(cls, http_status: int, body: Any) -> "KatError":
|
|
37
|
+
if isinstance(body, dict):
|
|
38
|
+
status = body.get("status") or body.get("statusCode") or http_status
|
|
39
|
+
try:
|
|
40
|
+
status = int(status)
|
|
41
|
+
except (TypeError, ValueError):
|
|
42
|
+
status = http_status
|
|
43
|
+
code = body.get("code")
|
|
44
|
+
message = body.get("message") or body.get("error") or "Request failed"
|
|
45
|
+
if isinstance(message, list): # validation pipes sometimes return a list
|
|
46
|
+
message = "; ".join(str(m) for m in message)
|
|
47
|
+
errors = body.get("errors") if isinstance(body.get("errors"), list) else None
|
|
48
|
+
return cls(status, str(code) if code is not None else None, str(message), errors, body)
|
|
49
|
+
text = body if isinstance(body, str) and body else f"HTTP {http_status}"
|
|
50
|
+
return cls(http_status, None, text, None, body)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class WebhookSignatureError(Exception):
|
|
54
|
+
"""Raised by :func:`katcloud.webhook.construct_event` when verification fails."""
|
katcloud/py.typed
ADDED
|
File without changes
|
katcloud/types.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Response shapes, taken from the examples in the KAT Cloud / Studio API docs.
|
|
2
|
+
|
|
3
|
+
All TypedDicts are ``total=False``: the docs show examples, not guarantees, so
|
|
4
|
+
any field may be missing. Unknown fields are passed through untouched.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Any, Dict, List, Literal, Optional, TypedDict
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AuthCheck(TypedDict, total=False):
|
|
11
|
+
apiKeyId: int
|
|
12
|
+
userId: int
|
|
13
|
+
name: str
|
|
14
|
+
groupIdList: List[int]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Group(TypedDict, total=False):
|
|
18
|
+
id: int
|
|
19
|
+
title: str
|
|
20
|
+
phoneNumber: str
|
|
21
|
+
channelId: int
|
|
22
|
+
status: str # ACTIVE | INACTIVE | PENDING
|
|
23
|
+
recordingEnabled: bool
|
|
24
|
+
createdAt: str
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class AvailableNumber(TypedDict, total=False):
|
|
28
|
+
isAvailable: bool
|
|
29
|
+
phoneNumber: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Channel(TypedDict, total=False):
|
|
33
|
+
id: int
|
|
34
|
+
phoneNumber: str
|
|
35
|
+
displayName: str
|
|
36
|
+
isPrimary: bool
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class MessageSendResult(TypedDict, total=False):
|
|
40
|
+
"""``GET /message/send-result/{chatId}``."""
|
|
41
|
+
|
|
42
|
+
id: str
|
|
43
|
+
content: str
|
|
44
|
+
subject: str
|
|
45
|
+
imageList: List[str]
|
|
46
|
+
externalMessageId: str
|
|
47
|
+
fromPhoneNumber: str
|
|
48
|
+
toPhoneNumber: str
|
|
49
|
+
sendStatus: str # SUCCESS | FAILED
|
|
50
|
+
chatType: str # SMS | LMS | MMS | RCS | KAKAO
|
|
51
|
+
resultStatus: str # success when 4100, 6600 or 7000
|
|
52
|
+
resultMessage: str
|
|
53
|
+
createdAt: str
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class SttLine(TypedDict, total=False):
|
|
57
|
+
role: str
|
|
58
|
+
text: str
|
|
59
|
+
timestamp: float
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class RecordingFile(TypedDict, total=False):
|
|
63
|
+
url: str
|
|
64
|
+
expiresAt: str
|
|
65
|
+
contentLength: int
|
|
66
|
+
contentType: str
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class CallHistory(TypedDict, total=False):
|
|
70
|
+
callHistoryId: str
|
|
71
|
+
fromNumber: str
|
|
72
|
+
toNumber: str
|
|
73
|
+
isInbound: bool
|
|
74
|
+
status: str # ANSWERED | MISSED | REJECTED | UNKNOWN
|
|
75
|
+
tag: str # AI | DIRECT | AI_TO_DIRECT | UNKNOWN
|
|
76
|
+
duration: int
|
|
77
|
+
summary: str
|
|
78
|
+
sttAI: List[SttLine]
|
|
79
|
+
sttDirect: List[SttLine]
|
|
80
|
+
recordingAI: RecordingFile
|
|
81
|
+
recordingDirect: RecordingFile
|
|
82
|
+
isRecorded: bool
|
|
83
|
+
channelId: int
|
|
84
|
+
groupId: int
|
|
85
|
+
createdAt: str
|
|
86
|
+
updatedAt: str
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class CallHistoryPage(TypedDict, total=False):
|
|
90
|
+
data: List[CallHistory]
|
|
91
|
+
total: int
|
|
92
|
+
offset: int
|
|
93
|
+
limit: int
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class Agent(TypedDict, total=False):
|
|
97
|
+
id: int
|
|
98
|
+
groupId: int
|
|
99
|
+
name: str
|
|
100
|
+
direction: str # INBOUND | OUTBOUND
|
|
101
|
+
prompt: str
|
|
102
|
+
status: str # ACTIVE | DISABLED
|
|
103
|
+
context: Optional[str]
|
|
104
|
+
greeting: Optional[str]
|
|
105
|
+
voice: Optional[str]
|
|
106
|
+
language: Optional[str]
|
|
107
|
+
liveModel: Optional[str]
|
|
108
|
+
maxCallSeconds: Optional[int]
|
|
109
|
+
aiInterruptionEnabled: Optional[bool]
|
|
110
|
+
version: int
|
|
111
|
+
createdAt: str
|
|
112
|
+
updatedAt: str
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class AiOutboundCall(TypedDict, total=False):
|
|
116
|
+
"""AI outbound call status.
|
|
117
|
+
|
|
118
|
+
TODO: the REST response of ``GET /group/{groupId}/ai-outbound/calls/{requestId}``
|
|
119
|
+
is not documented field-by-field. These keys come from the ``AI_OUTBOUND``
|
|
120
|
+
webhook payload and may differ from the REST response.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
requestId: str
|
|
124
|
+
callHistoryId: str
|
|
125
|
+
status: str # COMPLETED | NO_ANSWER | BUSY | REJECTED | CANCELED | FAILED
|
|
126
|
+
endReason: str
|
|
127
|
+
answered: bool
|
|
128
|
+
answeredAt: str
|
|
129
|
+
endedAt: str
|
|
130
|
+
durationSeconds: int
|
|
131
|
+
analysisStatus: str # NOT_APPLICABLE | PENDING | READY | PARTIAL | FAILED
|
|
132
|
+
settlementStatus: str # PENDING | SETTLED | WAIVED
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class Webhook(TypedDict, total=False):
|
|
136
|
+
id: int
|
|
137
|
+
eventType: str
|
|
138
|
+
url: str
|
|
139
|
+
createdAt: str
|
|
140
|
+
updatedAt: str
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class WebhookTestResult(TypedDict, total=False):
|
|
144
|
+
success: bool
|
|
145
|
+
statusCode: int
|
|
146
|
+
responseTime: int
|
|
147
|
+
error: Optional[str]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class WebhookSecret(TypedDict, total=False):
|
|
151
|
+
secret: str
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
WebhookEventType = Literal[
|
|
155
|
+
"MESSAGE_RECEIVED",
|
|
156
|
+
"SEND_RESULT",
|
|
157
|
+
"CALL_RECEIVED",
|
|
158
|
+
"CALL_COMPLETED",
|
|
159
|
+
"INTAKE",
|
|
160
|
+
"AI_OUTBOUND",
|
|
161
|
+
]
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class WebhookEvent(TypedDict, total=False):
|
|
165
|
+
eventId: str
|
|
166
|
+
eventType: str
|
|
167
|
+
timestamp: str
|
|
168
|
+
data: Dict[str, Any]
|
|
169
|
+
isTest: bool
|
katcloud/webhook.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Webhook signature verification.
|
|
2
|
+
|
|
3
|
+
Per the KAT Cloud docs every webhook carries two headers:
|
|
4
|
+
|
|
5
|
+
* ``X-Webhook-Timestamp``: send time in unix seconds
|
|
6
|
+
* ``X-Webhook-Signature``: ``"v1=" + hex(HMAC-SHA256(secret, "<timestamp>.<raw body>"))``
|
|
7
|
+
|
|
8
|
+
The secret is the full ``whsec_...`` string (including the prefix), from
|
|
9
|
+
``GET /webhook/secret``. Verify against the raw bytes, never re-serialised JSON,
|
|
10
|
+
compare in constant time and reject timestamps more than 5 minutes off.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import hashlib
|
|
14
|
+
import hmac
|
|
15
|
+
import json
|
|
16
|
+
import time
|
|
17
|
+
from typing import Any, Dict, Iterable, Optional, Union
|
|
18
|
+
|
|
19
|
+
from .errors import WebhookSignatureError
|
|
20
|
+
|
|
21
|
+
TIMESTAMP_HEADER = "X-Webhook-Timestamp"
|
|
22
|
+
SIGNATURE_HEADER = "X-Webhook-Signature"
|
|
23
|
+
DEFAULT_TOLERANCE_SECONDS = 300
|
|
24
|
+
|
|
25
|
+
SecretArg = Union[str, Iterable[str]]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def compute_signature(secret: str, timestamp: Union[str, int], raw_body: bytes) -> str:
|
|
29
|
+
"""Return the ``v1=<hex>`` signature KAT Cloud would send for this body."""
|
|
30
|
+
if isinstance(raw_body, str):
|
|
31
|
+
raw_body = raw_body.encode("utf-8")
|
|
32
|
+
digest = hmac.new(
|
|
33
|
+
secret.encode("utf-8"),
|
|
34
|
+
str(timestamp).encode("utf-8") + b"." + raw_body,
|
|
35
|
+
hashlib.sha256,
|
|
36
|
+
).hexdigest()
|
|
37
|
+
return "v1=" + digest
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def verify_signature(
|
|
41
|
+
raw_body: bytes,
|
|
42
|
+
timestamp: Optional[str],
|
|
43
|
+
signature: Optional[str],
|
|
44
|
+
secret: SecretArg,
|
|
45
|
+
tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS,
|
|
46
|
+
now: Optional[float] = None,
|
|
47
|
+
) -> bool:
|
|
48
|
+
"""Return True if the signature is valid and the timestamp is fresh.
|
|
49
|
+
|
|
50
|
+
``secret`` may be a single secret or several (e.g. new and previous while
|
|
51
|
+
rotating with ``POST /webhook/secret/rotate``, as the docs suggest).
|
|
52
|
+
"""
|
|
53
|
+
if not timestamp or not signature:
|
|
54
|
+
return False
|
|
55
|
+
try:
|
|
56
|
+
ts = int(str(timestamp).strip())
|
|
57
|
+
except ValueError:
|
|
58
|
+
return False
|
|
59
|
+
current = time.time() if now is None else now
|
|
60
|
+
if abs(current - ts) > tolerance_seconds:
|
|
61
|
+
return False
|
|
62
|
+
secrets = [secret] if isinstance(secret, str) else list(secret)
|
|
63
|
+
sig = signature.strip().encode("utf-8")
|
|
64
|
+
ok = False
|
|
65
|
+
for s in secrets:
|
|
66
|
+
if not s:
|
|
67
|
+
continue
|
|
68
|
+
expected = compute_signature(s, str(timestamp).strip(), raw_body).encode("utf-8")
|
|
69
|
+
# evaluate every secret so timing does not reveal which one matched
|
|
70
|
+
ok = hmac.compare_digest(expected, sig) or ok
|
|
71
|
+
return ok
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _header(headers: Any, name: str) -> Optional[str]:
|
|
75
|
+
if headers is None:
|
|
76
|
+
return None
|
|
77
|
+
value = headers.get(name)
|
|
78
|
+
if value is None and isinstance(headers, dict):
|
|
79
|
+
lower = name.lower()
|
|
80
|
+
for k, v in headers.items():
|
|
81
|
+
if k.lower() == lower:
|
|
82
|
+
return v
|
|
83
|
+
return value
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def construct_event(
|
|
87
|
+
raw_body: bytes,
|
|
88
|
+
headers: Any,
|
|
89
|
+
secret: SecretArg,
|
|
90
|
+
tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS,
|
|
91
|
+
now: Optional[float] = None,
|
|
92
|
+
) -> Dict[str, Any]:
|
|
93
|
+
"""Verify then parse a webhook. Raises :class:`WebhookSignatureError`.
|
|
94
|
+
|
|
95
|
+
``headers`` is any mapping with ``.get`` (``http.server`` headers, Flask
|
|
96
|
+
``request.headers``, or a plain dict).
|
|
97
|
+
"""
|
|
98
|
+
ok = verify_signature(
|
|
99
|
+
raw_body,
|
|
100
|
+
_header(headers, TIMESTAMP_HEADER),
|
|
101
|
+
_header(headers, SIGNATURE_HEADER),
|
|
102
|
+
secret,
|
|
103
|
+
tolerance_seconds=tolerance_seconds,
|
|
104
|
+
now=now,
|
|
105
|
+
)
|
|
106
|
+
if not ok:
|
|
107
|
+
raise WebhookSignatureError("invalid or expired webhook signature")
|
|
108
|
+
return json.loads(raw_body.decode("utf-8") if isinstance(raw_body, bytes) else raw_body)
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: katcloud
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: KAT Cloud API Python SDK
|
|
5
|
+
Author: 한국에이아이통신(주)
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://katcloud.kr
|
|
8
|
+
Project-URL: Documentation, https://katcloud.kr/docs/api
|
|
9
|
+
Project-URL: Repository, https://github.com/katcloud-kr/kat-sdk
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Typing :: Typed
|
|
13
|
+
Requires-Python: >=3.8
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# katcloud
|
|
17
|
+
|
|
18
|
+
한국에이아이통신(주) KAT Cloud API 용 Python SDK 입니다. 표준 라이브러리만 쓰고 Python 3.8 이상에서 동작합니다.
|
|
19
|
+
|
|
20
|
+
KAT Cloud 는 AI 에이전트를 한국 전화망에 연결하는 통신 인프라입니다. 070 번호 발급, 문자, 통화 기록, AI 발신, 웹훅을 API 로 다룹니다.
|
|
21
|
+
|
|
22
|
+
- 문서: https://katcloud.kr/docs/api
|
|
23
|
+
- 콘솔(API 키 발급): https://app.katcloud.kr
|
|
24
|
+
|
|
25
|
+
## 설치
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install katcloud
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## 사용
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from katcloud import Client, KatError
|
|
35
|
+
|
|
36
|
+
kat = Client(api_key="zpa...") # 또는 환경 변수 KATCLOUD_API_KEY
|
|
37
|
+
|
|
38
|
+
# 번호 발급
|
|
39
|
+
group_id = kat.create_group(group_title="my-agent")
|
|
40
|
+
for group in kat.list_groups():
|
|
41
|
+
print(group["phoneNumber"])
|
|
42
|
+
|
|
43
|
+
# 문자 보내기
|
|
44
|
+
chat_id = kat.send_message("01098765432", "예약이 확정되었습니다.", from_number="07012345678")
|
|
45
|
+
|
|
46
|
+
# AI 발신 (실제 전화가 걸리고 요금이 생길 수 있습니다)
|
|
47
|
+
call = kat.create_ai_outbound_call(group_id, {
|
|
48
|
+
"agentId": 12,
|
|
49
|
+
"callerChannelId": 34,
|
|
50
|
+
"destination": "01098765432",
|
|
51
|
+
"inputs": {},
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
kat.list_agents(group_id)
|
|
56
|
+
except KatError as e:
|
|
57
|
+
print(e.status, e.code, e.message)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## 웹훅 서명 검증
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from katcloud import construct_event
|
|
64
|
+
|
|
65
|
+
event = construct_event(raw_body, headers, secret) # 실패하면 WebhookSignatureError
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## 라이선스
|
|
69
|
+
|
|
70
|
+
MIT
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
katcloud/__init__.py,sha256=ea8xpBbKqJoom6KKtDe5wr4RXzw0aQkOyhSkUUqWPhE,558
|
|
2
|
+
katcloud/client.py,sha256=g0koVFaHQEfSIF5ew8bEROPiYOaWJhThOJjWZRzwOSs,15478
|
|
3
|
+
katcloud/errors.py,sha256=CaQbOpuNBW0ox_bdrMxzzou4rUbQTz1wRtT3Pz5at-0,2132
|
|
4
|
+
katcloud/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
katcloud/types.py,sha256=ZO4WC3WmA46Ockx6egQYTX9pKV7Ft2d2FbENE-s3F80,3815
|
|
6
|
+
katcloud/webhook.py,sha256=3i-plHYY5g75TQH8k_8aF1SQXIazK0C-uNN2R2eZ33w,3483
|
|
7
|
+
katcloud-0.1.0.dist-info/METADATA,sha256=GYSAAhmP_RA34Lpc74y-AifhrUl9_1xV-trsUZ4KQAk,1876
|
|
8
|
+
katcloud-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
katcloud-0.1.0.dist-info/top_level.txt,sha256=52a-2C7Y13ZgC_LxXy8I99QrjLUSXOvxGQ0u9AzqPg0,9
|
|
10
|
+
katcloud-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
katcloud
|