karboai 1.4.0 → 1.6.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.RU.md ADDED
@@ -0,0 +1,414 @@
1
+ # KarboAI — Русская документация
2
+
3
+ [🇬🇧 English documentation](./README.md)
4
+
5
+ Библиотека для создания ботов в приложении [KarboAI](https://karboai.com).
6
+
7
+ ## Содержание
8
+
9
+ - [Установка](#установка)
10
+ - [Быстрый старт](#быстрый-старт)
11
+ - [Преимущества](#преимущества)
12
+ - [Класс KarboAI](#класс-karboai)
13
+ - [Конструктор](#конструктор)
14
+ - [Геттеры](#геттеры)
15
+ - [Публичные методы](#публичные-методы)
16
+ - [me()](#me)
17
+ - [text()](#text)
18
+ - [image()](#image)
19
+ - [upload()](#upload)
20
+ - [message()](#message)
21
+ - [members()](#members)
22
+ - [user()](#user)
23
+ - [leave()](#leave)
24
+ - [kick()](#kick)
25
+ - [attach()](#attach)
26
+ - [bind()](#bind)
27
+ - [Класс Router](#класс-router)
28
+ - [Конструктор](#конструктор-router)
29
+ - [Геттеры](#геттеры-router)
30
+ - [Методы](#методы-router)
31
+ - [pre()](#pre)
32
+ - [on()](#on)
33
+ - [command()](#command)
34
+ - [Схемы](#схемы)
35
+ - [Логирование](#логирование)
36
+
37
+ ## Установка
38
+
39
+ ```bash
40
+ npm install karboai
41
+ ```
42
+
43
+ ## Быстрый старт
44
+
45
+ ```typescript
46
+ import { KarboAI, Router } from 'karboai';
47
+
48
+ const karbo = new KarboAI({
49
+ token: 'ваш-токен-бота',
50
+ id: 'ваш-id-бота',
51
+ enableLogging: true,
52
+ });
53
+
54
+ const router = new Router();
55
+
56
+ router.command('/start', async ({ karbo, message }) => {
57
+ await karbo.text(message.chatId, 'Привет! Добро пожаловать в KarboAI бот.');
58
+ });
59
+
60
+ router.on('message', async ({ karbo, message }) => {
61
+ await karbo.text(message.chatId, `Вы сказали: ${message.content}`);
62
+ });
63
+
64
+ karbo.bind(router);
65
+ karbo.attach();
66
+ ```
67
+
68
+ ## Преимущества
69
+
70
+ - **Типизация** — Полная поддержка TypeScript с валидацией Zod-схемами всех ответов API
71
+ - **WebSocket** — Обработка сообщений в реальном времени через socket.io-client
72
+ - **Система роутеров** — Модульная архитектура с поддержкой роутеров и промежуточного ПО
73
+ - **Middleware** — Конвейер промежуточного ПО для фильтрации и обработки событий
74
+ - **Команды** — Встроенный парсер команд с поиском по префиксу
75
+ - **Логирование** — Опциональное структурированное логирование через pino
76
+ - **Обработка ошибок** — Исчерпывающие типы ошибок для всех HTTP-статусов
77
+ - **Загрузка файлов** — Поддержка multipart/form-data для загрузки изображений
78
+ - **Чистый API** — Интуитивные имена методов в camelCase
79
+
80
+ ## Класс KarboAI
81
+
82
+ Основной класс для взаимодействия с API KarboAI.
83
+
84
+ ### Конструктор
85
+
86
+ ```typescript
87
+ new KarboAI(config: KarboConfig)
88
+ ```
89
+
90
+ **Параметры:**
91
+ - `config.token` — Токен аутентификации бота
92
+ - `config.id` — ID бота
93
+ - `config.enableLogging?` — Включить логирование (по умолчанию: `false`)
94
+
95
+ **Пример:**
96
+ ```typescript
97
+ const karbo = new KarboAI({
98
+ token: 'ваш-токен-бота',
99
+ id: 'ваш-id-бота',
100
+ enableLogging: true,
101
+ });
102
+ ```
103
+
104
+ ### Геттеры
105
+
106
+ #### `id`
107
+
108
+ Возвращает ID бота из конфигурации.
109
+
110
+ ```typescript
111
+ console.log(karbo.id); // 'ваш-id-бота'
112
+ ```
113
+
114
+ ### Публичные методы
115
+
116
+ #### `me()`
117
+
118
+ Возвращает информацию о боте.
119
+
120
+ **Возвращает:** `Promise<MeResponse>` — Объект с полями `botId`, `name`, `status`
121
+
122
+ **Пример:**
123
+ ```typescript
124
+ const botInfo = await karbo.me();
125
+ console.log(botInfo.name, botInfo.status);
126
+ ```
127
+
128
+ #### `text(chatId, content, replyMessageId?)`
129
+
130
+ Отправляет текстовое сообщение в чат.
131
+
132
+ **Параметры:**
133
+ - `chatId` — ID целевого чата
134
+ - `content` — Текст сообщения
135
+ - `replyMessageId?` — Опциональный ID сообщения для ответа
136
+
137
+ **Возвращает:** `Promise<MessageResponse>` — Объект с `messageId` и `createdAt`
138
+
139
+ **Пример:**
140
+ ```typescript
141
+ await karbo.text('chat-123', 'Привет, мир!');
142
+ await karbo.text('chat-123', 'Отвечаю на сообщение', 'msg-456');
143
+ ```
144
+
145
+ #### `image(chatId, images, replyMessageId?)`
146
+
147
+ Отправляет изображения в чат.
148
+
149
+ **Параметры:**
150
+ - `chatId` — ID целевого чата
151
+ - `images` — Массив URL-адресов изображений
152
+ - `replyMessageId?` — Опциональный ID сообщения для ответа
153
+
154
+ **Возвращает:** `Promise<MessageResponse>` — Объект с `messageId` и `createdAt`
155
+
156
+ **Пример:**
157
+ ```typescript
158
+ await karbo.image('chat-123', ['https://example.com/img1.jpg', 'https://example.com/img2.jpg']);
159
+ ```
160
+
161
+ #### `upload(path)`
162
+
163
+ Загружает файл изображения и возвращает его URL.
164
+
165
+ **Параметры:**
166
+ - `path` — Путь к файлу на диске
167
+
168
+ **Возвращает:** `Promise<string>` — URL загруженного изображения
169
+
170
+ **Пример:**
171
+ ```typescript
172
+ const imageUrl = await karbo.upload('/путь/к/изображению.png');
173
+ await karbo.image('chat-123', [imageUrl]);
174
+ ```
175
+
176
+ #### `message(chatId, messageId)`
177
+
178
+ Получает конкретное сообщение из чата.
179
+
180
+ **Параметры:**
181
+ - `chatId` — ID чата
182
+ - `messageId` — ID сообщения
183
+
184
+ **Возвращает:** `Promise<Message>` — Объект сообщения
185
+
186
+ **Пример:**
187
+ ```typescript
188
+ const msg = await karbo.message('chat-123', 'msg-456');
189
+ console.log(msg.content, msg.author);
190
+ ```
191
+
192
+ #### `members(chatId, limit?, offset?)`
193
+
194
+ Получает участников чата.
195
+
196
+ **Параметры:**
197
+ - `chatId` — ID чата
198
+ - `limit?` — Количество участников (по умолчанию: `100`)
199
+ - `offset?` — Смещение для пагинации (по умолчанию: `0`)
200
+
201
+ **Возвращает:** `Promise<MembersResponse>` — Объект с массивом `items` типа `User`
202
+
203
+ **Пример:**
204
+ ```typescript
205
+ const members = await karbo.members('chat-123', 50, 0);
206
+ console.log(members.items);
207
+ ```
208
+
209
+ #### `user(userId)`
210
+
211
+ Получает информацию о пользователе.
212
+
213
+ **Параметры:**
214
+ - `userId` — ID пользователя
215
+
216
+ **Возвращает:** `Promise<User>` — Объект пользователя
217
+
218
+ **Пример:**
219
+ ```typescript
220
+ const user = await karbo.user('user-123');
221
+ console.log(user);
222
+ ```
223
+
224
+ #### `leave(chatId)`
225
+
226
+ Заставляет бота покинуть чат.
227
+
228
+ **Параметры:**
229
+ - `chatId` — ID чата
230
+
231
+ **Возвращает:** `Promise<boolean>` — Статус успешности
232
+
233
+ **Пример:**
234
+ ```typescript
235
+ const success = await karbo.leave('chat-123');
236
+ ```
237
+
238
+ #### `kick(chatId, userId)`
239
+
240
+ Выгоняет пользователя из чата.
241
+
242
+ **Параметры:**
243
+ - `chatId` — ID чата
244
+ - `userId` — ID пользователя для выгона
245
+
246
+ **Возвращает:** `Promise<boolean>` — Статус успешности
247
+
248
+ **Пример:**
249
+ ```typescript
250
+ const success = await karbo.kick('chat-123', 'user-456');
251
+ ```
252
+
253
+ #### `attach(callback?)`
254
+
255
+ Подключается к WebSocket KarboAI и начинает прослушивать события.
256
+
257
+ **Параметры:**
258
+ - `callback?` — Асинхронная функция, вызываемая после успешного подключения
259
+
260
+ **Пример:**
261
+ ```typescript
262
+ karbo.attach(async () => {
263
+ console.log('Бот теперь онлайн и слушает сообщения');
264
+ });
265
+ ```
266
+
267
+ #### `bind(...routers)`
268
+
269
+ Привязывает один или несколько роутеров к диспетчеру.
270
+
271
+ **Параметры:**
272
+ - `...routers` — Rest-параметр с экземплярами `Router`
273
+
274
+ **Пример:**
275
+ ```typescript
276
+ const mainRouter = new Router('main');
277
+ const adminRouter = new Router('admin');
278
+
279
+ mainRouter.command('/start', async ({ karbo, message }) => {
280
+ await karbo.text(message.chatId, 'Привет!');
281
+ });
282
+
283
+ adminRouter.command('/ban', async ({ karbo, message }) => {
284
+ // логика администратора
285
+ });
286
+
287
+ karbo.bind(mainRouter, adminRouter);
288
+ ```
289
+
290
+ ## Класс Router
291
+
292
+ Класс для организации обработчиков событий в модульные единицы.
293
+
294
+ ### Конструктор
295
+
296
+ ```typescript
297
+ new Router(name?: string)
298
+ ```
299
+
300
+ **Параметры:**
301
+ - `name?` — Имя роутера (генерируется автоматически, если не указано)
302
+
303
+ **Пример:**
304
+ ```typescript
305
+ const router = new Router('my-router');
306
+ ```
307
+
308
+ ### Геттеры
309
+
310
+ #### `name`
311
+
312
+ Возвращает имя роутера.
313
+
314
+ ```typescript
315
+ console.log(router.name); // 'my-router'
316
+ ```
317
+
318
+ #### `listeners`
319
+
320
+ Возвращает `Map` всех зарегистрированных обработчиков событий.
321
+
322
+ ```typescript
323
+ console.log(router.listeners); // Map<SocketEvent, Set<Listener>>
324
+ ```
325
+
326
+ ### Методы
327
+
328
+ #### `pre(middleware)`
329
+
330
+ Добавляет промежуточное ПО, выполняемое до вызова callback'ов событий.
331
+
332
+ **Параметры:**
333
+ - `middleware` — Функция, принимающая `KarboContext` и возвращающая `Promise<boolean>`
334
+
335
+ **Пример:**
336
+ ```typescript
337
+ router.pre(async ({ message }) => {
338
+ // Обрабатывать только сообщения с содержимым
339
+ return message.content.length > 0;
340
+ });
341
+ ```
342
+
343
+ #### `on(event, callback)`
344
+
345
+ Регистрирует обработчик события.
346
+
347
+ **Параметры:**
348
+ - `event` — Тип события (`'message'` | `'join'` | `'leave'` | `'voiceStart'` | `'voiceEnd'` | `'sticker'`)
349
+ - `callback` — Асинхронная функция, принимающая `KarboContext`
350
+
351
+ **Пример:**
352
+ ```typescript
353
+ router.on('message', async ({ karbo, message }) => {
354
+ console.log(`Новое сообщение в ${message.chatId}: ${message.content}`);
355
+ await karbo.text(message.chatId, 'Понял!');
356
+ });
357
+
358
+ router.on('join', async ({ karbo, message }) => {
359
+ await karbo.text(message.chatId, `Добро пожаловать, ${message.author.userId}!`);
360
+ });
361
+ ```
362
+
363
+ #### `command(startsWith, callback)`
364
+
365
+ Регистрирует обработчик команд, срабатывающий когда содержимое сообщения начинается с указанной строки.
366
+
367
+ **Параметры:**
368
+ - `startsWith` — Префикс команды для сопоставления
369
+ - `callback` — Асинхронная функция, принимающая `KarboContext`
370
+
371
+ **Пример:**
372
+ ```typescript
373
+ router.command('/help', async ({ karbo, message }) => {
374
+ await karbo.text(message.chatId, 'Доступные команды: /start, /help');
375
+ });
376
+
377
+ router.command('/start', async ({ karbo, message }) => {
378
+ await karbo.text(message.chatId, 'Добро пожаловать!');
379
+ });
380
+ ```
381
+
382
+ ## Схемы
383
+
384
+ Библиотека экспортирует несколько TypeScript-типов и Zod-схем:
385
+
386
+ - `KarboConfig` — Конфигурация для класса KarboAI
387
+ - `SendMessageConfig` — Конфигурация для отправки сообщений
388
+ - `Message` — Структура объекта сообщения
389
+ - `User`, `Author`, `Member` — Типы, связанные с пользователями
390
+ - `KarboContext` — Контекст, передаваемый в callback'и событий
391
+
392
+ ```typescript
393
+ import { KarboConfig, Message, KarboContext, User } from 'karboai';
394
+ ```
395
+
396
+ ## Логирование
397
+
398
+ Включите структурированное логирование, установив `enableLogging: true` в конфигурации:
399
+
400
+ ```typescript
401
+ const karbo = new KarboAI({
402
+ token: 'ваш-токен',
403
+ id: 'ваш-id',
404
+ enableLogging: true,
405
+ });
406
+ ```
407
+
408
+ Логи включают HTTP-запросы, коды статусов и входящие события.
409
+
410
+ ---
411
+
412
+ **Лицензия:** MIT
413
+ **Автор:** celt_is_god
414
+ **Репозиторий:** [github.com/thatcelt/KarboAI](https://github.com/thatcelt/KarboAI)
package/README.md CHANGED
@@ -1 +1,414 @@
1
1
  # KarboAI
2
+
3
+ [🇷🇺 Русская версия документации](./README.RU.md)
4
+
5
+ A powerful library for creating bots in the [KarboAI](https://karboai.com) application.
6
+
7
+ ## Table of Contents
8
+
9
+ - [Installation](#installation)
10
+ - [Quick Start](#quick-start)
11
+ - [Advantages](#advantages)
12
+ - [KarboAI Class](#karboai-class)
13
+ - [Constructor](#constructor)
14
+ - [Getters](#getters)
15
+ - [Public Methods](#public-methods)
16
+ - [me()](#me)
17
+ - [text()](#text)
18
+ - [image()](#image)
19
+ - [upload()](#upload)
20
+ - [message()](#message)
21
+ - [members()](#members)
22
+ - [user()](#user)
23
+ - [leave()](#leave)
24
+ - [kick()](#kick)
25
+ - [attach()](#attach)
26
+ - [bind()](#bind)
27
+ - [Router Class](#router-class)
28
+ - [Constructor](#router-constructor)
29
+ - [Getters](#router-getters)
30
+ - [Methods](#router-methods)
31
+ - [pre()](#pre)
32
+ - [on()](#on)
33
+ - [command()](#command)
34
+ - [Schemas](#schemas)
35
+ - [Logging](#logging)
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ npm install karboai
41
+ ```
42
+
43
+ ## Quick Start
44
+
45
+ ```typescript
46
+ import { KarboAI, Router } from 'karboai';
47
+
48
+ const karbo = new KarboAI({
49
+ token: 'your-bot-token',
50
+ id: 'your-bot-id',
51
+ enableLogging: true,
52
+ });
53
+
54
+ const router = new Router();
55
+
56
+ router.command('/start', async ({ karbo, message }) => {
57
+ await karbo.text(message.chatId, 'Hello! Welcome to KarboAI bot.');
58
+ });
59
+
60
+ router.on('message', async ({ karbo, message }) => {
61
+ await karbo.text(message.chatId, `You said: ${message.content}`);
62
+ });
63
+
64
+ karbo.bind(router);
65
+ karbo.attach();
66
+ ```
67
+
68
+ ## Advantages
69
+
70
+ - **Type-safe** — Full TypeScript support with Zod schema validation for all API responses
71
+ - **WebSocket support** — Real-time message handling via socket.io-client
72
+ - **Router system** — Modular architecture with routers and middleware support
73
+ - **Middleware pipeline** — Pre-processing middleware for filtering and transforming events
74
+ - **Command handling** — Built-in command parser with `startsWith` matching
75
+ - **Logging** — Optional structured logging with pino
76
+ - **Error handling** — Comprehensive error types for all HTTP status codes
77
+ - **File uploads** — Multipart form data support for image uploads
78
+ - **Clean API** — Intuitive method names with camelCase conventions
79
+
80
+ ## KarboAI Class
81
+
82
+ Main class for interacting with the KarboAI API.
83
+
84
+ ### Constructor
85
+
86
+ ```typescript
87
+ new KarboAI(config: KarboConfig)
88
+ ```
89
+
90
+ **Parameters:**
91
+ - `config.token` — Bot authentication token
92
+ - `config.id` — Bot ID
93
+ - `config.enableLogging?` — Enable logging (default: `false`)
94
+
95
+ **Example:**
96
+ ```typescript
97
+ const karbo = new KarboAI({
98
+ token: 'your-bot-token',
99
+ id: 'your-bot-id',
100
+ enableLogging: true,
101
+ });
102
+ ```
103
+
104
+ ### Getters
105
+
106
+ #### `id`
107
+
108
+ Returns the bot's ID from the configuration.
109
+
110
+ ```typescript
111
+ console.log(karbo.id); // 'your-bot-id'
112
+ ```
113
+
114
+ ### Public Methods
115
+
116
+ #### `me()`
117
+
118
+ Returns information about the bot.
119
+
120
+ **Returns:** `Promise<MeResponse>` — Object with `botId`, `name`, and `status`
121
+
122
+ **Example:**
123
+ ```typescript
124
+ const botInfo = await karbo.me();
125
+ console.log(botInfo.name, botInfo.status);
126
+ ```
127
+
128
+ #### `text(chatId, content, replyMessageId?)`
129
+
130
+ Sends a text message to a chat.
131
+
132
+ **Parameters:**
133
+ - `chatId` — Target chat ID
134
+ - `content` — Message text
135
+ - `replyMessageId?` — Optional message ID to reply to
136
+
137
+ **Returns:** `Promise<MessageResponse>` — Object with `messageId` and `createdAt`
138
+
139
+ **Example:**
140
+ ```typescript
141
+ await karbo.text('chat-123', 'Hello world!');
142
+ await karbo.text('chat-123', 'Replying to message', 'msg-456');
143
+ ```
144
+
145
+ #### `image(chatId, images, replyMessageId?)`
146
+
147
+ Sends images to a chat.
148
+
149
+ **Parameters:**
150
+ - `chatId` — Target chat ID
151
+ - `images` — Array of image URLs
152
+ - `replyMessageId?` — Optional message ID to reply to
153
+
154
+ **Returns:** `Promise<MessageResponse>` — Object with `messageId` and `createdAt`
155
+
156
+ **Example:**
157
+ ```typescript
158
+ await karbo.image('chat-123', ['https://example.com/img1.jpg', 'https://example.com/img2.jpg']);
159
+ ```
160
+
161
+ #### `upload(path)`
162
+
163
+ Uploads an image file and returns its URL.
164
+
165
+ **Parameters:**
166
+ - `path` — File path on disk
167
+
168
+ **Returns:** `Promise<string>` — Uploaded image URL
169
+
170
+ **Example:**
171
+ ```typescript
172
+ const imageUrl = await karbo.upload('/path/to/image.png');
173
+ await karbo.image('chat-123', [imageUrl]);
174
+ ```
175
+
176
+ #### `message(chatId, messageId)`
177
+
178
+ Retrieves a specific message from a chat.
179
+
180
+ **Parameters:**
181
+ - `chatId` — Chat ID
182
+ - `messageId` — Message ID
183
+
184
+ **Returns:** `Promise<Message>` — Message object
185
+
186
+ **Example:**
187
+ ```typescript
188
+ const msg = await karbo.message('chat-123', 'msg-456');
189
+ console.log(msg.content, msg.author);
190
+ ```
191
+
192
+ #### `members(chatId, limit?, offset?)`
193
+
194
+ Retrieves members of a chat.
195
+
196
+ **Parameters:**
197
+ - `chatId` — Chat ID
198
+ - `limit?` — Number of members to return (default: `100`)
199
+ - `offset?` — Offset for pagination (default: `0`)
200
+
201
+ **Returns:** `Promise<MembersResponse>` — Object with `items` array of `User`
202
+
203
+ **Example:**
204
+ ```typescript
205
+ const members = await karbo.members('chat-123', 50, 0);
206
+ console.log(members.items);
207
+ ```
208
+
209
+ #### `user(userId)`
210
+
211
+ Retrieves information about a user.
212
+
213
+ **Parameters:**
214
+ - `userId` — User ID
215
+
216
+ **Returns:** `Promise<User>` — User object
217
+
218
+ **Example:**
219
+ ```typescript
220
+ const user = await karbo.user('user-123');
221
+ console.log(user);
222
+ ```
223
+
224
+ #### `leave(chatId)`
225
+
226
+ Makes the bot leave a chat.
227
+
228
+ **Parameters:**
229
+ - `chatId` — Chat ID
230
+
231
+ **Returns:** `Promise<boolean>` — Success status
232
+
233
+ **Example:**
234
+ ```typescript
235
+ const success = await karbo.leave('chat-123');
236
+ ```
237
+
238
+ #### `kick(chatId, userId)`
239
+
240
+ Kicks a user from a chat.
241
+
242
+ **Parameters:**
243
+ - `chatId` — Chat ID
244
+ - `userId` — User ID to kick
245
+
246
+ **Returns:** `Promise<boolean>` — Success status
247
+
248
+ **Example:**
249
+ ```typescript
250
+ const success = await karbo.kick('chat-123', 'user-456');
251
+ ```
252
+
253
+ #### `attach(callback?)`
254
+
255
+ Connects to the KarboAI WebSocket and starts listening for events.
256
+
257
+ **Parameters:**
258
+ - `callback?` — Async function called after successful connection
259
+
260
+ **Example:**
261
+ ```typescript
262
+ karbo.attach(async () => {
263
+ console.log('Bot is now online and listening for messages');
264
+ });
265
+ ```
266
+
267
+ #### `bind(...routers)`
268
+
269
+ Binds one or more routers to the dispatcher.
270
+
271
+ **Parameters:**
272
+ - `...routers` — Rest parameter of `Router` instances
273
+
274
+ **Example:**
275
+ ```typescript
276
+ const mainRouter = new Router('main');
277
+ const adminRouter = new Router('admin');
278
+
279
+ mainRouter.command('/start', async ({ karbo, message }) => {
280
+ await karbo.text(message.chatId, 'Hello!');
281
+ });
282
+
283
+ adminRouter.command('/ban', async ({ karbo, message }) => {
284
+ // admin logic
285
+ });
286
+
287
+ karbo.bind(mainRouter, adminRouter);
288
+ ```
289
+
290
+ ## Router Class
291
+
292
+ Class for organizing event handlers into modular units.
293
+
294
+ ### Constructor
295
+
296
+ ```typescript
297
+ new Router(name?: string)
298
+ ```
299
+
300
+ **Parameters:**
301
+ - `name?` — Router name (auto-generated if not provided)
302
+
303
+ **Example:**
304
+ ```typescript
305
+ const router = new Router('my-router');
306
+ ```
307
+
308
+ ### Getters
309
+
310
+ #### `name`
311
+
312
+ Returns the router's name.
313
+
314
+ ```typescript
315
+ console.log(router.name); // 'my-router'
316
+ ```
317
+
318
+ #### `listeners`
319
+
320
+ Returns a `Map` of all registered event listeners.
321
+
322
+ ```typescript
323
+ console.log(router.listeners); // Map<SocketEvent, Set<Listener>>
324
+ ```
325
+
326
+ ### Methods
327
+
328
+ #### `pre(middleware)`
329
+
330
+ Adds middleware that runs before event callbacks.
331
+
332
+ **Parameters:**
333
+ - `middleware` — Function that receives `KarboContext` and returns `Promise<boolean>`
334
+
335
+ **Example:**
336
+ ```typescript
337
+ router.pre(async ({ message }) => {
338
+ // Only process messages with content
339
+ return message.content.length > 0;
340
+ });
341
+ ```
342
+
343
+ #### `on(event, callback)`
344
+
345
+ Registers an event listener.
346
+
347
+ **Parameters:**
348
+ - `event` — Event type (`'message'` | `'join'` | `'leave'` | `'voiceStart'` | `'voiceEnd'` | `'sticker'`)
349
+ - `callback` — Async function receiving `KarboContext`
350
+
351
+ **Example:**
352
+ ```typescript
353
+ router.on('message', async ({ karbo, message }) => {
354
+ console.log(`New message in ${message.chatId}: ${message.content}`);
355
+ await karbo.text(message.chatId, 'Got it!');
356
+ });
357
+
358
+ router.on('join', async ({ karbo, message }) => {
359
+ await karbo.text(message.chatId, `Welcome, ${message.author.userId}!`);
360
+ });
361
+ ```
362
+
363
+ #### `command(startsWith, callback)`
364
+
365
+ Registers a command handler that triggers when message content starts with the given string.
366
+
367
+ **Parameters:**
368
+ - `startsWith` — Command prefix to match
369
+ - `callback` — Async function receiving `KarboContext`
370
+
371
+ **Example:**
372
+ ```typescript
373
+ router.command('/help', async ({ karbo, message }) => {
374
+ await karbo.text(message.chatId, 'Available commands: /start, /help');
375
+ });
376
+
377
+ router.command('/start', async ({ karbo, message }) => {
378
+ await karbo.text(message.chatId, 'Welcome!');
379
+ });
380
+ ```
381
+
382
+ ## Schemas
383
+
384
+ The library exports several TypeScript types and Zod schemas:
385
+
386
+ - `KarboConfig` — Configuration for the KarboAI class
387
+ - `SendMessageConfig` — Configuration for sending messages
388
+ - `Message` — Message object structure
389
+ - `User`, `Author`, `Member` — User-related types
390
+ - `KarboContext` — Context passed to event callbacks
391
+
392
+ ```typescript
393
+ import { KarboConfig, Message, KarboContext, User } from 'karboai';
394
+ ```
395
+
396
+ ## Logging
397
+
398
+ Enable structured logging by setting `enableLogging: true` in the config:
399
+
400
+ ```typescript
401
+ const karbo = new KarboAI({
402
+ token: 'your-token',
403
+ id: 'your-id',
404
+ enableLogging: true,
405
+ });
406
+ ```
407
+
408
+ Logs include HTTP requests, status codes, and incoming events.
409
+
410
+ ---
411
+
412
+ **License:** MIT
413
+ **Author:** celt_is_god
414
+ **Repository:** [github.com/thatcelt/KarboAI](https://github.com/thatcelt/KarboAI)
@@ -6,5 +6,9 @@ export declare const ERRORS: Record<number, ErrorData>;
6
6
  export declare const SOCKET_TOPICS: {
7
7
  0: string;
8
8
  1: string;
9
+ 2: string;
10
+ 7: string;
11
+ 8: string;
12
+ 12: string;
9
13
  };
10
14
  //# sourceMappingURL=constants.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,eAAO,MAAM,SAAS,4BAA4B,CAAC;AAEnD,eAAO,MAAM,aAAa,EAAE,aAE3B,CAAC;AAEF,eAAO,MAAM,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAyB5C,CAAC;AAEF,eAAO,MAAM,aAAa;;;CAIzB,CAAC"}
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,eAAO,MAAM,SAAS,4BAA4B,CAAC;AAEnD,eAAO,MAAM,aAAa,EAAE,aAE3B,CAAC;AAEF,eAAO,MAAM,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAyB5C,CAAC;AAEF,eAAO,MAAM,aAAa;;;;;;;CAQzB,CAAC"}
package/dist/constants.js CHANGED
@@ -35,4 +35,8 @@ exports.SOCKET_TOPICS = {
35
35
  // TODO: add more topics
36
36
  0: 'message',
37
37
  1: 'join',
38
+ 2: 'leave',
39
+ 7: 'voiceStart',
40
+ 8: 'voiceEnd',
41
+ 12: 'sticker',
38
42
  };
@@ -1 +1 @@
1
- {"version":3,"file":"dispatcher.d.ts","sourceRoot":"","sources":["../../../src/core/hub/dispatcher.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAyB,MAAM,uBAAuB,CAAC;AAG/E,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAElC,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,qBAAa,UAAU;IACrB,OAAO,CAAC,KAAK,CAAU;IACvB,OAAO,CAAC,MAAM,CAAC,CAAS;IAExB,OAAO,CAAC,SAAS,CAGb;gBAEQ,KAAK,EAAE,OAAO;IAI1B,OAAO,CAAC,gBAAgB,CAsBtB;IAEK,IAAI,GAAI,GAAG,SAAS,MAAM,EAAE,KAAG,IAAI,CAWxC;IAEK,MAAM,GAAI,OAAO,MAAM,EAAE,UAAU,eAAe,KAAG,IAAI,CAa9D;CACH"}
1
+ {"version":3,"file":"dispatcher.d.ts","sourceRoot":"","sources":["../../../src/core/hub/dispatcher.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAyB,MAAM,uBAAuB,CAAC;AAG/E,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAElC,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,qBAAa,UAAU;IACrB,OAAO,CAAC,KAAK,CAAU;IACvB,OAAO,CAAC,MAAM,CAAC,CAAS;IAExB,OAAO,CAAC,SAAS,CAGb;gBAEQ,KAAK,EAAE,OAAO;IAI1B,OAAO,CAAC,gBAAgB,CAuBtB;IAEK,IAAI,GAAI,GAAG,SAAS,MAAM,EAAE,KAAG,IAAI,CAWxC;IAEK,MAAM,GAAI,OAAO,MAAM,EAAE,UAAU,eAAe,KAAG,IAAI,CAa9D;CACH"}
@@ -18,17 +18,18 @@ class Dispatcher {
18
18
  if (message.author.userId == this.karbo.id)
19
19
  return;
20
20
  const event = constants_1.SOCKET_TOPICS[message.type];
21
+ logger_1.LOGGER.info({
22
+ event,
23
+ content: message.content,
24
+ chatId: message.chatId,
25
+ userId: message.author.userId,
26
+ type: message.type,
27
+ });
21
28
  this.listeners.get(event)?.forEach(async (listener) => {
22
29
  for (const middleware of listener.middlewares) {
23
30
  if (!(await middleware({ karbo: this.karbo, message })))
24
31
  return;
25
32
  }
26
- logger_1.LOGGER.info({
27
- event,
28
- content: message.content,
29
- chatId: message.chatId,
30
- userId: message.author.userId,
31
- });
32
33
  listener.callback({ karbo: this.karbo, message });
33
34
  });
34
35
  });
@@ -10,7 +10,7 @@ export declare const MessageSchema: z.ZodPipe<z.ZodObject<{
10
10
  sticker: z.ZodOptional<z.ZodNullable<z.ZodString>>;
11
11
  images: z.ZodArray<z.ZodString>;
12
12
  audio_duration_ms: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
13
- waveform: z.ZodOptional<z.ZodNullable<z.ZodString>>;
13
+ waveform: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodAny>>>;
14
14
  video_note: z.ZodOptional<z.ZodNullable<z.ZodString>>;
15
15
  video_note_duration_ms: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
16
16
  transparent: z.ZodOptional<z.ZodBoolean>;
@@ -96,7 +96,7 @@ export declare const MessageSchema: z.ZodPipe<z.ZodObject<{
96
96
  audio?: string | null | undefined;
97
97
  sticker?: string | null | undefined;
98
98
  audio_duration_ms?: number | null | undefined;
99
- waveform?: string | null | undefined;
99
+ waveform?: any[] | null | undefined;
100
100
  video_note?: string | null | undefined;
101
101
  video_note_duration_ms?: number | null | undefined;
102
102
  transparent?: boolean | undefined;
@@ -15,7 +15,7 @@ exports.MessageSchema = zod_1.z
15
15
  sticker: zod_1.z.string().nullable().optional(),
16
16
  images: zod_1.z.array(zod_1.z.string()),
17
17
  audio_duration_ms: zod_1.z.number().nullable().optional(),
18
- waveform: zod_1.z.string().nullable().optional(),
18
+ waveform: zod_1.z.array(zod_1.z.any()).nullable().optional(),
19
19
  video_note: zod_1.z.string().nullable().optional(),
20
20
  video_note_duration_ms: zod_1.z.number().nullable().optional(),
21
21
  transparent: zod_1.z.boolean().optional(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "karboai",
3
- "version": "1.4.0",
3
+ "version": "1.6.0",
4
4
  "description": "A powerful lib for https://karboai.com",
5
5
  "keywords": [
6
6
  "karbo",