@noti-bot/sdk 0.11.0 → 0.13.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 +33 -7
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +1 -0
- package/dist/index.d.ts +54 -6
- package/dist/index.js +74 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -71,24 +71,33 @@ await kakao.sendMessage({
|
|
|
71
71
|
|
|
72
72
|
## 이미지 보내기
|
|
73
73
|
|
|
74
|
-
`text` 대신 `imageUrl
|
|
74
|
+
`text` 대신 `imageUrl`(공개 주소) 또는 `image`(파일 바이트)를 주면 이미지 한 장을 보냅니다. 키에 `messages:image` 권한이 있어야 합니다(키를 만들 때 따로 고릅니다).
|
|
75
75
|
|
|
76
76
|
```ts
|
|
77
|
+
// 주소로: 허브가 한 번 내려받습니다
|
|
77
78
|
await bot.sendMessage({
|
|
78
79
|
roomSlug: "reports",
|
|
79
80
|
imageUrl: "https://cdn.example.com/reports/2026-11-30.png",
|
|
80
81
|
requestId: "report:2026-11-30",
|
|
81
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
|
+
});
|
|
82
91
|
```
|
|
83
92
|
|
|
84
93
|
- 주소는 `https://`로 시작하는 공개 주소여야 하고, 리다이렉트 없이 이미지를 바로 돌려줘야 합니다.
|
|
85
|
-
- PNG·JPEG·GIF, 5MB
|
|
86
|
-
-
|
|
87
|
-
-
|
|
88
|
-
-
|
|
94
|
+
- PNG·JPEG·WebP·AVIF·GIF, 원본 15MB 이하(GIF는 5MB). 형식은 파일 내용으로 판단합니다.
|
|
95
|
+
- GIF 외에는 긴 변 2560px 이하로 줄이고 메타데이터(EXIF·위치 정보)를 지워서 보냅니다.
|
|
96
|
+
- `text`·`mentions`·`replyTo`와 같이 쓸 수 없고, `imageUrl`과 `image`도 같이 못 씁니다. 글을 같이 보내려면 요청을 따로 보내세요.
|
|
97
|
+
- 같은 `requestId`로 다시 보내면 중복으로 처리합니다. 같은 `requestId`에 다른 파일이면 `idempotency_conflict`.
|
|
89
98
|
- 이미지 메시지는 수정할 수 없습니다(REST `PATCH /v1/messages/{requestId}`는 `edit_not_supported`). 삭제와 공감은 됩니다.
|
|
90
99
|
|
|
91
|
-
거절은 `NotiBotApiError`의 `code`로 옵니다: `image_url_not_allowed`(보낼 수 없는 주소), `image_fetch_failed`(받지
|
|
100
|
+
거절은 `NotiBotApiError`의 `code`로 옵니다: `image_url_not_allowed`(보낼 수 없는 주소), `image_fetch_failed`(받지 못함, HTTP 422), `image_too_large`, `unsupported_image`, `image_send_disabled`(서비스에서 꺼져 있음), `plan_image_not_allowed`(이미지를 보낼 수 없는 플랜), `image_busy`(잠시 뒤 다시), `image_processing_unavailable`(HTTP 503, `retryAfterMs` 뒤 다시).
|
|
92
101
|
|
|
93
102
|
## 이름으로 태그
|
|
94
103
|
|
|
@@ -111,6 +120,22 @@ if (target) await bot.sendMessage({ roomSlug: "tf", text: `${target.mention} 확
|
|
|
111
120
|
|
|
112
121
|
그 방에 없는 사람이면 `mention_unresolved`로 발송되지 않습니다. 상황에 따라 태그 없이 `@이름` 글자로만 나갈 수 있습니다.
|
|
113
122
|
|
|
123
|
+
## "입력 중" 표시
|
|
124
|
+
|
|
125
|
+
답을 만드는 데 시간이 걸릴 때(AI 응답 등) `setTyping`을 먼저 부르면, 방 사람들에게 봇이 "입력 중"으로 보입니다. 준비되면 `sendMessage`로 보내세요. 메시지가 나가면 표시는 바로 꺼집니다.
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
await bot.setTyping({ room: event.room }); // 웹훅의 방 이름, 10초
|
|
129
|
+
// 또는 { roomSlug: "tf" } / { roomId: "…" }
|
|
130
|
+
const answer = await generateAnswer(event.content); // 오래 걸리는 작업
|
|
131
|
+
await bot.sendMessage({ room: event.room, text: answer, replyTo: event.messageId });
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
- `durationSeconds`(1~30, 기본 10)초 동안 보입니다. 더 오래 걸리면 끝나기 전에 다시 부르세요. 다시 부르면 그때부터 다시 셉니다.
|
|
135
|
+
- 접수만 하고 기다리지 않습니다. 상대 화면에 보였는지는 카카오톡이 알려 주지 않고, 봇폰이 연결돼 있지 않으면 조용히 건너뜁니다. 실패해도 발송에는 영향이 없으니 결과를 기다리지 않아도 됩니다.
|
|
136
|
+
- `messages:send` 권한이 필요하고, 방마다 분당 30번까지입니다(넘으면 `429 rate_limited`, `body.scope: "room_typing"`). 아직 카톡 방과 연결되지 않은 방은 `409 typing_unsupported`.
|
|
137
|
+
- 테스트 키는 `{ typing: false, test: true }`로 답하고 폰에 넘기지 않습니다.
|
|
138
|
+
|
|
114
139
|
## 오류 처리
|
|
115
140
|
|
|
116
141
|
모든 오류는 `NotiBotError`를 상속합니다. 한 번의 `catch`로 전부 받고, `name`이나 `instanceof`로 갈라 봅니다.
|
|
@@ -146,6 +171,7 @@ try {
|
|
|
146
171
|
|
|
147
172
|
## 변경 이력
|
|
148
173
|
|
|
174
|
+
- **0.13.0** — `setTyping({ room | roomId | roomSlug, durationSeconds? })`: 봇의 "입력 중" 표시(`POST /v1/typing`, `/v1/rooms/{slug}/typing`).
|
|
149
175
|
- **0.9.0** — `getMessage(requestId)`: 보낸 메시지의 전달 결과(`GET /v1/messages/{requestId}`).
|
|
150
176
|
- **0.8.0** — 워크스페이스 API 키(`nb_live_`/`nb_test_`). `kb_` 키는 더 이상 동작하지 않음. 콘솔에서 새로 발급해 교체하세요. `room_not_bound` 대신 `404 room_not_found`.
|
|
151
177
|
|
|
@@ -160,7 +186,7 @@ pnpm --filter @noti-bot/sdk pack --pack-destination /tmp/notibot-sdk-release
|
|
|
160
186
|
|
|
161
187
|
## 키 권한
|
|
162
188
|
|
|
163
|
-
대시보드에서 키 이름과 허용 작업을 선택합니다. `listRooms()`는 `rooms:read`, `sendMessage()
|
|
189
|
+
대시보드에서 키 이름과 허용 작업을 선택합니다. `listRooms()`는 `rooms:read`, `sendMessage()`·`setTyping()`은 `messages:send`(이미지는 `messages:image`도)가 필요하며 부족하면 `403 insufficient_scope`가 반환됩니다. 키 권한은 워크스페이스의 방 범위를 넓히지 않습니다. 권한을 바꾸려면 새 키를 발급하고 연동을 교체한 뒤 이전 키를 폐기하세요.
|
|
164
190
|
|
|
165
191
|
## 실제 발송 없는 테스트 키
|
|
166
192
|
|
package/dist/errors.d.ts
CHANGED
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
*/
|
|
20
20
|
export declare const NOTIBOT_ERROR_BRAND: unique symbol;
|
|
21
21
|
/** 허브가 돌려주는 오류 코드. 서버 라우트(`src/outbound/routes.ts`)가 정본이다. */
|
|
22
|
-
export declare const NOTIBOT_ERROR_CODES: readonly ["validation_error", "invalid_room_slug", "unauthorized", "plan_message_limit", "insufficient_scope", "room_not_found", "message_not_found", "room_inactive", "idempotency_conflict", "rate_limited", "kill_switch", "queue_full", "request_failed"];
|
|
22
|
+
export declare const NOTIBOT_ERROR_CODES: readonly ["validation_error", "invalid_room_slug", "unauthorized", "plan_message_limit", "insufficient_scope", "room_not_found", "message_not_found", "room_inactive", "idempotency_conflict", "rate_limited", "kill_switch", "queue_full", "typing_unsupported", "request_failed"];
|
|
23
23
|
export type NotiBotErrorCode = (typeof NOTIBOT_ERROR_CODES)[number];
|
|
24
24
|
/**
|
|
25
25
|
* 알려진 코드는 자동완성으로 뜨되, 허브가 새 코드를 추가해도 타입이 깨지지 않는다.
|
package/dist/errors.js
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -33,6 +33,8 @@ export type SendMessageInput = ({
|
|
|
33
33
|
/** `<@kakaoUserId>` (see {@link mention}) becomes a real Kakao tag. */
|
|
34
34
|
text: string;
|
|
35
35
|
imageUrl?: never;
|
|
36
|
+
image?: never;
|
|
37
|
+
filename?: never;
|
|
36
38
|
/**
|
|
37
39
|
* Tag people by display name (e.g. `["김철수"]`). Each must match exactly one room member;
|
|
38
40
|
* `@이름` in `text` becomes the tag, otherwise tags go first. Unknown or ambiguous names
|
|
@@ -46,14 +48,33 @@ export type SendMessageInput = ({
|
|
|
46
48
|
replyTo?: string;
|
|
47
49
|
} | {
|
|
48
50
|
/**
|
|
49
|
-
* Send one image instead of text: a public `https://` address of a PNG, JPEG
|
|
50
|
-
* to 5 MB, served directly (no redirect). The hub downloads it once
|
|
51
|
-
* request. Requires the `messages:image` scope. Cannot be combined
|
|
52
|
-
* `mentions` or `replyTo`. Rejections: `image_url_not_allowed`,
|
|
53
|
-
* `image_too_large`, `unsupported_image`,
|
|
54
|
-
*
|
|
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`, `plan_image_not_allowed`, `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.
|
|
55
59
|
*/
|
|
56
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;
|
|
57
78
|
text?: never;
|
|
58
79
|
mentions?: never;
|
|
59
80
|
replyTo?: never;
|
|
@@ -134,6 +155,27 @@ export interface InboundWebhookEvent {
|
|
|
134
155
|
}[];
|
|
135
156
|
test?: boolean;
|
|
136
157
|
}
|
|
158
|
+
/** `room` 은 방 이름(웹훅 이벤트의 `room`). `roomId`·`roomSlug` 와 같이 쓰지 않는다 */
|
|
159
|
+
export type SetTypingInput = ({
|
|
160
|
+
roomId: string;
|
|
161
|
+
} | {
|
|
162
|
+
roomSlug: string;
|
|
163
|
+
} | {
|
|
164
|
+
room: string;
|
|
165
|
+
}) & {
|
|
166
|
+
/** 몇 초 동안 보일지. 1~30, 기본 10. 그 방으로 봇 메시지가 나가면 바로 꺼진다 */
|
|
167
|
+
durationSeconds?: number;
|
|
168
|
+
};
|
|
169
|
+
export interface SetTypingResult {
|
|
170
|
+
ok: true;
|
|
171
|
+
/** 폰에 넘길 요청을 접수했는지. 테스트 키(`nb_test_`)는 false */
|
|
172
|
+
typing: boolean;
|
|
173
|
+
durationSeconds: number;
|
|
174
|
+
/** 표시가 끝나는 시각(ISO 8601). 테스트 키에는 없다 */
|
|
175
|
+
until?: string;
|
|
176
|
+
room?: string;
|
|
177
|
+
test?: boolean;
|
|
178
|
+
}
|
|
137
179
|
export interface RequestOptions {
|
|
138
180
|
signal?: AbortSignal;
|
|
139
181
|
}
|
|
@@ -169,5 +211,11 @@ export declare class NotiBot {
|
|
|
169
211
|
}) & {
|
|
170
212
|
q?: string;
|
|
171
213
|
}, options?: RequestOptions): Promise<RoomMembers>;
|
|
214
|
+
/**
|
|
215
|
+
* 방 사람들에게 봇이 "입력 중"으로 보이게 한다. 답을 만드는 데 시간이 걸릴 때 먼저 부르고,
|
|
216
|
+
* 준비되면 `sendMessage` 로 보낸다(메시지가 나가면 바로 꺼진다). 더 오래 보이려면 끝나기 전에 다시 부른다.
|
|
217
|
+
* 접수만 하고 기다리지 않으며, 상대에게 보였는지는 알 수 없다. `messages:send` 권한, 방마다 분당 30번.
|
|
218
|
+
*/
|
|
219
|
+
setTyping(input: SetTypingInput, options?: RequestOptions): Promise<SetTypingResult>;
|
|
172
220
|
private request;
|
|
173
221
|
}
|
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,8 +45,23 @@ 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
|
-
(input.imageUrl === undefined &&
|
|
48
|
+
(input.imageUrl === undefined &&
|
|
49
|
+
input.image === undefined &&
|
|
50
|
+
(!input.text?.trim() || input.text.length > 4000)))
|
|
47
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
|
+
}
|
|
48
65
|
if (input.imageUrl !== undefined) {
|
|
49
66
|
if (input.text !== undefined || input.mentions !== undefined || input.replyTo !== undefined)
|
|
50
67
|
throw new TypeError("imageUrl cannot be combined with text, mentions or replyTo.");
|
|
@@ -56,11 +73,20 @@ export class NotiBot {
|
|
|
56
73
|
throw new TypeError("requestId must contain 1 to 128 characters.");
|
|
57
74
|
if (input.replyTo !== undefined && !/^\d{1,20}$/.test(input.replyTo))
|
|
58
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
|
+
}
|
|
59
85
|
const data = await this.request(input.roomId !== undefined
|
|
60
86
|
? `/v1/rooms/id/${encodeURIComponent(input.roomId)}/messages`
|
|
61
87
|
: input.roomSlug !== undefined
|
|
62
88
|
? `/v1/rooms/${encodeURIComponent(input.roomSlug)}/messages`
|
|
63
|
-
: "/v1/messages", "POST", {
|
|
89
|
+
: "/v1/messages", "POST", uploadForm ?? {
|
|
64
90
|
room: input.room,
|
|
65
91
|
...(input.imageUrl !== undefined ? { image_url: input.imageUrl } : { msg: input.text }),
|
|
66
92
|
request_id: requestId,
|
|
@@ -141,6 +167,45 @@ export class NotiBot {
|
|
|
141
167
|
syncedAt: typeof data.syncedAt === "number" ? data.syncedAt : null,
|
|
142
168
|
};
|
|
143
169
|
}
|
|
170
|
+
/**
|
|
171
|
+
* 방 사람들에게 봇이 "입력 중"으로 보이게 한다. 답을 만드는 데 시간이 걸릴 때 먼저 부르고,
|
|
172
|
+
* 준비되면 `sendMessage` 로 보낸다(메시지가 나가면 바로 꺼진다). 더 오래 보이려면 끝나기 전에 다시 부른다.
|
|
173
|
+
* 접수만 하고 기다리지 않으며, 상대에게 보였는지는 알 수 없다. `messages:send` 권한, 방마다 분당 30번.
|
|
174
|
+
*/
|
|
175
|
+
async setTyping(input, options = {}) {
|
|
176
|
+
const duration = input.durationSeconds;
|
|
177
|
+
if (duration !== undefined && (!Number.isInteger(duration) || duration < 1 || duration > 30))
|
|
178
|
+
throw new TypeError("durationSeconds must be an integer between 1 and 30.");
|
|
179
|
+
if ("roomId" in input
|
|
180
|
+
? !input.roomId?.trim()
|
|
181
|
+
: "roomSlug" in input
|
|
182
|
+
? !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(input.roomSlug ?? "")
|
|
183
|
+
: !input.room?.trim())
|
|
184
|
+
throw new TypeError("room, roomId or a valid roomSlug is required.");
|
|
185
|
+
const data = await this.request("roomId" in input
|
|
186
|
+
? `/v1/rooms/id/${encodeURIComponent(input.roomId)}/typing`
|
|
187
|
+
: "roomSlug" in input
|
|
188
|
+
? `/v1/rooms/${encodeURIComponent(input.roomSlug)}/typing`
|
|
189
|
+
: "/v1/typing", "POST", {
|
|
190
|
+
...("room" in input ? { room: input.room } : {}),
|
|
191
|
+
...(duration === undefined ? {} : { duration_s: duration }),
|
|
192
|
+
}, options.signal);
|
|
193
|
+
if (!object(data) ||
|
|
194
|
+
data.ok !== true ||
|
|
195
|
+
typeof data.typing !== "boolean" ||
|
|
196
|
+
typeof data.duration_s !== "number" ||
|
|
197
|
+
(data.until !== undefined && typeof data.until !== "string") ||
|
|
198
|
+
(data.room !== undefined && typeof data.room !== "string"))
|
|
199
|
+
throw new NotiBotProtocolError();
|
|
200
|
+
return {
|
|
201
|
+
ok: true,
|
|
202
|
+
typing: data.typing,
|
|
203
|
+
durationSeconds: data.duration_s,
|
|
204
|
+
...(typeof data.until === "string" ? { until: data.until } : {}),
|
|
205
|
+
...(typeof data.room === "string" ? { room: data.room } : {}),
|
|
206
|
+
...(data.test === true ? { test: true } : {}),
|
|
207
|
+
};
|
|
208
|
+
}
|
|
144
209
|
async request(path, method, body, signal, requestId) {
|
|
145
210
|
const timeout = AbortSignal.timeout(this.timeoutMs);
|
|
146
211
|
const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
@@ -152,9 +217,14 @@ export class NotiBot {
|
|
|
152
217
|
headers: {
|
|
153
218
|
Authorization: `Bearer ${this.apiKey}`,
|
|
154
219
|
Accept: "application/json",
|
|
155
|
-
|
|
220
|
+
// multipart: fetch sets the Content-Type with its boundary
|
|
221
|
+
...(body === undefined || body instanceof FormData
|
|
222
|
+
? {}
|
|
223
|
+
: { "Content-Type": "application/json" }),
|
|
156
224
|
},
|
|
157
|
-
...(body === undefined
|
|
225
|
+
...(body === undefined
|
|
226
|
+
? {}
|
|
227
|
+
: { body: body instanceof FormData ? body : JSON.stringify(body) }),
|
|
158
228
|
signal: combined,
|
|
159
229
|
// API keys must never be forwarded to a redirected origin.
|
|
160
230
|
redirect: "error",
|