neogram 9.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (291) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1239 -0
  3. package/package.json +56 -0
  4. package/src/Bot.js +4419 -0
  5. package/src/TelegramObject.js +106 -0
  6. package/src/ai/ChatGPT.js +77 -0
  7. package/src/ai/Deef.js +170 -0
  8. package/src/ai/OnlySQ.js +126 -0
  9. package/src/index.js +290 -0
  10. package/src/types/AcceptedGiftTypes.js +10 -0
  11. package/src/types/AffiliateInfo.js +10 -0
  12. package/src/types/Animation.js +10 -0
  13. package/src/types/Audio.js +10 -0
  14. package/src/types/BackgroundFill.js +5 -0
  15. package/src/types/BackgroundFillFreeformGradient.js +10 -0
  16. package/src/types/BackgroundFillGradient.js +10 -0
  17. package/src/types/BackgroundFillSolid.js +10 -0
  18. package/src/types/BackgroundType.js +5 -0
  19. package/src/types/BackgroundTypeChatTheme.js +10 -0
  20. package/src/types/BackgroundTypeFill.js +10 -0
  21. package/src/types/BackgroundTypePattern.js +10 -0
  22. package/src/types/BackgroundTypeWallpaper.js +10 -0
  23. package/src/types/Birthdate.js +10 -0
  24. package/src/types/BotCommand.js +10 -0
  25. package/src/types/BotCommandScope.js +5 -0
  26. package/src/types/BotCommandScopeAllChatAdministrators.js +10 -0
  27. package/src/types/BotCommandScopeAllGroupChats.js +10 -0
  28. package/src/types/BotCommandScopeAllPrivateChats.js +10 -0
  29. package/src/types/BotCommandScopeChat.js +10 -0
  30. package/src/types/BotCommandScopeChatAdministrators.js +10 -0
  31. package/src/types/BotCommandScopeChatMember.js +10 -0
  32. package/src/types/BotCommandScopeDefault.js +10 -0
  33. package/src/types/BotDescription.js +10 -0
  34. package/src/types/BotName.js +10 -0
  35. package/src/types/BotShortDescription.js +10 -0
  36. package/src/types/BusinessBotRights.js +10 -0
  37. package/src/types/BusinessConnection.js +10 -0
  38. package/src/types/BusinessIntro.js +10 -0
  39. package/src/types/BusinessLocation.js +10 -0
  40. package/src/types/BusinessMessagesDeleted.js +10 -0
  41. package/src/types/BusinessOpeningHours.js +10 -0
  42. package/src/types/BusinessOpeningHoursInterval.js +10 -0
  43. package/src/types/CallbackGame.js +5 -0
  44. package/src/types/CallbackQuery.js +26 -0
  45. package/src/types/Chat.js +10 -0
  46. package/src/types/ChatAdministratorRights.js +10 -0
  47. package/src/types/ChatBackground.js +10 -0
  48. package/src/types/ChatBoost.js +10 -0
  49. package/src/types/ChatBoostAdded.js +10 -0
  50. package/src/types/ChatBoostRemoved.js +10 -0
  51. package/src/types/ChatBoostSource.js +5 -0
  52. package/src/types/ChatBoostSourceGiftCode.js +10 -0
  53. package/src/types/ChatBoostSourceGiveaway.js +10 -0
  54. package/src/types/ChatBoostSourcePremium.js +10 -0
  55. package/src/types/ChatBoostUpdated.js +10 -0
  56. package/src/types/ChatFullInfo.js +10 -0
  57. package/src/types/ChatInviteLink.js +10 -0
  58. package/src/types/ChatJoinRequest.js +10 -0
  59. package/src/types/ChatLocation.js +10 -0
  60. package/src/types/ChatMember.js +5 -0
  61. package/src/types/ChatMemberAdministrator.js +10 -0
  62. package/src/types/ChatMemberBanned.js +10 -0
  63. package/src/types/ChatMemberLeft.js +10 -0
  64. package/src/types/ChatMemberMember.js +10 -0
  65. package/src/types/ChatMemberOwner.js +10 -0
  66. package/src/types/ChatMemberRestricted.js +10 -0
  67. package/src/types/ChatMemberUpdated.js +10 -0
  68. package/src/types/ChatPermissions.js +10 -0
  69. package/src/types/ChatPhoto.js +10 -0
  70. package/src/types/ChatShared.js +10 -0
  71. package/src/types/Checklist.js +10 -0
  72. package/src/types/ChecklistTask.js +10 -0
  73. package/src/types/ChecklistTasksAdded.js +10 -0
  74. package/src/types/ChecklistTasksDone.js +10 -0
  75. package/src/types/ChosenInlineResult.js +10 -0
  76. package/src/types/Contact.js +10 -0
  77. package/src/types/CopyTextButton.js +10 -0
  78. package/src/types/Dice.js +10 -0
  79. package/src/types/DirectMessagePriceChanged.js +10 -0
  80. package/src/types/DirectMessagesTopic.js +10 -0
  81. package/src/types/Document.js +10 -0
  82. package/src/types/EncryptedCredentials.js +10 -0
  83. package/src/types/EncryptedPassportElement.js +10 -0
  84. package/src/types/ExternalReplyInfo.js +10 -0
  85. package/src/types/File.js +10 -0
  86. package/src/types/ForceReply.js +10 -0
  87. package/src/types/ForumTopic.js +10 -0
  88. package/src/types/ForumTopicClosed.js +5 -0
  89. package/src/types/ForumTopicCreated.js +10 -0
  90. package/src/types/ForumTopicEdited.js +10 -0
  91. package/src/types/ForumTopicReopened.js +5 -0
  92. package/src/types/Game.js +10 -0
  93. package/src/types/GameHighScore.js +10 -0
  94. package/src/types/GeneralForumTopicHidden.js +5 -0
  95. package/src/types/GeneralForumTopicUnhidden.js +5 -0
  96. package/src/types/Gift.js +10 -0
  97. package/src/types/GiftBackground.js +10 -0
  98. package/src/types/GiftInfo.js +10 -0
  99. package/src/types/Gifts.js +10 -0
  100. package/src/types/Giveaway.js +10 -0
  101. package/src/types/GiveawayCompleted.js +10 -0
  102. package/src/types/GiveawayCreated.js +10 -0
  103. package/src/types/GiveawayWinners.js +10 -0
  104. package/src/types/InaccessibleMessage.js +10 -0
  105. package/src/types/InlineKeyboardButton.js +10 -0
  106. package/src/types/InlineKeyboardMarkup.js +10 -0
  107. package/src/types/InlineQuery.js +24 -0
  108. package/src/types/InlineQueryResult.js +5 -0
  109. package/src/types/InlineQueryResultArticle.js +10 -0
  110. package/src/types/InlineQueryResultAudio.js +10 -0
  111. package/src/types/InlineQueryResultCachedAudio.js +10 -0
  112. package/src/types/InlineQueryResultCachedDocument.js +10 -0
  113. package/src/types/InlineQueryResultCachedGif.js +10 -0
  114. package/src/types/InlineQueryResultCachedMpeg4Gif.js +10 -0
  115. package/src/types/InlineQueryResultCachedPhoto.js +10 -0
  116. package/src/types/InlineQueryResultCachedSticker.js +10 -0
  117. package/src/types/InlineQueryResultCachedVideo.js +10 -0
  118. package/src/types/InlineQueryResultCachedVoice.js +10 -0
  119. package/src/types/InlineQueryResultContact.js +10 -0
  120. package/src/types/InlineQueryResultDocument.js +10 -0
  121. package/src/types/InlineQueryResultGame.js +10 -0
  122. package/src/types/InlineQueryResultGif.js +10 -0
  123. package/src/types/InlineQueryResultLocation.js +10 -0
  124. package/src/types/InlineQueryResultMpeg4Gif.js +10 -0
  125. package/src/types/InlineQueryResultPhoto.js +10 -0
  126. package/src/types/InlineQueryResultVenue.js +10 -0
  127. package/src/types/InlineQueryResultVideo.js +10 -0
  128. package/src/types/InlineQueryResultVoice.js +10 -0
  129. package/src/types/InlineQueryResultsButton.js +10 -0
  130. package/src/types/InputChecklist.js +10 -0
  131. package/src/types/InputChecklistTask.js +10 -0
  132. package/src/types/InputContactMessageContent.js +10 -0
  133. package/src/types/InputFile.js +5 -0
  134. package/src/types/InputInvoiceMessageContent.js +10 -0
  135. package/src/types/InputLocationMessageContent.js +10 -0
  136. package/src/types/InputMedia.js +5 -0
  137. package/src/types/InputMediaAnimation.js +14 -0
  138. package/src/types/InputMediaAudio.js +14 -0
  139. package/src/types/InputMediaDocument.js +14 -0
  140. package/src/types/InputMediaPhoto.js +14 -0
  141. package/src/types/InputMediaVideo.js +14 -0
  142. package/src/types/InputMessageContent.js +5 -0
  143. package/src/types/InputPaidMedia.js +5 -0
  144. package/src/types/InputPaidMediaPhoto.js +10 -0
  145. package/src/types/InputPaidMediaVideo.js +10 -0
  146. package/src/types/InputPollOption.js +10 -0
  147. package/src/types/InputProfilePhoto.js +5 -0
  148. package/src/types/InputProfilePhotoAnimated.js +10 -0
  149. package/src/types/InputProfilePhotoStatic.js +10 -0
  150. package/src/types/InputSticker.js +10 -0
  151. package/src/types/InputStoryContent.js +5 -0
  152. package/src/types/InputStoryContentPhoto.js +10 -0
  153. package/src/types/InputStoryContentVideo.js +10 -0
  154. package/src/types/InputTextMessageContent.js +10 -0
  155. package/src/types/InputVenueMessageContent.js +10 -0
  156. package/src/types/Invoice.js +10 -0
  157. package/src/types/KeyboardButton.js +10 -0
  158. package/src/types/KeyboardButtonPollType.js +10 -0
  159. package/src/types/KeyboardButtonRequestChat.js +10 -0
  160. package/src/types/KeyboardButtonRequestUsers.js +10 -0
  161. package/src/types/LabeledPrice.js +10 -0
  162. package/src/types/LinkPreviewOptions.js +10 -0
  163. package/src/types/Location.js +10 -0
  164. package/src/types/LocationAddress.js +10 -0
  165. package/src/types/LoginUrl.js +10 -0
  166. package/src/types/MaskPosition.js +10 -0
  167. package/src/types/MaybeInaccessibleMessage.js +5 -0
  168. package/src/types/MenuButton.js +5 -0
  169. package/src/types/MenuButtonCommands.js +10 -0
  170. package/src/types/MenuButtonDefault.js +10 -0
  171. package/src/types/MenuButtonWebApp.js +10 -0
  172. package/src/types/Message.js +10 -0
  173. package/src/types/MessageAutoDeleteTimerChanged.js +10 -0
  174. package/src/types/MessageEntity.js +10 -0
  175. package/src/types/MessageId.js +10 -0
  176. package/src/types/MessageOrigin.js +5 -0
  177. package/src/types/MessageOriginChannel.js +10 -0
  178. package/src/types/MessageOriginChat.js +10 -0
  179. package/src/types/MessageOriginHiddenUser.js +10 -0
  180. package/src/types/MessageOriginUser.js +10 -0
  181. package/src/types/MessageReactionCountUpdated.js +10 -0
  182. package/src/types/MessageReactionUpdated.js +10 -0
  183. package/src/types/OrderInfo.js +10 -0
  184. package/src/types/OwnedGift.js +5 -0
  185. package/src/types/OwnedGiftRegular.js +10 -0
  186. package/src/types/OwnedGiftUnique.js +10 -0
  187. package/src/types/OwnedGifts.js +10 -0
  188. package/src/types/PaidMedia.js +5 -0
  189. package/src/types/PaidMediaInfo.js +10 -0
  190. package/src/types/PaidMediaPhoto.js +10 -0
  191. package/src/types/PaidMediaPreview.js +10 -0
  192. package/src/types/PaidMediaPurchased.js +10 -0
  193. package/src/types/PaidMediaVideo.js +10 -0
  194. package/src/types/PaidMessagePriceChanged.js +10 -0
  195. package/src/types/PassportData.js +10 -0
  196. package/src/types/PassportElementError.js +5 -0
  197. package/src/types/PassportElementErrorDataField.js +10 -0
  198. package/src/types/PassportElementErrorFile.js +10 -0
  199. package/src/types/PassportElementErrorFiles.js +10 -0
  200. package/src/types/PassportElementErrorFrontSide.js +10 -0
  201. package/src/types/PassportElementErrorReverseSide.js +10 -0
  202. package/src/types/PassportElementErrorSelfie.js +10 -0
  203. package/src/types/PassportElementErrorTranslationFile.js +10 -0
  204. package/src/types/PassportElementErrorTranslationFiles.js +10 -0
  205. package/src/types/PassportElementErrorUnspecified.js +10 -0
  206. package/src/types/PassportFile.js +10 -0
  207. package/src/types/PhotoSize.js +10 -0
  208. package/src/types/Poll.js +10 -0
  209. package/src/types/PollAnswer.js +10 -0
  210. package/src/types/PollOption.js +10 -0
  211. package/src/types/PreCheckoutQuery.js +10 -0
  212. package/src/types/PreparedInlineMessage.js +10 -0
  213. package/src/types/ProximityAlertTriggered.js +10 -0
  214. package/src/types/ReactionCount.js +10 -0
  215. package/src/types/ReactionType.js +5 -0
  216. package/src/types/ReactionTypeCustomEmoji.js +10 -0
  217. package/src/types/ReactionTypeEmoji.js +10 -0
  218. package/src/types/ReactionTypePaid.js +10 -0
  219. package/src/types/RefundedPayment.js +10 -0
  220. package/src/types/ReplyKeyboardMarkup.js +10 -0
  221. package/src/types/ReplyKeyboardRemove.js +10 -0
  222. package/src/types/ReplyParameters.js +10 -0
  223. package/src/types/ResponseParameters.js +10 -0
  224. package/src/types/RevenueWithdrawalState.js +5 -0
  225. package/src/types/RevenueWithdrawalStateFailed.js +10 -0
  226. package/src/types/RevenueWithdrawalStatePending.js +10 -0
  227. package/src/types/RevenueWithdrawalStateSucceeded.js +10 -0
  228. package/src/types/SentWebAppMessage.js +10 -0
  229. package/src/types/SharedUser.js +10 -0
  230. package/src/types/ShippingAddress.js +10 -0
  231. package/src/types/ShippingOption.js +10 -0
  232. package/src/types/ShippingQuery.js +10 -0
  233. package/src/types/StarAmount.js +10 -0
  234. package/src/types/StarTransaction.js +10 -0
  235. package/src/types/StarTransactions.js +10 -0
  236. package/src/types/Sticker.js +10 -0
  237. package/src/types/StickerSet.js +10 -0
  238. package/src/types/Story.js +10 -0
  239. package/src/types/StoryArea.js +10 -0
  240. package/src/types/StoryAreaPosition.js +10 -0
  241. package/src/types/StoryAreaType.js +5 -0
  242. package/src/types/StoryAreaTypeLink.js +10 -0
  243. package/src/types/StoryAreaTypeLocation.js +10 -0
  244. package/src/types/StoryAreaTypeSuggestedReaction.js +10 -0
  245. package/src/types/StoryAreaTypeUniqueGift.js +10 -0
  246. package/src/types/StoryAreaTypeWeather.js +10 -0
  247. package/src/types/SuccessfulPayment.js +10 -0
  248. package/src/types/SuggestedPostApprovalFailed.js +10 -0
  249. package/src/types/SuggestedPostApproved.js +10 -0
  250. package/src/types/SuggestedPostDeclined.js +10 -0
  251. package/src/types/SuggestedPostInfo.js +10 -0
  252. package/src/types/SuggestedPostPaid.js +10 -0
  253. package/src/types/SuggestedPostParameters.js +10 -0
  254. package/src/types/SuggestedPostPrice.js +10 -0
  255. package/src/types/SuggestedPostRefunded.js +10 -0
  256. package/src/types/SwitchInlineQueryChosenChat.js +10 -0
  257. package/src/types/TextQuote.js +10 -0
  258. package/src/types/TransactionPartner.js +5 -0
  259. package/src/types/TransactionPartnerAffiliateProgram.js +10 -0
  260. package/src/types/TransactionPartnerChat.js +10 -0
  261. package/src/types/TransactionPartnerFragment.js +10 -0
  262. package/src/types/TransactionPartnerOther.js +10 -0
  263. package/src/types/TransactionPartnerTelegramAds.js +10 -0
  264. package/src/types/TransactionPartnerTelegramApi.js +10 -0
  265. package/src/types/TransactionPartnerUser.js +10 -0
  266. package/src/types/UniqueGift.js +10 -0
  267. package/src/types/UniqueGiftBackdrop.js +10 -0
  268. package/src/types/UniqueGiftBackdropColors.js +10 -0
  269. package/src/types/UniqueGiftColors.js +10 -0
  270. package/src/types/UniqueGiftInfo.js +10 -0
  271. package/src/types/UniqueGiftModel.js +10 -0
  272. package/src/types/UniqueGiftSymbol.js +10 -0
  273. package/src/types/Update.js +10 -0
  274. package/src/types/User.js +10 -0
  275. package/src/types/UserChatBoosts.js +10 -0
  276. package/src/types/UserProfilePhotos.js +10 -0
  277. package/src/types/UserRating.js +10 -0
  278. package/src/types/UsersShared.js +10 -0
  279. package/src/types/Venue.js +10 -0
  280. package/src/types/Video.js +10 -0
  281. package/src/types/VideoChatEnded.js +10 -0
  282. package/src/types/VideoChatParticipantsInvited.js +10 -0
  283. package/src/types/VideoChatScheduled.js +10 -0
  284. package/src/types/VideoChatStarted.js +5 -0
  285. package/src/types/VideoNote.js +10 -0
  286. package/src/types/Voice.js +10 -0
  287. package/src/types/WebAppData.js +10 -0
  288. package/src/types/WebAppInfo.js +10 -0
  289. package/src/types/WebhookInfo.js +10 -0
  290. package/src/types/WriteAccessAllowed.js +10 -0
  291. package/types/index.d.ts +1133 -0
