neogram 9.3.0 → 9.3.1

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.
Files changed (2) hide show
  1. package/README.md +518 -1032
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,1239 +1,725 @@
1
- # 📚 neogram v9.3
1
+ # Neogram
2
2
 
3
- **neogram** JavaScript/Node.js порт Python-библиотеки `neogram` v9.3 для работы с **Telegram Bot API** и **AI**.
4
- Полностью сохраняет функционал оригинальной Python-версии, включая все 162 метода Bot API и 281 тип данных.
3
+ **Neogram** is a lightweight JavaScript module for working with the Telegram Bot API and AI. This is a port of the original Python library by SiriLV. It combines simple Telegram workflows with powerful features like text and image generation, translation, and more.
5
4
 
6
- **Автор:** SiriLV
7
- **Почта:** siriteamrs@gmail.com
8
- **Портировщик:** AndrewImm-OP
9
- **Лицензия:** MIT
10
-
11
- ---
12
-
13
- ## 📦 Установка
5
+ ## Installation
14
6
 
15
7
  ```bash
16
8
  npm install neogram
17
9
  ```
18
10
 
19
- или из локального исходника:
20
-
21
- ```bash
22
- cd neogram
23
- npm install
24
- ```
25
-
26
- **Требования:** Node.js 18+ (рекомендуется 20+)
27
-
28
- ## 🛠️ Разработка
29
-
30
- Для разработки и тестирования библиотеки:
31
-
32
- ```bash
33
- # Установка зависимостей
34
- npm install
35
-
36
- # Запуск всех тестов
37
- npm test
38
-
39
- # Запуск тестов с покрытием кода
40
- npm run test:coverage
41
-
42
- # Запуск тестов в режиме наблюдения
43
- npm run test:watch
44
-
45
- # Проверка линтера
46
- npm run lint
47
-
48
- # Автоматическое исправление линтера
49
- npm run lint:fix
50
-
51
- # Проверка типов TypeScript
52
- npm run typecheck
53
-
54
- # Полная проверка CI (линтер + типы + тесты)
55
- npm run ci
56
- ```
57
-
58
- **Тестовое покрытие:** 65.29% (1256 тестов в 44 файлах)
59
-
60
- ## 📘 TypeScript Поддержка
61
-
62
- Библиотека полностью совместима с TypeScript. Типы автоматически подключаются при импорте:
63
-
64
- ```typescript
65
- import { Bot, Message, User } from 'neogram';
66
-
67
- const bot = new Bot('TOKEN');
68
- const message: Message = await bot.getUpdates().then(u => u[0].message!);
69
- const user: User = message.from_user!;
70
- ```
11
+ ## Dependencies
71
12
 
72
- Все 162 метода Bot API и 281 типа данных имеют полные TypeScript декларации.
13
+ - `axios` (^1.7.7) - HTTP client for API requests
14
+ - `cheerio` (^1.0.0) - HTML parser for web scraping
15
+ - `form-data` (^4.0.0) - Form data handling for file uploads
73
16
 
74
- ---
17
+ ## Usage
75
18
 
76
- ## 🚀 Быстрый старт
19
+ ### Importing
77
20
 
78
21
  ```javascript
79
- import { Bot } from 'neogram';
80
-
81
- const bot = new Bot('YOUR_BOT_TOKEN', { timeout: 60_000 });
82
-
83
- // Получение информации о боте
84
- const me = await bot.getMe();
85
- console.log(`Бот запущен: @${me.username}`);
86
-
87
- // Отправка сообщения
88
- await bot.sendMessage({
89
- chat_id: 123456789,
90
- text: 'Привет, мир!'
91
- });
22
+ import { Bot, ChatGPT, OnlySQ, Deef } from 'neogram';
92
23
  ```
93
24
 
94
- ---
95
-
96
- ## 📖 Основной класс `Bot`
97
-
98
- ### Инициализация
25
+ ### Basic Bot Usage
99
26
 
