neogram 9.3.0 → 9.3.2

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