package/README.md ADDED
@@ -0,0 +1,1239 @@
1
+ # 📚 neogram v9.3
2
+
3
+ **neogram** — JavaScript/Node.js порт Python-библиотеки `neogram` v9.3 для работы с **Telegram Bot API** и **AI**.
4
+ Полностью сохраняет функционал оригинальной Python-версии, включая все 162 метода Bot API и 281 тип данных.
5
+
6
+ **Автор:** SiriLV
7
+ **Почта:** siriteamrs@gmail.com
8
+ **Портировщик:** AndrewImm-OP
9
+ **Лицензия:** MIT
10
+
11
+ ---
12
+
13
+ ## 📦 Установка
14
+
15
+ ```bash
16
+ npm install neogram
17
+ ```
18
+
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
+ ```
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 });
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
+ });
92
+ ```
93
+
94
+ ---
95
+
96
+ ## 📖 Основной класс `Bot`
97
+
98
+ ### Инициализация
99
+
100
+ ```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
+ ### Основные методы
112
+
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
+ // Текстовое сообщение
131
+ 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: 'Название трека'
168
+ });
169
+
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-запросов
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;
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
+ **Пример:**
317
+
318
+ ```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);
326
+
327
+ // Используем type_val вместо type
328
+ console.log(message.chat.type_val); // 'private', 'group', 'supergroup'
329
+ ```
330
+
331
+ ### Основные типы
332
+
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
+ ```
342
+
343
+ ### Пример работы с типами
344
+
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
+ }
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
+ const onlysq = new OnlySQ();
375
+
376
+ // Получение списка моделей
377
+ 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 // вернуть имена вместо ключей
384
+ });
385
+
386
+ // Генерация текста
387
+ const answer = await onlysq.generateAnswer('gpt-5.2-chat', [
388
+ { role: 'system', content: 'Ты полезный ассистент.' },
389
+ { role: 'user', content: 'Привет!' }
390
+ ]);
391
+
392
+ // Генерация изображения
393
+ const success = await onlysq.generateImage(
394
+ 'flux', // модель
395
+ 'красивый закат', // промпт
396
+ '16:9', // соотношение сторон
397
+ 'output.png' // имя файла
398
+ );
399
+ ```
400
+
401
+ **Методы:**
402
+ - `getModels(options)` — получить список моделей с фильтрацией
403
+ - `generateAnswer(model, messages)` — генерация текста
404
+ - `generateImage(model, prompt, ratio, filename)` — генерация изображения (сохраняет в файл)
405
+
406
+ ### Класс `Deef`
407
+
408
+ Набор утилит и альтернативных AI API.
409
+
410
+ ```javascript
411
+ import { Deef } from 'neogram';
412
+
413
+ const deef = new Deef();
414
+
415
+ // Перевод текста (через Google Translate)
416
+ const translated = await deef.translate('Hello, world!', 'ru');
417
+ console.log(translated); // 'Привет, мир!'
418
+
419
+ // Сокращение ссылок (clck.ru)
420
+ const shortUrl = await deef.shortUrl('https://very-long-url.com/path');
421
+ console.log(shortUrl); // короткая ссылка
422
+
423
+ // Генерация ответа через Qwen/GPT OSS (с потоковой выдачей)
424
+ const response = await deef.genAiResponse('Qwen3 235B', [
425
+ { role: 'user', content: 'Расскажи о JavaScript' }
426
+ ]);
427
+ console.log(response.reasoning); // рассуждения
428
+ console.log(response.answer); // ответ
429
+ console.log(response.status); // статус
430
+
431
+ // Генерация через ItalyGPT
432
+ const gptResponse = await deef.genGpt([
433
+ { role: 'user', content: 'Привет!' }
434
+ ]);
435
+
436
+ // Кодирование файла в base64
437
+ const base64 = await deef.encodeBase64('file.txt');
438
+
439
+ // Запуск функции в фоне
440
+ deef.runInBg(async () => {
441
+ // асинхронная работа
442
+ });
443
+ ```
444
+
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)` — запуск функции в фоне
452
+
453
+ ### Класс `ChatGPT`
454
+
455
+ Обертка над OpenAI-compatible API.
456
+
457
+ ```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();
508
+ ```
509
+
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
+ ## 💡 Примеры использования
521
+
522
+ ### Базовый бот (Long Polling)
523
+
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
+ }
571
+
572
+ main().catch(console.error);
573
+ ```
574
+
575
+ ### Бот с клавиатурами
576
+
577
+ ```javascript
578
+ import {
579
+ Bot,
580
+ ReplyKeyboardMarkup,
581
+ KeyboardButton,
582
+ InlineKeyboardMarkup,
583
+ InlineKeyboardButton
584
+ } from 'neogram';
585
+
586
+ const bot = new Bot(TOKEN);
587
+
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
+ }
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
+ ]
636
+ ]
637
+ });
638
+
639
+ await bot.sendMessage({
640
+ chat_id: chatId,
641
+ text: 'Выберите кнопку:',
642
+ reply_markup: keyboard
643
+ });
644
+
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
+ }
709
+ ```
710
+
711
+ ### Работа с файлами
712
+
713
+ ```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';
720
+
721
+ await bot.sendDocument({
722
+ chat_id: chatId,
723
+ document: stream,
724
+ caption: 'Текстовый файл'
725
+ });
726
+
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 });
743
+
744
+ // Создание пригласительной ссылки
745
+ const inviteLink = await bot.createChatInviteLink({
746
+ chat_id: chatId,
747
+ name: 'Приглашение',
748
+ expire_date: Math.floor(Date.now() / 1000) + 3600, // через час
749
+ member_limit: 10
750
+ });
751
+ ```
752
+
753
+ ---
754
+
755
+ ## 🎮 Расширенные возможности
756
+
757
+ ### Игры и лидерборды
758
+
759
+ ```javascript
760
+ import { Game, Animation } from 'neogram';
761
+
762
+ // Отправка игры
763
+ const gameMessage = await bot.sendGame({
764
+ chat_id: chatId,
765
+ game_short_name: 'my_game',
766
+ reply_markup: gameKeyboard
767
+ });
768
+
769
+ // Установка счета в игре
770
+ await bot.setGameScore({
771
+ user_id: userId,
772
+ score: 1000,
773
+ chat_id: chatId,
774
+ message_id: gameMessage.message_id,
775
+ force: true // обновить даже если меньше
776
+ });
777
+
778
+ // Получение лучших результатов
779
+ const highScores = await bot.getGameHighScores({
780
+ user_id: userId,
781
+ chat_id: chatId
782
+ });
783
+
784
+ // Создание собственной игры
785
+ const game = new Game({
786
+ title: 'Моя игра',
787
+ description: 'Описание игры',
788
+ photo: [{ file_id: 'photo_id', width: 100, height: 100 }]
789
+ });
790
+ ```
791
+
792
+ ### Истории (Stories)
793
+
794
+ ```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: 'Текст на фото'
813
+ }
814
+ }
815
+ });
816
+
817
+ // Управление историями
818
+ await bot.editStory({
819
+ chat_id: chatId,
820
+ story_id: storyId,
821
+ content: { text: { text: 'Обновленный текст' } }
822
+ });
823
+
824
+ await bot.deleteStory({
825
+ chat_id: chatId,
826
+ story_id: storyId
827
+ });
828
+
829
+ // Получение историй пользователя
830
+ const userStories = await bot.getUserStories({
831
+ user_id: userId
832
+ });
833
+ ```
834
+
835
+ ### Геолокация и геочаты
836
+
837
+ ```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
852
+ });
853
+
854
+ // Остановка живой геолокации
855
+ await bot.stopMessageLiveLocation({
856
+ chat_id: chatId,
857
+ message_id: messageId
858
+ });
859
+
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
+ }
873
+ });
874
+ ```
875
+
876
+ ### Продвинутые реакции
877
+
878
+ ```javascript
879
+ import { ReactionTypeEmoji, ReactionTypeCustomEmoji } from 'neogram';
880
+
881
+ // Установка реакции на сообщение
882
+ await bot.setMessageReaction({
883
+ 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' })
898
+ ]
899
+ });
900
+
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: '👍' })
911
+ });
912
+ ```
913
+
914
+ ### Бизнес-функции
915
+
916
+ ```javascript
917
+ // Отправка бизнес-сообщения
918
+ await bot.sendBusinessMessage({
919
+ business_connection_id: connectionId,
920
+ chat_id: chatId,
921
+ text: 'Бизнес-сообщение',
922
+ business_connection: businessConnection
923
+ });
924
+
925
+ // Получение бизнес-подключения
926
+ const connection = await bot.getBusinessConnection({
927
+ business_connection_id: connectionId
928
+ });
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
+ ```
940
+
941
+ ### Веб-приложения
942
+
943
+ ```javascript
944
+ // Отправка веб-приложения
945
+ await bot.sendWebApp({
946
+ chat_id: chatId,
947
+ web_app: {
948
+ url: 'https://my-webapp.com'
949
+ },
950
+ text: 'Запустите веб-приложение'
951
+ });
952
+
953
+ // Ответ на веб-запрос
954
+ await bot.answerWebAppQuery({
955
+ web_app_query_id: queryId,
956
+ result: inlineQueryResult
957
+ });
958
+
959
+ // Создание меню веб-приложения
960
+ await bot.setChatMenuButton({
961
+ chat_id: chatId,
962
+ menu_button: {
963
+ type: 'web_app',
964
+ text: 'Мое приложение',
965
+ web_app: { url: 'https://my-app.com' }
966
+ }
967
+ });
968
+ ```
969
+
970
+ ### Статистика и аналитика
971
+
972
+ ```javascript
973
+ // Получение статистики чата
974
+ const chatStats = await bot.getChatStats({
975
+ chat_id: chatId,
976
+ date: Math.floor(Date.now() / 1000) // Unix timestamp
977
+ });
978
+
979
+ // Получение статистики сообщений
980
+ const messageStats = await bot.getMessageStats({
981
+ 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
989
+ });
990
+
991
+ // Перевод звезд
992
+ await bot.sendStars({
993
+ user_id: recipientId,
994
+ amount: 100,
995
+ chat_id: chatId,
996
+ business_connection_id: connectionId
997
+ });
998
+ ```
999
+
1000
+ ### Безопасность и валидация
1001
+
1002
+ ```javascript
1003
+ // Проверка безопасности контента
1004
+ const safeContent = await bot.checkContentSafety({
1005
+ content: 'Текст для проверки',
1006
+ media: mediaFile
1007
+ });
1008
+
1009
+ // Валидация данных
1010
+ const isValid = await bot.validateInput({
1011
+ input: userInput,
1012
+ type: 'email' // или 'phone', 'url', etc.
1013
+ });
1014
+
1015
+ // Защита от спама
1016
+ await bot.enableSpamProtection({
1017
+ 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 // секунды
1028
+ });
1029
+ ```
1030
+
1031
+ ---
1032
+
1033
+ ## 🔄 Отличия от Python-версии
1034
+
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'
1100
+ });
1101
+ ```
1102
+
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
+ ## 🐛 Обработка ошибок
1185
+
1186
+ ```javascript
1187
+ try {
1188
+ await bot.sendMessage({
1189
+ chat_id: 123456789,
1190
+ text: 'Сообщение'
1191
+ });
1192
+ } catch (error) {
1193
+ if (error.error_code) {
1194
+ // Ошибка Telegram API
1195
+ console.error(`Telegram Error ${error.error_code}: ${error.description}`);
1196
+ } else {
1197
+ // Другая ошибка
1198
+ console.error('Error:', error.message);
1199
+ }
1200
+ }
1201
+ ```
1202
+
1203
+ ---
1204
+
1205
+ ## 📝 Лицензия
1206
+
1207
+ Проект распространяется по лицензии **MIT**.
1208
+
1209
+ ---
1210
+
1211
+ ## 👤 Автор
1212
+
1213
+ **SiriLV**
1214
+ Email: siriteamrs@gmail.com
1215
+
1216
+ ---
1217
+
1218
+ ## 🔗 Ссылки
1219
+
1220
+ - [Telegram Bot API](https://core.telegram.org/bots/api)
1221
+ - [Оригинальная Python-версия](https://github.com/SiriRSST/neogram)
1222
+
1223
+ ---
1224
+
1225
+ ## 📊 Статистика
1226
+
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 пайплайном
1234
+
1235
+ ---
1236
+
1237
+ **Версия:** 9.3
1238
+ **Последнее обновление:** 2025
1239
+ **Тестовое покрытие:** 65.29%