100
27
  ```javascript
101
- import { Bot } from 'neogram';
102
-
103
- const bot = new Bot(token, options);
104
- ```
105
-
106
- **Параметры:**
107
- - `token` (string, обязательный) — токен бота от [@BotFather](https://t.me/BotFather)
108
- - `options` (object, опционально):
109
- - `timeout` (number) — таймаут запросов в миллисекундах (по умолчанию: 60000)
110
-
111
- ### Основные методы
28
+ const bot = new Bot('YOUR_BOT_TOKEN');
112
29
 
113
- Все методы Bot API реализованы как асинхронные функции. Методы принимают объект с параметрами:
114
-
115
- #### Получение обновлений
116
-
117
- ```javascript
118
- // Long Polling
119
- const updates = await bot.getUpdates({
120
- offset: 0,
121
- limit: 100,
122
- timeout: 30,
123
- allowed_updates: ['message', 'callback_query']
124
- });
125
- ```
126
-
127
- #### Отправка сообщений
128
-
129
- ```javascript
130
- // Текстовое сообщение
30
+ // Send a message
131
31
  await bot.sendMessage({
132
- chat_id: 123456789,
133
- text: 'Привет!',
134
- parse_mode: 'HTML',
135
- reply_markup: keyboard
136
- });
137
-
138
- // Фото
139
- await bot.sendPhoto({
140
- chat_id: 123456789,
141
- photo: 'https://example.com/image.jpg', // или Buffer, Stream
142
- caption: 'Описание фото'
143
- });
144
-
145
- // Документ
146
- const fs = await import('fs');
147
- const fileStream = fs.createReadStream('document.pdf');
148
- await bot.sendDocument({
149
- chat_id: 123456789,
150
- document: fileStream,
151
- caption: 'Документ'
152
- });
153
-
154
- // Видео
155
- await bot.sendVideo({
156
- chat_id: 123456789,
157
- video: videoBuffer,
158
- caption: 'Видео',
159
- supports_streaming: true
160
- });
161
-
162
- // Аудио
163
- await bot.sendAudio({
164
- chat_id: 123456789,
165
- audio: audioStream,
166
- performer: 'Исполнитель',
167
- title: 'Название трека'
32
+ chat_id: '@your_channel',
33
+ text: 'Hello from Neogram!'
168
34
  });
169
35
 
170
- // Голосовое сообщение
171
- await bot.sendVoice({
172
- chat_id: 123456789,
173
- voice: voiceBuffer
174
- });
175
- ```
176
-
177
- #### Редактирование сообщений
178
-
179
- ```javascript
180
- // Редактирование текста
181
- await bot.editMessageText({
182
- chat_id: 123456789,
183
- message_id: 123,
184
- text: 'Обновленный текст'
185
- });
186
-
187
- // Редактирование медиа
188
- await bot.editMessageMedia({
189
- chat_id: 123456789,
190
- message_id: 123,
191
- media: newMedia
192
- });
193
- ```
194
-
195
- #### Удаление и копирование
196
-
197
- ```javascript
198
- // Удаление сообщения
199
- await bot.deleteMessage({
200
- chat_id: 123456789,
201
- message_id: 123
202
- });
203
-
204
- // Копирование сообщения
205
- await bot.copyMessage({
206
- chat_id: 123456789,
207
- from_chat_id: 987654321,
208
- message_id: 456
209
- });
210
- ```
211
-
212
- #### Работа с клавиатурами
213
-
214
- ```javascript
215
- import {
216
- ReplyKeyboardMarkup,
217
- KeyboardButton,
218
- InlineKeyboardMarkup,
219
- InlineKeyboardButton
220
- } from 'neogram';
221
-
222
- // Обычная клавиатура
223
- const keyboard = new ReplyKeyboardMarkup({
224
- keyboard: [
225
- [new KeyboardButton({ text: 'Кнопка 1' })],
226
- [new KeyboardButton({ text: 'Кнопка 2' })]
227
- ],
228
- resize_keyboard: true
229
- });
230
-
231
- // Inline клавиатура
232
- const inlineKeyboard = new InlineKeyboardMarkup({
233
- inline_keyboard: [
234
- [
235
- new InlineKeyboardButton({
236
- text: 'Кнопка',
237
- callback_data: 'data'
238
- })
239
- ]
240
- ]
241
- });
242
- ```
243
-
244
- #### Обработка callback-запросов
36
+ // Get bot information
37
+ const me = await bot.getMe();
38
+ console.log(`Bot username: @${me.username}`);
39
+ ```
40
+
41
+ ## Core API Methods
42
+
43
+ The `Bot` class provides comprehensive access to the Telegram Bot API. Here are the main categories of methods:
44
+
45
+ ### Message Management
46
+
47
+ #### Sending Messages
48
+ - `sendMessage(options)` - Send text messages
49
+ - `sendPhoto(options)` - Send photos
50
+ - `sendAudio(options)` - Send audio files
51
+ - `sendDocument(options)` - Send documents
52
+ - `sendVideo(options)` - Send videos
53
+ - `sendAnimation(options)` - Send animations/GIFs
54
+ - `sendVoice(options)` - Send voice messages
55
+ - `sendVideoNote(options)` - Send video notes
56
+ - `sendPaidMedia(options)` - Send paid media
57
+ - `sendMediaGroup(options)` - Send media groups
58
+ - `sendLocation(options)` - Send location
59
+ - `sendVenue(options)` - Send venue information
60
+ - `sendContact(options)` - Send contact information
61
+ - `sendPoll(options)` - Send polls
62
+ - `sendChecklist(options)` - Send checklists
63
+ - `sendDice(options)` - Send dice (games)
64
+ - `sendMessageDraft(options)` - Send message drafts
65
+
66
+ #### Message Actions
67
+ - `deleteMessage(options)` - Delete messages
68
+ - `forwardMessage(options)` - Forward messages
69
+ - `forwardMessages(options)` - Forward multiple messages
70
+ - `copyMessage(options)` - Copy messages
71
+ - `copyMessages(options)` - Copy multiple messages
72
+ - `sendChatAction(options)` - Send chat actions (typing, etc.)
73
+ - `setMessageReaction(options)` - Set message reactions
74
+
75
+ ### Chat Management
76
+
77
+ #### Member Management
78
+ - `banChatMember(options)` - Ban chat members
79
+ - `unbanChatMember(options)` - Unban chat members
80
+ - `restrictChatMember(options)` - Restrict chat members
81
+ - `promoteChatMember(options)` - Promote chat members
82
+ - `setChatAdministratorCustomTitle(options)` - Set admin custom titles
83
+
84
+ #### Chat Settings
85
+ - `setChatTitle(options)` - Set chat title
86
+ - `setChatDescription(options)` - Set chat description
87
+ - `setChatPhoto(options)` - Set chat photo
88
+ - `deleteChatPhoto()` - Delete chat photo
89
+ - `setChatPermissions(options)` - Set chat permissions
90
+ - `exportChatInviteLink(options)` - Export invite links
91
+ - `createChatInviteLink(options)` - Create invite links
92
+ - `editChatInviteLink(options)` - Edit invite links
93
+ - `revokeChatInviteLink(options)` - Revoke invite links
94
+ - `approveChatJoinRequest(options)` - Approve join requests
95
+ - `declineChatJoinRequest(options)` - Decline join requests
96
+ - `setChatStickerSet(options)` - Set chat sticker set
97
+ - `deleteChatStickerSet()` - Delete chat sticker set
98
+
99
+ ### Webhook Management
100
+
101
+ - `setWebhook(options)` - Set webhook URL
102
+ - `deleteWebhook(options)` - Delete webhook
103
+ - `getWebhookInfo()` - Get webhook information
104
+
105
+ ### Updates and Polling
106
+
107
+ - `getUpdates(options)` - Get bot updates
108
+ - `setWebhook(options)` - Set webhook
109
+ - `deleteWebhook(options)` - Delete webhook
110
+ - `getWebhookInfo()` - Get webhook info
111
+
112
+ ### User and File Management
113
+
114
+ - `getUserProfilePhotos(options)` - Get user profile photos
115
+ - `setUserEmojiStatus(options)` - Set user emoji status
116
+ - `getFile(options)` - Get file information
117
+
118
+ ### Bot Commands and Menus
119
+
120
+ - `setMyCommands(options)` - Set bot commands
121
+ - `deleteMyCommands(options)` - Delete bot commands
122
+ - `getMyCommands(options)` - Get bot commands
123
+ - `setMyName(options)` - Set bot name
124
+ - `getMyName(options)` - Get bot name
125
+ - `setMyDescription(options)` - Set bot description
126
+ - `getMyDescription()` - Get bot description
127
+ - `setMyShortDescription(options)` - Set short description
128
+ - `getMyShortDescription()` - Get short description
129
+ - `setChatMenuButton(options)` - Set chat menu button
130
+ - `getChatMenuButton(options)` - Get chat menu button
131
+ - `setMyDefaultAdministratorRights(options)` - Set default admin rights
132
+ - `getMyDefaultAdministratorRights()` - Get default admin rights
133
+
134
+ ### Games and Inline
135
+
136
+ - `sendGame(options)` - Send games
137
+ - `setGameScore(options)` - Set game scores
138
+ - `getGameHighScores(options)` - Get game high scores
139
+ - `answerInlineQuery(options)` - Answer inline queries
140
+ - `answerWebAppQuery(options)` - Answer web app queries
141
+
142
+ ### Stickers and Media
143
+
144
+ - `sendSticker(options)` - Send stickers
145
+ - `getStickerSet(options)` - Get sticker sets
146
+ - `uploadStickerFile(options)` - Upload sticker files
147
+ - `createNewStickerSet(options)` - Create sticker sets
148
+ - `addStickerToSet(options)` - Add stickers to sets
149
+ - `setStickerPositionInSet(options)` - Set sticker positions
150
+ - `deleteStickerFromSet(options)` - Delete stickers from sets
151
+ - `replaceStickerInSet(options)` - Replace stickers in sets
152
+ - `setStickerSetThumbnail(options)` - Set sticker set thumbnails
153
+ - `setStickerSetTitle(options)` - Set sticker set titles
154
+ - `setStickerEmojiList(options)` - Set sticker emoji lists
155
+ - `setStickerKeywords(options)` - Set sticker keywords
156
+ - `setStickerMaskPosition(options)` - Set sticker mask positions
157
+ - `setCustomEmojiStickerSetThumbnail(options)` - Set custom emoji sticker thumbnails
158
+ - `deleteStickerSet(options)` - Delete sticker sets
159
+ - `getCustomEmojiStickers(options)` - Get custom emoji stickers
160
+
161
+ ### Payments and Stars
162
+
163
+ - `sendInvoice(options)` - Send invoices
164
+ - `createInvoiceLink(options)` - Create invoice links
165
+ - `answerPreCheckoutQuery(options)` - Answer pre-checkout queries
166
+ - `answerShippingQuery(options)` - Answer shipping queries
167
+ - `refundStarPayment(options)` - Refund star payments
168
+ - `getStarTransactions(options)` - Get star transactions
169
+ - `sendPaidMedia(options)` - Send paid media
170
+
171
+ ### Business Features
172
+
173
+ - `sendBusinessMessage(options)` - Send business messages
174
+ - `getBusinessConnection(options)` - Get business connections
175
+ - `getBusinessAccount()` - Get business account info
176
+
177
+ ### Stories
178
+
179
+ - `sendStory(options)` - Send stories
180
+ - `editStory(options)` - Edit stories
181
+ - `deleteStory(options)` - Delete stories
182
+ - `getUserStories(options)` - Get user stories
183
+
184
+ ### Forums
185
+
186
+ - `createForumTopic(options)` - Create forum topics
187
+ - `editForumTopic(options)` - Edit forum topics
188
+ - `closeForumTopic(options)` - Close forum topics
189
+ - `reopenForumTopic(options)` - Reopen forum topics
190
+ - `deleteForumTopic(options)` - Delete forum topics
191
+ - `unpinAllForumTopicMessages(options)` - Unpin forum topic messages
192
+ - `editGeneralForumTopic(options)` - Edit general forum topics
193
+ - `closeGeneralForumTopic(options)` - Close general forum topics
194
+ - `reopenGeneralForumTopic(options)` - Reopen general forum topics
195
+ - `hideGeneralForumTopic(options)` - Hide general forum topics
196
+ - `unhideGeneralForumTopic(options)` - Unhide general forum topics
197
+ - `getForumTopicIconStickers()` - Get forum topic icon stickers
198
+
199
+ ## AI Integration
200
+
201
+ Neogram includes several AI classes for enhanced functionality:
202
+
203
+ ### ChatGPT Class
204
+
205
+ Provides access to OpenAI-compatible APIs:
245
206
 
246
207
  ```javascript
247
- // Ответ на callback
248
- await bot.answerCallbackQuery({
249
- callback_query_id: queryId,
250
- text: 'Ответ',
251
- show_alert: true
208
+ const chatgpt = new ChatGPT('https://api.openai.com/v1', {
209
+ 'Authorization': 'Bearer YOUR_API_KEY'
252
210
  });
253
- ```
254
211
 
255
- ### Полный список методов
256
-
257
- Библиотека поддерживает **все 162 метода** Telegram Bot API:
258
-
259
- - `getMe`, `getUpdates`, `setWebhook`, `deleteWebhook`, `getWebhookInfo`
260
- - `sendMessage`, `sendPhoto`, `sendVideo`, `sendAudio`, `sendDocument`, `sendVoice`, `sendVideoNote`, `sendAnimation`, `sendSticker`, `sendDice`, `sendPoll`, `sendPaidMedia`
261
- - `editMessageText`, `editMessageCaption`, `editMessageMedia`, `editMessageReplyMarkup`, `editMessageLiveLocation`, `stopMessageLiveLocation`
262
- - `deleteMessage`, `deleteMessages`, `deleteChatPhoto`, `setChatPhoto`
263
- - `copyMessage`, `forwardMessage`, `forwardMessages`
264
- - `getChat`, `getChatMember`, `getChatAdministrators`, `getChatMemberCount`, `getChatMemberCount`
265
- - `setChatTitle`, `setChatDescription`, `setChatPermissions`, `setChatAdministratorCustomTitle`
266
- - `banChatMember`, `unbanChatMember`, `restrictChatMember`, `promoteChatMember`
267
- - `createChatInviteLink`, `editChatInviteLink`, `revokeChatInviteLink`, `approveChatJoinRequest`, `declineChatJoinRequest`
268
- - `setChatStickerSet`, `deleteChatStickerSet`
269
- - `answerCallbackQuery`, `answerInlineQuery`, `answerWebAppQuery`
270
- - `setMyCommands`, `deleteMyCommands`, `getMyCommands`, `setMyName`, `getMyName`, `setMyDescription`, `getMyDescription`, `setMyShortDescription`, `getMyShortDescription`
271
- - `setChatMenuButton`, `getChatMenuButton`, `setMyDefaultAdministratorRights`, `getMyDefaultAdministratorRights`
272
- - `sendInvoice`, `createInvoiceLink`, `answerPreCheckoutQuery`, `answerShippingQuery`
273
- - `sendGame`, `setGameScore`, `getGameHighScores`
274
- - `setPassportDataErrors`
275
- - `sendGift`, `getOwnedGifts`, `getGiftInfo`
276
- - `sendStars`, `getStarTransactions`, `refundStarPayment`
277
- - `createForumTopic`, `editForumTopic`, `closeForumTopic`, `reopenForumTopic`, `deleteForumTopic`, `unpinAllForumTopicMessages`, `getForumTopicIconStickers`, `editGeneralForumTopic`, `closeGeneralForumTopic`, `reopenGeneralForumTopic`, `hideGeneralForumTopic`, `unhideGeneralForumTopic`
278
- - `uploadStickerFile`, `createNewStickerSet`, `addStickerToSet`, `setStickerPositionInSet`, `deleteStickerFromSet`, `replaceStickerInSet`, `setStickerSetThumbnail`, `setStickerSetTitle`, `setStickerEmojiList`, `setCustomEmojiStickerSetThumbnail`, `deleteStickerSet`, `getStickerSet`
279
- - `getFile`, `downloadFile`
280
- - `setMessageReaction`, `getBusinessConnection`
281
- - И многие другие...
282
-
283
- ---
284
-
285
- ## 📋 Типы данных
286
-
287
- Библиотека включает **281 тип данных** Telegram Bot API, все наследуются от базового класса `TelegramObject`.
288
-
289
- ### Базовый класс `TelegramObject`
290
-
291
- ```javascript
292
- import { TelegramObject } from 'neogram';
293
-
294
- class MyType extends TelegramObject {
295
- field1 = null;
296
- field2 = null;
297
- }
298
-
299
- // Сериализация
300
- const obj = new MyType();
301
- obj.field1 = 'value';
302
- const json = obj.toJSON(); // { field1: 'value' }
303
-
304
- // Десериализация
305
- const restored = MyType.fromJSON(json);
306
- ```
307
-
308
- ### Важные особенности именования
309
-
310
- В JavaScript, как и в Python-версии, некоторые поля Telegram API автоматически преобразуются:
311
-
312
- - `type` → `type_val` (например, в `Chat`, `MessageEntity`, `InputFile`)
313
- - `from` → `from_user` (например, в `Message`, `CallbackQuery`)
314
- - `filter` → `filter_val`
315
-
316
- **Пример:**
212
+ // Generate chat completion
213
+ const response = await chatgpt.generateChatCompletion(
214
+ 'gpt-3.5-turbo',
215
+ [{ role: 'user', content: 'Hello!' }]
216
+ );
317
217
 
318
- ```javascript
319
- import { Message, Chat } from 'neogram';
218
+ // Generate images
219
+ const image = await chatgpt.generateImage('A beautiful sunset');
320
220
 
321
- const update = await bot.getUpdates();
322
- const message = update[0].message;
221
+ // Generate embeddings
222
+ const embedding = await chatgpt.generateEmbedding('text-embedding-ada-002', 'Hello world');
323
223
 
324
- // Используем from_user вместо from
325
- console.log(message.from_user.first_name);
224
+ // Transcribe audio
225
+ const transcription = await chatgpt.generateTranscription(file, 'whisper-1');
326
226
 
327
- // Используем type_val вместо type
328
- console.log(message.chat.type_val); // 'private', 'group', 'supergroup'
227
+ // Translate audio
228
+ const translation = await chatgpt.generateTranslation(file, 'whisper-1');
329
229
  ```
330
230
 
331
- ### Основные типы
231
+ **Methods:**
232
+ - `generateChatCompletion(model, messages, temperature, max_tokens, stream, ...kwargs)`
233
+ - `generateImage(prompt, n, size, response_format, ...kwargs)`
234
+ - `generateEmbedding(model, input, user, ...kwargs)`
235
+ - `generateTranscription(file, model, language, prompt, response_format, temperature, ...kwargs)`
236
+ - `generateTranslation(file, model, prompt, response_format, temperature, ...kwargs)`
237
+ - `getModels()`
332
238
 
333
- ```javascript
334
- import {
335
- Update, Message, User, Chat,
336
- CallbackQuery, InlineQuery,
337
- ReplyKeyboardMarkup, InlineKeyboardMarkup,
338
- BotCommand, File, PhotoSize,
339
- // ... и еще 274 типа
340
- } from 'neogram';
341
- ```
239
+ ### OnlySQ Class
342
240
 
343
- ### Пример работы с типами
241
+ Provides access to OnlySQ AI services:
344
242
 
345
243
  ```javascript
346
- import { Update, Message, User } from 'neogram';
347
-
348
- const updates = await bot.getUpdates();
349
- for (const update of updates) {
350
- if (update.message) {
351
- const msg = update.message;
352
- const user = msg.from_user; // не 'from'!
353
- console.log(`Сообщение от ${user.first_name}: ${msg.text}`);
354
- } else if (update.callback_query) {
355
- const cb = update.callback_query;
356
- console.log(`Callback data: ${cb.data}`);
357
- }
358
- }
359
- ```
360
-
361
- ---
362
-
363
- ## 🤖 Модуль AI (Нейросети)
364
-
365
- Библиотека включает три класса для работы с AI-сервисами.
366
-
367
- ### Класс `OnlySQ`
368
-
369
- Интерфейс к сервису OnlySQ для генерации текста и изображений.
370
-
371
- ```javascript
372
- import { OnlySQ } from 'neogram';
373
-
374
244
  const onlysq = new OnlySQ();
375
245
 
376
- // Получение списка моделей
246
+ // Get available models
377
247
  const models = await onlysq.getModels({
378
- modality: 'text', // 'text' или 'image'
379
- status: 'work', // статус модели
380
- can_tools: true, // поддержка инструментов
381
- can_stream: false, // поддержка стриминга
382
- max_cost: 0.01, // максимальная стоимость
383
- return_names: false // вернуть имена вместо ключей
248
+ modality: 'text', // Filter by modality
249
+ can_tools: true, // Filter by tool capability
250
+ can_stream: false, // Filter by streaming capability
251
+ status: 'active', // Filter by status
252
+ max_cost: 0.01, // Filter by maximum cost
253
+ return_names: true // Return model names instead of IDs
384
254
  });
385
255
 
386
- // Генерация текста
256
+ // Generate text response
387
257
  const answer = await onlysq.generateAnswer('gpt-5.2-chat', [
388
- { role: 'system', content: 'Ты полезный ассистент.' },
389
- { role: 'user', content: 'Привет!' }
258
+ { role: 'user', content: 'Explain quantum computing' }
390
259
  ]);
391
260
 
392
- // Генерация изображения
393
- const success = await onlysq.generateImage(
394
- 'flux', // модель
395
- 'красивый закат', // промпт
396
- '16:9', // соотношение сторон
397
- 'output.png' // имя файла
398
- );
261
+ // Generate image
262
+ await onlysq.generateImage('flux', 'A futuristic city', '16:9', 'output.png');
399
263
  ```
400
264
 
401
- **Методы:**
402
- - `getModels(options)` получить список моделей с фильтрацией
403
- - `generateAnswer(model, messages)` генерация текста
404
- - `generateImage(model, prompt, ratio, filename)` генерация изображения (сохраняет в файл)
265
+ **Methods:**
266
+ - `getModels(options)` - Get filtered list of available models
267
+ - `generateAnswer(model, messages)` - Generate text responses
268
+ - `generateImage(model, prompt, ratio, filename)` - Generate and save images
405
269
 
406
- ### Класс `Deef`
270
+ ### Deef Class
407
271
 
408
- Набор утилит и альтернативных AI API.
272
+ Provides utility AI functions and integrations:
409
273
 
410
274
  ```javascript
411
- import { Deef } from 'neogram';
412
-
413
275
  const deef = new Deef();
414
276
 
415
- // Перевод текста (через Google Translate)
416
- const translated = await deef.translate('Hello, world!', 'ru');
417
- console.log(translated); // 'Привет, мир!'
277
+ // Translate text
278
+ const translation = await deef.translate('Hello world', 'es');
418
279
 
419
- // Сокращение ссылок (clck.ru)
420
- const shortUrl = await deef.shortUrl('https://very-long-url.com/path');
421
- console.log(shortUrl); // короткая ссылка
280
+ // Shorten URLs
281
+ const shortUrl = await deef.shortUrl('https://example.com/very/long/url');
422
282
 
423
- // Генерация ответа через Qwen/GPT OSS (с потоковой выдачей)
283
+ // Generate AI responses
424
284
  const response = await deef.genAiResponse('Qwen3 235B', [
425
- { role: 'user', content: 'Расскажи о JavaScript' }
285
+ { role: 'user', content: 'Explain relativity' }
426
286
  ]);
427
- console.log(response.reasoning); // рассуждения
428
- console.log(response.answer); // ответ
429
- console.log(response.status); // статус
430
287
 
431
- // Генерация через ItalyGPT
288
+ // Generate GPT responses
432
289
  const gptResponse = await deef.genGpt([
433
- { role: 'user', content: 'Привет!' }
290
+ { role: 'user', content: 'Write a haiku about coding' }
434
291
  ]);
435
292
 
436
- // Кодирование файла в base64
437
- const base64 = await deef.encodeBase64('file.txt');
293
+ // Encode files to base64
294
+ const base64 = await deef.encodeBase64('/path/to/file.jpg');
438
295
 
439
- // Запуск функции в фоне
440
- deef.runInBg(async () => {
441
- // асинхронная работа
442
- });
296
+ // Run functions in background
297
+ deef.runInBg(myAsyncFunction, arg1, arg2);
443
298
  ```
444
299
 
445
- **Методы:**
446
- - `translate(text, lang)` перевод текста
447
- - `shortUrl(longUrl)` сокращение ссылок
448
- - `genAiResponse(model, messages)` генерация ответа (Qwen/GPT OSS)
449
- - `genGpt(messages)` генерация через ItalyGPT
450
- - `encodeBase64(path)` кодирование файла в base64
451
- - `runInBg(func, ...args)` запуск функции в фоне
300
+ **Methods:**
301
+ - `translate(text, lang)` - Translate text using Google Translate
302
+ - `shortUrl(longUrl)` - Shorten URLs using clck.ru
303
+ - `genAiResponse(model, messages)` - Generate AI responses with reasoning
304
+ - `genGpt(messages)` - Generate GPT responses
305
+ - `encodeBase64(path)` - Encode files to base64
306
+ - `runInBg(func, ...args)` - Run functions asynchronously in background
452
307
 
453
- ### Класс `ChatGPT`
308
+ ## Type Definitions
454
309
 
455
- Обертка над OpenAI-compatible API.
310
+ The library includes comprehensive TypeScript definitions for all Telegram API objects. All 281+ types are exported and can be imported individually:
456
311
 
457
312
  ```javascript
458
- import { ChatGPT } from 'neogram';
459
-
460
- const chatgpt = new ChatGPT('https://api.openai.com/v1', {
461
- 'Authorization': 'Bearer YOUR_API_KEY'
462
- });
463
-
464
- // Генерация чат-комплишн
465
- const completion = await chatgpt.generateChatCompletion(
466
- 'gpt-4',
467
- [
468
- { role: 'user', content: 'Привет!' }
469
- ],
470
- 0.7, // temperature
471
- 100, // max_tokens
472
- false // stream
473
- );
474
-
475
- // Генерация изображения
476
- const image = await chatgpt.generateImage(
477
- 'красивый пейзаж',
478
- 1, // n
479
- '1024x1024', // size
480
- 'url' // response_format
481
- );
482
-
483
- // Генерация эмбеддингов
484
- const embedding = await chatgpt.generateEmbedding(
485
- 'text-embedding-ada-002',
486
- 'текст для эмбеддинга'
487
- );
488
-
489
- // Транскрипция аудио
490
- const fs = await import('fs');
491
- const audioFile = fs.createReadStream('audio.mp3');
492
- const transcription = await chatgpt.generateTranscription(
493
- audioFile,
494
- 'whisper-1',
495
- 'ru', // language
496
- null, // prompt
497
- 'json' // response_format
498
- );
499
-
500
- // Перевод аудио
501
- const translation = await chatgpt.generateTranslation(
502
- audioFile,
503
- 'whisper-1'
504
- );
505
-
506
- // Получение списка моделей
507
- const models = await chatgpt.getModels();
313
+ import {
314
+ User,
315
+ Message,
316
+ Chat,
317
+ InlineKeyboardMarkup,
318
+ // ... and 278+ more types
319
+ } from 'neogram';
508
320
  ```
509
321
 
510
- **Методы:**
511
- - `generateChatCompletion(model, messages, temperature, max_tokens, stream, ...kwargs)` — чат-комплишн
512
- - `generateImage(prompt, n, size, response_format, ...kwargs)` — генерация изображения
513
- - `generateEmbedding(model, input, user, ...kwargs)` — генерация эмбеддингов
514
- - `generateTranscription(file, model, language, prompt, response_format, temperature, ...kwargs)` — транскрипция аудио
515
- - `generateTranslation(file, model, prompt, response_format, temperature, ...kwargs)` — перевод аудио
516
- - `getModels()` — получение списка моделей
517
-
518
- ---
519
-
520
- ## 💡 Примеры использования
322
+ ## Examples
521
323
 
522
- ### Базовый бот (Long Polling)
324
+ See the `examples/` directory for complete usage examples:
523
325
 
524
- ```javascript
525
- import { Bot, Update } from 'neogram';
526
-
527
- const TOKEN = process.env.BOT_TOKEN;
528
- const bot = new Bot(TOKEN, { timeout: 30_000 });
529
-
530
- async function main() {
531
- console.log('Бот запущен...');
532
- let offset = 0;
533
-
534
- while (true) {
535
- try {
536
- const updates = await bot.getUpdates({
537
- offset,
538
- timeout: 30,
539
- allowed_updates: ['message']
540
- });
541
-
542
- if (!updates || updates.length === 0) continue;
543
-
544
- for (const update of updates) {
545
- offset = update.update_id + 1;
546
-
547
- if (update.message) {
548
- const msg = update.message;
549
- const chatId = msg.chat.id;
550
- const text = msg.text;
551
-
552
- if (text === '/start') {
553
- await bot.sendMessage({
554
- chat_id: chatId,
555
- text: `Привет, ${msg.from_user.first_name}!`
556
- });
557
- } else {
558
- await bot.sendMessage({
559
- chat_id: chatId,
560
- text: `Вы написали: ${text}`
561
- });
562
- }
563
- }
564
- }
565
- } catch (error) {
566
- console.error('Ошибка:', error);
567
- await new Promise(resolve => setTimeout(resolve, 2000));
568
- }
569
- }
570
- }
326
+ - `simple-bot.js` - Basic bot setup
327
+ - `test-bot.js` - Comprehensive bot testing
328
+ - `ai-bot.js` - AI-integrated bot example
571
329
 
572
- main().catch(console.error);
573
- ```
330
+ ### Function Examples
574
331
 
575
- ### Бот с клавиатурами
332
+ #### Message Management
576
333
 
577
334
  ```javascript
578
- import {
579
- Bot,
580
- ReplyKeyboardMarkup,
581
- KeyboardButton,
582
- InlineKeyboardMarkup,
583
- InlineKeyboardButton
584
- } from 'neogram';
585
-
586
- const bot = new Bot(TOKEN);
335
+ // Send formatted message
336
+ await bot.sendMessage({
337
+ chat_id: chatId,
338
+ text: '*Bold text* and _italic text_',
339
+ parse_mode: 'Markdown'
340
+ });
587
341
 
588
- function getMainKeyboard() {
589
- return new ReplyKeyboardMarkup({
590
- keyboard: [
342
+ // Send message with reply markup
343
+ await bot.sendMessage({
344
+ chat_id: chatId,
345
+ text: 'Choose an option:',
346
+ reply_markup: {
347
+ inline_keyboard: [
591
348
  [
592
- new KeyboardButton({ text: '📸 Фото' }),
593
- new KeyboardButton({ text: '📄 Документ' })
349
+ { text: 'Option 1', callback_data: 'opt1' },
350
+ { text: 'Option 2', callback_data: 'opt2' }
594
351
  ]
595
- ],
596
- resize_keyboard: true
597
- });
598
- }
599
-
600
- // Обработка сообщений
601
- if (text === '/start') {
602
- await bot.sendMessage({
603
- chat_id: chatId,
604
- text: 'Выберите действие:',
605
- reply_markup: getMainKeyboard()
606
- });
607
- } else if (text === '📸 Фото') {
608
- const fs = await import('fs');
609
- const photo = fs.createReadStream('photo.jpg');
610
- await bot.sendPhoto({
611
- chat_id: chatId,
612
- photo,
613
- caption: 'Ваше фото'
614
- });
615
- }
616
- ```
617
-
618
- ### Бот с callback-кнопками
619
-
620
- ```javascript
621
- import { InlineKeyboardMarkup, InlineKeyboardButton } from 'neogram';
622
-
623
- // Отправка inline-клавиатуры
624
- const keyboard = new InlineKeyboardMarkup({
625
- inline_keyboard: [
626
- [
627
- new InlineKeyboardButton({
628
- text: 'Кнопка 1',
629
- callback_data: 'btn1'
630
- }),
631
- new InlineKeyboardButton({
632
- text: 'Кнопка 2',
633
- callback_data: 'btn2'
634
- })
635
352
  ]
636
- ]
353
+ }
637
354
  });
638
355
 
639
- await bot.sendMessage({
356
+ // Edit message
357
+ await bot.editMessageText({
640
358
  chat_id: chatId,
641
- text: 'Выберите кнопку:',
642
- reply_markup: keyboard
359
+ message_id: messageId,
360
+ text: 'Updated message',
361
+ reply_markup: newMarkup
643
362
  });
644
363
 
645
- // Обработка callback
646
- if (update.callback_query) {
647
- const cb = update.callback_query;
648
-
649
- if (cb.data === 'btn1') {
650
- await bot.answerCallbackQuery({
651
- callback_query_id: cb.id,
652
- text: 'Нажата кнопка 1'
653
- });
654
-
655
- await bot.editMessageText({
656
- chat_id: cb.message.chat.id,
657
- message_id: cb.message.message_id,
658
- text: 'Вы нажали кнопку 1!'
659
- });
660
- }
661
- }
662
- ```
663
-
664
- ### Бот с AI интеграцией
665
-
666
- ```javascript
667
- import { Bot, OnlySQ, Deef } from 'neogram';
668
-
669
- const bot = new Bot(TOKEN);
670
- const onlysq = new OnlySQ();
671
- const deef = new Deef();
672
-
673
- // Генерация ответа через OnlySQ
674
- if (text.startsWith('/ask ')) {
675
- const question = text.substring(5);
676
- const answer = await onlysq.generateAnswer('gpt-5.2-chat', [
677
- { role: 'user', content: question }
678
- ]);
679
- await bot.sendMessage({
680
- chat_id: chatId,
681
- text: answer
682
- });
683
- }
684
-
685
- // Перевод текста
686
- if (text.startsWith('/translate ')) {
687
- const textToTranslate = text.substring(11);
688
- const translated = await deef.translate(textToTranslate, 'en');
689
- await bot.sendMessage({
690
- chat_id: chatId,
691
- text: `Перевод: ${translated}`
692
- });
693
- }
694
-
695
- // Генерация изображения
696
- if (text.startsWith('/image ')) {
697
- const prompt = text.substring(7);
698
- const success = await onlysq.generateImage('flux', prompt, '16:9', 'generated.png');
699
- if (success) {
700
- const fs = await import('fs');
701
- const image = fs.createReadStream('generated.png');
702
- await bot.sendPhoto({
703
- chat_id: chatId,
704
- photo: image,
705
- caption: `Изображение: ${prompt}`
706
- });
707
- }
708
- }
364
+ // Delete multiple messages
365
+ await bot.deleteMessages({
366
+ chat_id: chatId,
367
+ message_ids: [msgId1, msgId2, msgId3]
368
+ });
709
369
  ```
710
370
 
711
- ### Работа с файлами
371
+ #### Media Handling
712
372
 
713
373
  ```javascript
714
- // Отправка файла из памяти
715
- import { Readable } from 'stream';
716
-
717
- const buffer = Buffer.from('Hello, World!');
718
- const stream = Readable.from(buffer);
719
- stream.name = 'hello.txt';
374
+ // Send photo with caption
375
+ await bot.sendPhoto({
376
+ chat_id: chatId,
377
+ photo: 'https://example.com/photo.jpg',
378
+ caption: 'Beautiful scenery',
379
+ parse_mode: 'HTML'
380
+ });
720
381
 
382
+ // Send document from file
383
+ const fs = await import('fs');
384
+ const docStream = fs.createReadStream('./document.pdf');
721
385
  await bot.sendDocument({
722
386
  chat_id: chatId,
723
- document: stream,
724
- caption: 'Текстовый файл'
387
+ document: docStream,
388
+ filename: 'report.pdf',
389
+ caption: 'Monthly report'
725
390
  });
726
391
 
727
- // Скачивание файла
728
- const file = await bot.getFile({ file_id: fileId });
729
- const fileUrl = `https://api.telegram.org/file/bot${TOKEN}/${file.file_path}`;
730
- // Скачать файл по URL
731
- ```
732
-
733
- ### Работа с группами
734
-
735
- ```javascript
736
- // Получение информации о чате
737
- const chat = await bot.getChat({ chat_id: chatId });
738
- console.log(chat.title);
739
- console.log(chat.type_val); // 'group', 'supergroup', 'private'
740
-
741
- // Получение администраторов
742
- const admins = await bot.getChatAdministrators({ chat_id: chatId });
392
+ // Send audio with metadata
393
+ await bot.sendAudio({
394
+ chat_id: chatId,
395
+ audio: audioBuffer,
396
+ title: 'Song Title',
397
+ performer: 'Artist Name',
398
+ duration: 180
399
+ });
743
400
 
744
- // Создание пригласительной ссылки
745
- const inviteLink = await bot.createChatInviteLink({
401
+ // Send video with thumbnail
402
+ await bot.sendVideo({
746
403
  chat_id: chatId,
747
- name: 'Приглашение',
748
- expire_date: Math.floor(Date.now() / 1000) + 3600, // через час
749
- member_limit: 10
404
+ video: videoStream,
405
+ thumbnail: thumbnailBuffer,
406
+ caption: 'Tutorial video',
407
+ supports_streaming: true
750
408
  });
751
409
  ```
752
410
 
753
- ---
754
-
755
- ## 🎮 Расширенные возможности
756
-
757
- ### Игры и лидерборды
411
+ #### Chat Management
758
412
 
759
413
  ```javascript
760
- import { Game, Animation } from 'neogram';
414
+ // Get chat information
415
+ const chat = await bot.getChat({ chat_id: chatId });
416
+ console.log(`Chat: ${chat.title}, Members: ${chat.members_count}`);
761
417
 
762
- // Отправка игры
763
- const gameMessage = await bot.sendGame({
418
+ // Ban user
419
+ await bot.banChatMember({
764
420
  chat_id: chatId,
765
- game_short_name: 'my_game',
766
- reply_markup: gameKeyboard
767
- });
768
-
769
- // Установка счета в игре
770
- await bot.setGameScore({
771
421
  user_id: userId,
772
- score: 1000,
773
- chat_id: chatId,
774
- message_id: gameMessage.message_id,
775
- force: true // обновить даже если меньше
422
+ until_date: Date.now() / 1000 + 86400, // 24 hours
423
+ revoke_messages: true
776
424
  });
777
425
 
778
- // Получение лучших результатов
779
- const highScores = await bot.getGameHighScores({
780
- user_id: userId,
781
- chat_id: chatId
426
+ // Create invite link
427
+ const inviteLink = await bot.createChatInviteLink({
428
+ chat_id: chatId,
429
+ name: 'Temporary access',
430
+ expire_date: Date.now() / 1000 + 3600, // 1 hour
431
+ member_limit: 5
782
432
  });
783
433
 
784
- // Создание собственной игры
785
- const game = new Game({
786
- title: 'Моя игра',
787
- description: 'Описание игры',
788
- photo: [{ file_id: 'photo_id', width: 100, height: 100 }]
434
+ // Set chat permissions
435
+ await bot.setChatPermissions({
436
+ chat_id: chatId,
437
+ permissions: {
438
+ can_send_messages: true,
439
+ can_send_media_messages: false,
440
+ can_send_polls: false,
441
+ can_send_other_messages: false,
442
+ can_add_web_page_previews: false,
443
+ can_change_info: false,
444
+ can_invite_users: true,
445
+ can_pin_messages: false
446
+ }
789
447
  });
790
448
  ```
791
449
 
792
- ### Истории (Stories)
450
+ #### Inline Queries and Games
793
451
 
794
452
  ```javascript
795
- // Создание истории с текстом
796
- const story = await bot.sendStory({
797
- chat_id: chatId,
798
- content: {
799
- text: {
800
- text: 'Моя история!'
801
- }
802
- },
803
- caption: 'Описание истории'
804
- });
805
-
806
- // Создание истории с фото
807
- const photoStory = await bot.sendStory({
808
- chat_id: chatId,
809
- content: {
810
- photo: {
811
- media: 'photo_file_id',
812
- text: 'Текст на фото'
453
+ // Answer inline query
454
+ await bot.answerInlineQuery({
455
+ inline_query_id: queryId,
456
+ results: [
457
+ {
458
+ type: 'article',
459
+ id: '1',
460
+ title: 'Article Title',
461
+ input_message_content: {
462
+ message_text: 'Article content here'
463
+ }
813
464
  }
814
- }
465
+ ],
466
+ cache_time: 300
815
467
  });
816
468
 
817
- // Управление историями
818
- await bot.editStory({
469
+ // Send game
470
+ const gameMessage = await bot.sendGame({
819
471
  chat_id: chatId,
820
- story_id: storyId,
821
- content: { text: { text: 'Обновленный текст' } }
472
+ game_short_name: 'my_game'
822
473
  });
823
474
 
824
- await bot.deleteStory({
475
+ // Update game score
476
+ await bot.setGameScore({
477
+ user_id: userId,
478
+ score: 1500,
825
479
  chat_id: chatId,
826
- story_id: storyId
827
- });
828
-
829
- // Получение историй пользователя
830
- const userStories = await bot.getUserStories({
831
- user_id: userId
480
+ message_id: gameMessage.message_id,
481
+ force: true
832
482
  });
833
483
  ```
834
484
 
835
- ### Геолокация и геочаты
485
+ #### Stickers and Files
836
486
 
837
487
  ```javascript
838
- // Отправка геолокации
839
- await bot.sendLocation({
488
+ // Send sticker
489
+ await bot.sendSticker({
840
490
  chat_id: chatId,
841
- latitude: 55.7558,
842
- longitude: 37.6173,
843
- live_period: 86400 // живая геолокация на сутки
491
+ sticker: 'CAACAgIAAxkBAAE...sticker_file_id'
844
492
  });
845
493
 
846
- // Обновление живой геолокации
847
- await bot.editMessageLiveLocation({
848
- chat_id: chatId,
849
- message_id: messageId,
850
- latitude: newLat,
851
- longitude: newLng
852
- });
853
-
854
- // Остановка живой геолокации
855
- await bot.stopMessageLiveLocation({
856
- chat_id: chatId,
857
- message_id: messageId
858
- });
494
+ // Get file download link
495
+ const file = await bot.getFile({ file_id: 'file_id_here' });
496
+ const downloadUrl = `https://api.telegram.org/file/bot${bot.token}/${file.file_path}`;
859
497
 
860
- // Работа с геочатами
861
- const geoChat = await bot.getGeoChat({
862
- chat_id: geoChatId
863
- });
864
-
865
- // Установка геопозиции чата
866
- await bot.setChatLocation({
867
- chat_id: chatId,
868
- location: {
869
- latitude: 55.7558,
870
- longitude: 37.6173,
871
- address: 'Москва, Россия'
872
- }
498
+ // Upload sticker file
499
+ const stickerFile = await bot.uploadStickerFile({
500
+ user_id: userId,
501
+ sticker: stickerBuffer,
502
+ sticker_format: 'static'
873
503
  });
874
504
  ```
875
505
 
876
- ### Продвинутые реакции
506
+ #### Payments
877
507
 
878
508
  ```javascript
879
- import { ReactionTypeEmoji, ReactionTypeCustomEmoji } from 'neogram';
880
-
881
- // Установка реакции на сообщение
882
- await bot.setMessageReaction({
509
+ // Send invoice
510
+ await bot.sendInvoice({
883
511
  chat_id: chatId,
884
- message_id: messageId,
885
- reaction: [
886
- new ReactionTypeEmoji({ emoji: '👍' }),
887
- new ReactionTypeEmoji({ emoji: '❤️' })
888
- ],
889
- is_big: true
890
- });
891
-
892
- // Реакция с кастомным эмодзи
893
- await bot.setMessageReaction({
894
- chat_id: chatId,
895
- message_id: messageId,
896
- reaction: [
897
- new ReactionTypeCustomEmoji({ custom_emoji_id: 'emoji_id' })
512
+ title: 'Product Name',
513
+ description: 'Product description',
514
+ payload: 'order_123',
515
+ provider_token: 'PAYMENT_PROVIDER_TOKEN',
516
+ currency: 'USD',
517
+ prices: [
518
+ { label: 'Price', amount: 1000 } // $10.00
898
519
  ]
899
520
  });
900
521
 
901
- // Получение аналитики реакций
902
- const reactions = await bot.getMessageReactionCount({
903
- chat_id: chatId,
904
- message_id: messageId
905
- });
906
-
907
- const userReactions = await bot.getMessageUserReactionList({
908
- chat_id: chatId,
909
- message_id: messageId,
910
- reaction: new ReactionTypeEmoji({ emoji: '👍' })
522
+ // Answer pre-checkout query
523
+ await bot.answerPreCheckoutQuery({
524
+ pre_checkout_query_id: queryId,
525
+ ok: true,
526
+ error_message: null
911
527
  });
912
528
  ```
913
529
 
914
- ### Бизнес-функции
530
+ #### Business Features
915
531
 
916
532
  ```javascript
917
- // Отправка бизнес-сообщения
533
+ // Send business message
918
534
  await bot.sendBusinessMessage({
919
535
  business_connection_id: connectionId,
920
536
  chat_id: chatId,
921
- text: 'Бизнес-сообщение',
922
- business_connection: businessConnection
537
+ text: 'Business inquiry response',
538
+ reply_parameters: {
539
+ message_id: originalMessageId
540
+ }
923
541
  });
924
542
 
925
- // Получение бизнес-подключения
543
+ // Get business connection
926
544
  const connection = await bot.getBusinessConnection({
927
545
  business_connection_id: connectionId
928
546
  });
929
-
930
- // Управление бизнес-аккаунтом
931
- const businessAccount = await bot.getBusinessAccount();
932
-
933
- // Отправка бизнес-аккаунту
934
- await bot.sendMessageToBusinessAccount({
935
- business_connection_id: connectionId,
936
- chat_id: chatId,
937
- text: 'Сообщение в бизнес-аккаунт'
938
- });
939
547
  ```
940
548
 
941
- ### Веб-приложения
549
+ #### Stories
942
550
 
943
551
  ```javascript
944
- // Отправка веб-приложения
945
- await bot.sendWebApp({
552
+ // Send story with photo
553
+ await bot.sendStory({
946
554
  chat_id: chatId,
947
- web_app: {
948
- url: 'https://my-webapp.com'
555
+ content: {
556
+ photo: {
557
+ media: photoFileId,
558
+ text: 'Story caption'
559
+ }
949
560
  },
950
- text: 'Запустите веб-приложение'
561
+ caption: 'Story description'
951
562
  });
952
563
 
953
- // Ответ на веб-запрос
954
- await bot.answerWebAppQuery({
955
- web_app_query_id: queryId,
956
- result: inlineQueryResult
957
- });
958
-
959
- // Создание меню веб-приложения
960
- await bot.setChatMenuButton({
564
+ // Edit story
565
+ await bot.editStory({
961
566
  chat_id: chatId,
962
- menu_button: {
963
- type: 'web_app',
964
- text: 'Мое приложение',
965
- web_app: { url: 'https://my-app.com' }
567
+ story_id: storyId,
568
+ content: {
569
+ text: {
570
+ text: 'Updated story content'
571
+ }
966
572
  }
967
573
  });
968
574
  ```
969
575
 
970
- ### Статистика и аналитика
576
+ #### Forums
971
577
 
972
578
  ```javascript
973
- // Получение статистики чата
974
- const chatStats = await bot.getChatStats({
579
+ // Create forum topic
580
+ const topic = await bot.createForumTopic({
975
581
  chat_id: chatId,
976
- date: Math.floor(Date.now() / 1000) // Unix timestamp
582
+ name: 'General Discussion',
583
+ icon_color: 0x6FB9F0,
584
+ icon_custom_emoji_id: 'emoji_id'
977
585
  });
978
586
 
979
- // Получение статистики сообщений
980
- const messageStats = await bot.getMessageStats({
587
+ // Edit topic
588
+ await bot.editForumTopic({
981
589
  chat_id: chatId,
982
- date: Math.floor(Date.now() / 1000)
983
- });
984
-
985
- // Получение звездной статистики
986
- const starStats = await bot.getStarTransactions({
987
- offset: 0,
988
- limit: 100
590
+ message_thread_id: topic.message_thread_id,
591
+ name: 'Updated Topic Name'
989
592
  });
990
593
 
991
- // Перевод звезд
992
- await bot.sendStars({
993
- user_id: recipientId,
994
- amount: 100,
594
+ // Close topic
595
+ await bot.closeForumTopic({
995
596
  chat_id: chatId,
996
- business_connection_id: connectionId
597
+ message_thread_id: topic.message_thread_id
997
598
  });
998
599
  ```
999
600
 
1000
- ### Безопасность и валидация
601
+ #### Advanced Bot Features
1001
602
 
1002
603
  ```javascript
1003
- // Проверка безопасности контента
1004
- const safeContent = await bot.checkContentSafety({
1005
- content: 'Текст для проверки',
1006
- media: mediaFile
604
+ // Set bot commands
605
+ await bot.setMyCommands({
606
+ commands: [
607
+ { command: 'start', description: 'Start the bot' },
608
+ { command: 'help', description: 'Get help' },
609
+ { command: 'settings', description: 'Bot settings' }
610
+ ],
611
+ scope: { type: 'all_private_chats' },
612
+ language_code: 'en'
1007
613
  });
1008
614
 
1009
- // Валидация данных
1010
- const isValid = await bot.validateInput({
1011
- input: userInput,
1012
- type: 'email' // или 'phone', 'url', etc.
615
+ // Set webhook
616
+ await bot.setWebhook({
617
+ url: 'https://yourdomain.com/webhook',
618
+ secret_token: 'your_secret_token',
619
+ max_connections: 100,
620
+ allowed_updates: ['message', 'callback_query']
1013
621
  });
1014
622
 
1015
- // Защита от спама
1016
- await bot.enableSpamProtection({
623
+ // Send poll
624
+ await bot.sendPoll({
1017
625
  chat_id: chatId,
1018
- enabled: true,
1019
- strict_mode: true
1020
- });
1021
-
1022
- // Ограничение запросов
1023
- const rateLimited = await bot.checkRateLimit({
1024
- user_id: userId,
1025
- action: 'send_message',
1026
- limit: 100, // сообщений в час
1027
- window: 3600 // секунды
626
+ question: 'What is your favorite color?',
627
+ options: ['Red', 'Blue', 'Green', 'Yellow'],
628
+ is_anonymous: false,
629
+ allows_multiple_answers: true
1028
630
  });
1029
- ```
1030
-
1031
- ---
1032
-
1033
- ## 🔄 Отличия от Python-версии
1034
631
 
1035
- ### Асинхронность
1036
-
1037
- Все методы в JavaScript-версии **асинхронные** (используют `async/await`), в то время как в Python они синхронные.
1038
-
1039
- **Python:**
1040
- ```python
1041
- bot.send_message(chat_id=123, text="Hello")
1042
- ```
1043
-
1044
- **JavaScript:**
1045
- ```javascript
1046
- await bot.sendMessage({ chat_id: 123, text: "Hello" });
1047
- ```
1048
-
1049
- ### Именование методов
1050
-
1051
- Методы используют **camelCase** вместо snake_case:
1052
-
1053
- - `send_message` → `sendMessage`
1054
- - `get_updates` → `getUpdates`
1055
- - `answer_callback_query` → `answerCallbackQuery`
1056
-
1057
- ### Параметры методов
1058
-
1059
- Методы принимают **один объект** с параметрами вместо позиционных аргументов:
1060
-
1061
- **Python:**
1062
- ```python
1063
- bot.send_message(chat_id=123, text="Hello", parse_mode="HTML")
1064
- ```
1065
-
1066
- **JavaScript:**
1067
- ```javascript
1068
- await bot.sendMessage({
1069
- chat_id: 123,
1070
- text: "Hello",
1071
- parse_mode: "HTML"
1072
- });
1073
- ```
1074
-
1075
- ### Работа с файлами
1076
-
1077
- В JavaScript файлы передаются как:
1078
- - `Buffer` (Node.js)
1079
- - `Stream` (Readable stream)
1080
- - `string` (URL или file_id)
1081
-
1082
- **Пример:**
1083
- ```javascript
1084
- import fs from 'fs';
1085
-
1086
- // Из файла
1087
- const file = fs.createReadStream('file.pdf');
1088
- await bot.sendDocument({ chat_id: 123, document: file });
1089
-
1090
- // Из Buffer
1091
- const buffer = Buffer.from('content');
1092
- const stream = Readable.from(buffer);
1093
- stream.name = 'file.txt';
1094
- await bot.sendDocument({ chat_id: 123, document: stream });
1095
-
1096
- // По URL
1097
- await bot.sendPhoto({
1098
- chat_id: 123,
1099
- photo: 'https://example.com/image.jpg'
632
+ // Send location with live tracking
633
+ await bot.sendLocation({
634
+ chat_id: chatId,
635
+ latitude: 40.7128,
636
+ longitude: -74.0060,
637
+ live_period: 86400, // 24 hours
638
+ heading: 90,
639
+ proximity_alert_radius: 100
1100
640
  });
1101
641
  ```
1102
642
 
1103
- ### Импорты
1104
-
1105
- Используется ES6 модули (`import/export`):
1106
-
1107
- ```javascript
1108
- import { Bot, Update, Message } from 'neogram';
1109
- ```
1110
-
1111
- ---
1112
-
1113
- ## 📚 API Reference
1114
-
1115
- ### Bot
1116
-
1117
- Основной класс для работы с Telegram Bot API.
1118
-
1119
- #### Конструктор
1120
-
1121
- ```javascript
1122
- new Bot(token, options)
1123
- ```
1124
-
1125
- #### Методы
1126
-
1127
- Все методы возвращают `Promise` и должны использоваться с `await`.
1128
-
1129
- **Полный список методов:** см. раздел "Основной класс Bot" выше.
1130
-
1131
- ### TelegramObject
1132
-
1133
- Базовый класс для всех типов данных.
1134
-
1135
- #### Методы
1136
-
1137
- - `toJSON()` — сериализация объекта в JSON
1138
- - `static fromJSON(data)` — десериализация из JSON
1139
-
1140
- ### OnlySQ
1141
-
1142
- Класс для работы с OnlySQ API.
1143
-
1144
- #### Методы
1145
-
1146
- - `getModels(options)` — получить список моделей
1147
- - `generateAnswer(model, messages)` — генерация текста
1148
- - `generateImage(model, prompt, ratio, filename)` — генерация изображения
1149
-
1150
- ### Deef
1151
-
1152
- Класс утилит и альтернативных AI API.
1153
-
1154
- #### Методы
1155
-
1156
- - `translate(text, lang)` — перевод текста
1157
- - `shortUrl(longUrl)` — сокращение ссылок
1158
- - `genAiResponse(model, messages)` — генерация ответа
1159
- - `genGpt(messages)` — генерация через ItalyGPT
1160
- - `encodeBase64(path)` — кодирование в base64
1161
- - `runInBg(func, ...args)` — запуск в фоне
1162
-
1163
- ### ChatGPT
1164
-
1165
- Класс для работы с OpenAI-compatible API.
1166
-
1167
- #### Конструктор
1168
-
1169
- ```javascript
1170
- new ChatGPT(url, headers)
1171
- ```
1172
-
1173
- #### Методы
1174
-
1175
- - `generateChatCompletion(...)` — чат-комплишн
1176
- - `generateImage(...)` — генерация изображения
1177
- - `generateEmbedding(...)` — генерация эмбеддингов
1178
- - `generateTranscription(...)` — транскрипция аудио
1179
- - `generateTranslation(...)` — перевод аудио
1180
- - `getModels()` — список моделей
1181
-
1182
- ---
1183
-
1184
- ## 🐛 Обработка ошибок
643
+ #### Error Handling
1185
644
 
1186
645
  ```javascript
646
+ // Comprehensive error handling
1187
647
  try {
1188
- await bot.sendMessage({
1189
- chat_id: 123456789,
1190
- text: 'Сообщение'
648
+ const result = await bot.sendMessage({
649
+ chat_id: invalidChatId,
650
+ text: 'Test message'
1191
651
  });
1192
652
  } catch (error) {
1193
- if (error.error_code) {
1194
- // Ошибка Telegram API
1195
- console.error(`Telegram Error ${error.error_code}: ${error.description}`);
653
+ if (error.response) {
654
+ // Telegram API error
655
+ const { error_code, description } = error.response.data;
656
+ console.error(`Telegram API Error ${error_code}: ${description}`);
657
+
658
+ if (error_code === 403) {
659
+ console.log('Bot was blocked by user');
660
+ } else if (error_code === 400) {
661
+ console.log('Bad request - check parameters');
662
+ }
663
+ } else if (error.request) {
664
+ // Network error
665
+ console.error('Network error:', error.message);
1196
666
  } else {
1197
- // Другая ошибка
667
+ // Other error
1198
668
  console.error('Error:', error.message);
1199
669
  }
1200
670
  }
1201
- ```
1202
-
1203
- ---
1204
671
 
1205
- ## 📝 Лицензия
672
+ // Retry logic example
673
+ async function sendWithRetry(bot, options, maxRetries = 3) {
674
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
675
+ try {
676
+ return await bot.sendMessage(options);
677
+ } catch (error) {
678
+ if (attempt === maxRetries) throw error;
1206
679
 
1207
- Проект распространяется по лицензии **MIT**.
680
+ // Wait before retry (exponential backoff)
681
+ await new Promise(resolve =>
682
+ setTimeout(resolve, Math.pow(2, attempt) * 1000)
683
+ );
684
+ }
685
+ }
686
+ }
687
+ ```
1208
688
 
1209
- ---
689
+ ## Development
1210
690
 
1211
- ## 👤 Автор
691
+ ### Scripts
1212
692
 
1213
- **SiriLV**
1214
- Email: siriteamrs@gmail.com
693
+ - `npm run lint` - Lint code with ESLint
694
+ - `npm run lint:fix` - Auto-fix linting issues
695
+ - `npm run typecheck` - Run TypeScript type checking
696
+ - `npm run test` - Run tests with Vitest
697
+ - `npm run test:coverage` - Run tests with coverage
698
+ - `npm run ci` - Run full CI pipeline
1215
699
 
1216
- ---
700
+ ### Project Structure
1217
701
 
1218
- ## 🔗 Ссылки
702
+ ```
703
+ src/
704
+ ├── Bot.js # Main Bot API class
705
+ ├── TelegramObject.js # Base class for Telegram objects
706
+ ├── ai/ # AI integration classes
707
+ │ ├── ChatGPT.js
708
+ │ ├── OnlySQ.js
709
+ │ └── Deef.js
710
+ ├── types/ # Telegram API type definitions (281+ files)
711
+ └── index.js # Main export file
712
+ ```
1219
713
 
1220
- - [Telegram Bot API](https://core.telegram.org/bots/api)
1221
- - [Оригинальная Python-версия](https://github.com/SiriRSST/neogram)
714
+ ## Contributing
1222
715
 
1223
- ---
716
+ Contributions are welcome! Please see the [GitHub repository](https://github.com/AndrewImm-OP/neogram) for issues and pull requests.
1224
717
 
1225
- ## 📊 Статистика
718
+ ## License
1226
719
 
1227
- - **162 метода** Bot API
1228
- - ✅ **281 тип данных** Telegram API
1229
- - ✅ **3 AI класса** (OnlySQ, Deef, ChatGPT)
1230
- - ✅ **100% совместимость** с Python-версией по функционалу
1231
- - ✅ **44 тестовых файла** (1256 тестов)
1232
- - ✅ **65.29% покрытие кода** (Statements: 65.29%, Branches: 62.33%, Functions: 78.77%, Lines: 64.19%)
1233
- - ✅ **Enterprise-level тестирование** с полным CI/CD пайплайном
720
+ MIT License - see LICENSE file for details.
1234
721
 
1235
- ---
722
+ ## Credits
1236
723
 
1237
- **Версия:** 9.3
1238
- **Последнее обновление:** 2025
1239
- **Тестовое покрытие:** 65.29%
724
+ - Original Python library by [SiriLV](https://github.com/SiriLV)
725
+ - JavaScript port by [AndrewImm-OP](https://github.com/AndrewImm-OP)