@noti-bot/sdk 0.10.0 → 0.12.0
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.
- package/README.md +40 -11
- package/dist/index.d.ts +44 -8
- package/dist/index.js +42 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -56,7 +56,7 @@ await kakao.sendMessage({
|
|
|
56
56
|
|
|
57
57
|
## 답장
|
|
58
58
|
|
|
59
|
-
받은 웹훅의 `messageId`(카톡이 붙인 메시지 ID)를 `replyTo`에 넣으면 그 메시지를 인용한 답장으로 나갑니다. 같은 방의 메시지만 인용할 수 있고, 없는 ID면 발송 결과가 `failed` + `reply_target_not_found`입니다.
|
|
59
|
+
받은 웹훅의 `messageId`(카톡이 붙인 메시지 ID)를 `replyTo`에 넣으면 그 메시지를 인용한 답장으로 나갑니다. 같은 방의 메시지만 인용할 수 있고, 없는 ID면 발송 결과가 `failed` + `reply_target_not_found`입니다.
|
|
60
60
|
|
|
61
61
|
```ts
|
|
62
62
|
await kakao.sendMessage({
|
|
@@ -69,26 +69,56 @@ await kakao.sendMessage({
|
|
|
69
69
|
|
|
70
70
|
웹훅 응답으로 바로 답할 때는 `{"reply": "확인했어요", "reply_to": "<messageId>"}`를 돌려주면 됩니다.
|
|
71
71
|
|
|
72
|
+
## 이미지 보내기
|
|
73
|
+
|
|
74
|
+
`text` 대신 `imageUrl`(공개 주소) 또는 `image`(파일 바이트)를 주면 이미지 한 장을 보냅니다. 키에 `messages:image` 권한이 있어야 합니다(키를 만들 때 따로 고릅니다).
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
// 주소로: 허브가 한 번 내려받습니다
|
|
78
|
+
await bot.sendMessage({
|
|
79
|
+
roomSlug: "reports",
|
|
80
|
+
imageUrl: "https://cdn.example.com/reports/2026-11-30.png",
|
|
81
|
+
requestId: "report:2026-11-30",
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
// 파일로: 공개 주소가 필요 없습니다(multipart/form-data 로 올라갑니다)
|
|
85
|
+
await bot.sendMessage({
|
|
86
|
+
roomSlug: "reports",
|
|
87
|
+
image: await fs.promises.readFile("chart.png"), // Blob 또는 Uint8Array
|
|
88
|
+
filename: "chart.png", // 선택. 허브는 무시합니다
|
|
89
|
+
requestId: "report:2026-12-01",
|
|
90
|
+
});
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
- 주소는 `https://`로 시작하는 공개 주소여야 하고, 리다이렉트 없이 이미지를 바로 돌려줘야 합니다.
|
|
94
|
+
- PNG·JPEG·WebP·AVIF·GIF, 원본 15MB 이하(GIF는 5MB). 형식은 파일 내용으로 판단합니다.
|
|
95
|
+
- GIF 외에는 긴 변 2560px 이하로 줄이고 메타데이터(EXIF·위치 정보)를 지워서 보냅니다.
|
|
96
|
+
- `text`·`mentions`·`replyTo`와 같이 쓸 수 없고, `imageUrl`과 `image`도 같이 못 씁니다. 글을 같이 보내려면 요청을 따로 보내세요.
|
|
97
|
+
- 같은 `requestId`로 다시 보내면 중복으로 처리합니다. 같은 `requestId`에 다른 파일이면 `idempotency_conflict`.
|
|
98
|
+
- 이미지 메시지는 수정할 수 없습니다(REST `PATCH /v1/messages/{requestId}`는 `edit_not_supported`). 삭제와 공감은 됩니다.
|
|
99
|
+
|
|
100
|
+
거절은 `NotiBotApiError`의 `code`로 옵니다: `image_url_not_allowed`(보낼 수 없는 주소), `image_fetch_failed`(받지 못함, HTTP 422), `image_too_large`, `unsupported_image`, `image_send_disabled`(서비스에서 꺼져 있음), `image_busy`(잠시 뒤 다시), `image_processing_unavailable`(HTTP 503, `retryAfterMs` 뒤 다시).
|
|
101
|
+
|
|
72
102
|
## 이름으로 태그
|
|
73
103
|
|
|
74
104
|
이름만 알면 `mentions`로 태그할 수 있습니다. 그 방 참여자 한 명으로 정해져야 보내고, 없거나 여럿이면 `NotiBotApiError`(`mention_name_unknown` / `mention_name_ambiguous`, `body.candidates`)로 거절됩니다.
|
|
75
105
|
|
|
76
106
|
```ts
|
|
77
|
-
await bot.sendMessage({ roomSlug: "tf", text: "
|
|
107
|
+
await bot.sendMessage({ roomSlug: "tf", text: "@김철수 확인 부탁해요", mentions: ["김철수"] });
|
|
78
108
|
```
|
|
79
109
|
|
|
80
110
|
방에 누가 있는지는 `listRoomMembers`(목록만) 또는 `getRoomMembers`(검색 `q`, 인원 `known`/`total`, 오픈채팅 여부, 마지막 동기화)로 봅니다(`rooms:read` 권한). 카톡 방 정보에서 온 계정 ID와, 그 방에서 본 적 있는 표시 이름을 돌려줍니다.
|
|
81
111
|
|
|
82
112
|
```ts
|
|
83
113
|
const members = await bot.listRoomMembers({ roomSlug: "tf" });
|
|
84
|
-
// [{ userId: "
|
|
85
|
-
const target = members.find((m) => m.name === "
|
|
114
|
+
// [{ userId: "1234567890", name: "홍길동", mention: "<@1234567890>" }, { userId: "9876543210", name: null, ... }]
|
|
115
|
+
const target = members.find((m) => m.name === "홍길동");
|
|
86
116
|
if (target) await bot.sendMessage({ roomSlug: "tf", text: `${target.mention} 확인 부탁해요` });
|
|
87
117
|
```
|
|
88
118
|
|
|
89
|
-
`name
|
|
119
|
+
`name`을 아직 모르는 사람은 `null`입니다. 이름을 모르면 태그 글자를 만들 수 없어 `mention_unresolved`로 발송되지 않습니다. 키워드 자동응답(rule) 서비스는 응답 문구에 `{보낸사람}`을 쓰면 말한 사람을 태그합니다.
|
|
90
120
|
|
|
91
|
-
그 방에 없는 사람이면 `mention_unresolved`로 발송되지 않습니다.
|
|
121
|
+
그 방에 없는 사람이면 `mention_unresolved`로 발송되지 않습니다. 상황에 따라 태그 없이 `@이름` 글자로만 나갈 수 있습니다.
|
|
92
122
|
|
|
93
123
|
## 오류 처리
|
|
94
124
|
|
|
@@ -139,7 +169,7 @@ pnpm --filter @noti-bot/sdk pack --pack-destination /tmp/notibot-sdk-release
|
|
|
139
169
|
|
|
140
170
|
## 키 권한
|
|
141
171
|
|
|
142
|
-
대시보드에서 키 이름과 허용 작업을 선택합니다. `listRooms()`는 `rooms:read`, `sendMessage()`는 `messages:send
|
|
172
|
+
대시보드에서 키 이름과 허용 작업을 선택합니다. `listRooms()`는 `rooms:read`, `sendMessage()`는 `messages:send`(이미지는 `messages:image`도)가 필요하며 부족하면 `403 insufficient_scope`가 반환됩니다. 키 권한은 워크스페이스의 방 범위를 넓히지 않습니다. 권한을 바꾸려면 새 키를 발급하고 연동을 교체한 뒤 이전 키를 폐기하세요.
|
|
143
173
|
|
|
144
174
|
## 실제 발송 없는 테스트 키
|
|
145
175
|
|
|
@@ -149,15 +179,14 @@ pnpm --filter @noti-bot/sdk pack --pack-destination /tmp/notibot-sdk-release
|
|
|
149
179
|
|
|
150
180
|
동일 API 키로 이미 접수한 `requestId`의 방 ID 또는 본문을 바꾸면 `409 idempotency_conflict`를 반환합니다. 동일한 방·본문은 중복으로 처리하며 추가 큐/사용량을 만들지 않습니다. slug/방 표시명 변경은 고정 방 ID가 같으면 충돌로 보지 않습니다. 기존 기록 중 본문 검증값이 없는 건은 방 변경만 검출하고 재발송하지 않습니다. 검증값은 서버 비밀키로 보호하므로 비밀키 교체 후 이전 요청의 재시도는 충돌할 수 있습니다.
|
|
151
181
|
|
|
152
|
-
###
|
|
182
|
+
### IDs and webhook events
|
|
153
183
|
|
|
154
184
|
`sendMessage` and `listRooms` retain their existing contracts. Prefer a `roomId` or
|
|
155
|
-
`roomSlug` to a display name.
|
|
156
|
-
SDK clients must not call the phone directly. `queued: true` means accepted by the
|
|
185
|
+
`roomSlug` to a display name. `queued: true` means accepted by the
|
|
157
186
|
hub, not delivered to a recipient, and uncertain sends must not be retried blindly.
|
|
158
187
|
|
|
159
188
|
`InboundWebhookEvent` describes signed webhook events, including optional
|
|
160
|
-
`roomExternalId`, `senderId`, and `imageBase64
|
|
189
|
+
`roomExternalId`, `senderId`, and `imageBase64`. Treat IDs as strings;
|
|
161
190
|
Kakao IDs may exceed JavaScript's safe integer range. Check `X-NotiBot-Signature`
|
|
162
191
|
against the raw request body before parsing. Images are only included for rooms
|
|
163
192
|
explicitly enabled by the owner.
|
package/dist/index.d.ts
CHANGED
|
@@ -27,22 +27,58 @@ export type SendMessageInput = ({
|
|
|
27
27
|
room?: never;
|
|
28
28
|
roomSlug?: never;
|
|
29
29
|
}) & {
|
|
30
|
-
/** `<@kakaoUserId>` (see {@link mention}) becomes a real Kakao tag on the Iris transport. */
|
|
31
|
-
text: string;
|
|
32
30
|
/** Reuse this ID for the same logical send. No automatic retries are performed. */
|
|
33
31
|
requestId?: string;
|
|
32
|
+
} & ({
|
|
33
|
+
/** `<@kakaoUserId>` (see {@link mention}) becomes a real Kakao tag. */
|
|
34
|
+
text: string;
|
|
35
|
+
imageUrl?: never;
|
|
36
|
+
image?: never;
|
|
37
|
+
filename?: never;
|
|
34
38
|
/**
|
|
35
|
-
* Tag people by display name (e.g. `["
|
|
39
|
+
* Tag people by display name (e.g. `["김철수"]`). Each must match exactly one room member;
|
|
36
40
|
* `@이름` in `text` becomes the tag, otherwise tags go first. Unknown or ambiguous names
|
|
37
41
|
* reject with `mention_name_unknown` / `mention_name_ambiguous` (and `candidates`), unsent.
|
|
38
42
|
*/
|
|
39
43
|
mentions?: string[];
|
|
40
44
|
/**
|
|
41
|
-
* Quote a message of the same room: pass `InboundWebhookEvent.messageId`.
|
|
42
|
-
*
|
|
45
|
+
* Quote a message of the same room: pass `InboundWebhookEvent.messageId`.
|
|
46
|
+
* An unknown ID fails with `reply_target_not_found`.
|
|
43
47
|
*/
|
|
44
48
|
replyTo?: string;
|
|
45
|
-
}
|
|
49
|
+
} | {
|
|
50
|
+
/**
|
|
51
|
+
* Send one image instead of text: a public `https://` address of a PNG, JPEG, WebP, AVIF
|
|
52
|
+
* or GIF up to 15 MB (GIF: 5 MB), served directly (no redirect). The hub downloads it once
|
|
53
|
+
* when it accepts the request. Requires the `messages:image` scope. Cannot be combined
|
|
54
|
+
* with `text`, `image`, `mentions` or `replyTo`. Rejections: `image_url_not_allowed`,
|
|
55
|
+
* `image_fetch_failed` (HTTP 422), `image_too_large`, `unsupported_image`,
|
|
56
|
+
* `image_send_disabled`, `image_busy`, `image_processing_unavailable` (HTTP 503, retry later).
|
|
57
|
+
* Images other than GIF are resized to at most 2560 px on the long side and their
|
|
58
|
+
* metadata (EXIF, location) is removed.
|
|
59
|
+
*/
|
|
60
|
+
imageUrl: string;
|
|
61
|
+
image?: never;
|
|
62
|
+
filename?: never;
|
|
63
|
+
text?: never;
|
|
64
|
+
mentions?: never;
|
|
65
|
+
replyTo?: never;
|
|
66
|
+
} | {
|
|
67
|
+
/**
|
|
68
|
+
* Upload one image file (`multipart/form-data`) instead of text: PNG, JPEG, WebP, AVIF or
|
|
69
|
+
* GIF up to 15 MB (GIF: 5 MB). Nothing is fetched by the hub, so no public URL is needed.
|
|
70
|
+
* Requires the `messages:image` scope. Cannot be combined with `text`, `imageUrl`,
|
|
71
|
+
* `mentions` or `replyTo`. The format is detected from the content, not from the name.
|
|
72
|
+
* Same rejections as `imageUrl`, plus `image_too_large` when the upload exceeds 15 MB.
|
|
73
|
+
*/
|
|
74
|
+
image: Blob | Uint8Array;
|
|
75
|
+
/** Optional file name for the upload. The hub ignores it. */
|
|
76
|
+
filename?: string;
|
|
77
|
+
imageUrl?: never;
|
|
78
|
+
text?: never;
|
|
79
|
+
mentions?: never;
|
|
80
|
+
replyTo?: never;
|
|
81
|
+
});
|
|
46
82
|
export interface SendMessageResult {
|
|
47
83
|
ok: true;
|
|
48
84
|
queued: boolean;
|
|
@@ -103,7 +139,7 @@ export interface InboundWebhookEvent {
|
|
|
103
139
|
roomExternalId?: string;
|
|
104
140
|
sender: string;
|
|
105
141
|
senderId?: string;
|
|
106
|
-
/** KakaoTalk's ID of this message
|
|
142
|
+
/** KakaoTalk's ID of this message. Pass it as `replyTo` to quote it. */
|
|
107
143
|
messageId?: string;
|
|
108
144
|
msg: string;
|
|
109
145
|
command: string;
|
|
@@ -112,7 +148,7 @@ export interface InboundWebhookEvent {
|
|
|
112
148
|
received_at: number;
|
|
113
149
|
/** Present only for rooms explicitly enabled by the owner. Never log image bytes. */
|
|
114
150
|
imageBase64?: string;
|
|
115
|
-
/** Accounts the message actually tagged
|
|
151
|
+
/** Accounts the message actually tagged. Compare userId, not name. */
|
|
116
152
|
mentions?: {
|
|
117
153
|
userId: string;
|
|
118
154
|
name?: string;
|
package/dist/index.js
CHANGED
|
@@ -10,6 +10,8 @@ export function mention(kakaoUserId) {
|
|
|
10
10
|
throw new TypeError("kakaoUserId must be a numeric Kakao user ID");
|
|
11
11
|
return `<@${kakaoUserId}>`;
|
|
12
12
|
}
|
|
13
|
+
/** Largest original image the hub accepts. */
|
|
14
|
+
const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
|
|
13
15
|
function object(value) {
|
|
14
16
|
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
15
17
|
}
|
|
@@ -43,21 +45,50 @@ export class NotiBot {
|
|
|
43
45
|
: input.roomSlug !== undefined
|
|
44
46
|
? !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(input.roomSlug)
|
|
45
47
|
: !input.room?.trim()) ||
|
|
46
|
-
|
|
47
|
-
|
|
48
|
+
(input.imageUrl === undefined &&
|
|
49
|
+
input.image === undefined &&
|
|
50
|
+
(!input.text?.trim() || input.text.length > 4000)))
|
|
48
51
|
throw new TypeError("room and text are required; text must be at most 4000 characters.");
|
|
52
|
+
if (input.imageUrl !== undefined && input.image !== undefined)
|
|
53
|
+
throw new TypeError("imageUrl and image cannot be combined.");
|
|
54
|
+
let upload;
|
|
55
|
+
if (input.image !== undefined) {
|
|
56
|
+
if (input.text !== undefined || input.mentions !== undefined || input.replyTo !== undefined)
|
|
57
|
+
throw new TypeError("image cannot be combined with text, mentions or replyTo.");
|
|
58
|
+
upload =
|
|
59
|
+
input.image instanceof Blob
|
|
60
|
+
? input.image
|
|
61
|
+
: new Blob([input.image]);
|
|
62
|
+
if (upload.size < 1 || upload.size > MAX_UPLOAD_BYTES)
|
|
63
|
+
throw new TypeError("image must be between 1 byte and 15 MB.");
|
|
64
|
+
}
|
|
65
|
+
if (input.imageUrl !== undefined) {
|
|
66
|
+
if (input.text !== undefined || input.mentions !== undefined || input.replyTo !== undefined)
|
|
67
|
+
throw new TypeError("imageUrl cannot be combined with text, mentions or replyTo.");
|
|
68
|
+
if (!/^https:\/\/\S+$/.test(input.imageUrl) || input.imageUrl.length > 2048)
|
|
69
|
+
throw new TypeError("imageUrl must be an https:// URL of at most 2048 characters.");
|
|
70
|
+
}
|
|
49
71
|
const requestId = input.requestId ?? globalThis.crypto.randomUUID();
|
|
50
72
|
if (!requestId.trim() || requestId.length > 128)
|
|
51
73
|
throw new TypeError("requestId must contain 1 to 128 characters.");
|
|
52
74
|
if (input.replyTo !== undefined && !/^\d{1,20}$/.test(input.replyTo))
|
|
53
75
|
throw new TypeError("replyTo must be a Kakao message ID (digits only).");
|
|
76
|
+
let uploadForm;
|
|
77
|
+
if (upload) {
|
|
78
|
+
// room 과 request_id 를 파일보다 앞에 둔다: 허브가 한도 검사를 끝낸 뒤에 파일을 읽는다
|
|
79
|
+
uploadForm = new FormData();
|
|
80
|
+
if (input.room !== undefined)
|
|
81
|
+
uploadForm.append("room", input.room);
|
|
82
|
+
uploadForm.append("request_id", requestId);
|
|
83
|
+
uploadForm.append("image", upload, input.filename?.trim() || "image");
|
|
84
|
+
}
|
|
54
85
|
const data = await this.request(input.roomId !== undefined
|
|
55
86
|
? `/v1/rooms/id/${encodeURIComponent(input.roomId)}/messages`
|
|
56
87
|
: input.roomSlug !== undefined
|
|
57
88
|
? `/v1/rooms/${encodeURIComponent(input.roomSlug)}/messages`
|
|
58
|
-
: "/v1/messages", "POST", {
|
|
89
|
+
: "/v1/messages", "POST", uploadForm ?? {
|
|
59
90
|
room: input.room,
|
|
60
|
-
msg: input.text,
|
|
91
|
+
...(input.imageUrl !== undefined ? { image_url: input.imageUrl } : { msg: input.text }),
|
|
61
92
|
request_id: requestId,
|
|
62
93
|
...(input.mentions ? { mentions: input.mentions } : {}),
|
|
63
94
|
...(input.replyTo ? { reply_to: input.replyTo } : {}),
|
|
@@ -147,9 +178,14 @@ export class NotiBot {
|
|
|
147
178
|
headers: {
|
|
148
179
|
Authorization: `Bearer ${this.apiKey}`,
|
|
149
180
|
Accept: "application/json",
|
|
150
|
-
|
|
181
|
+
// multipart: fetch sets the Content-Type with its boundary
|
|
182
|
+
...(body === undefined || body instanceof FormData
|
|
183
|
+
? {}
|
|
184
|
+
: { "Content-Type": "application/json" }),
|
|
151
185
|
},
|
|
152
|
-
...(body === undefined
|
|
186
|
+
...(body === undefined
|
|
187
|
+
? {}
|
|
188
|
+
: { body: body instanceof FormData ? body : JSON.stringify(body) }),
|
|
153
189
|
signal: combined,
|
|
154
190
|
// API keys must never be forwarded to a redirected origin.
|
|
155
191
|
redirect: "error",
|