Node.js wrapper for the official Telegram Bot API with polling and webhook support, comprehensive message handling, media operations, and bot management features.
npx @tessl/cli install tessl/npm-node-telegram-bot-api@0.66.00
# Node.js Telegram Bot API
1
2
Node.js Telegram Bot API is a comprehensive wrapper for the official Telegram Bot API that enables developers to create sophisticated Telegram bots with JavaScript. It offers both polling and webhook mechanisms for receiving updates, supports regex-based message handlers for command processing, and provides full coverage of Telegram Bot API methods including media handling, inline keyboards, payments, games, and business features.
3
4
## Package Information
5
6
- **Package Name**: node-telegram-bot-api
7
- **Package Type**: npm
8
- **Language**: JavaScript (ES6, transpiled with Babel)
9
- **Installation**: `npm install node-telegram-bot-api`
10
11
## Core Imports
12
13
```javascript
14
const TelegramBot = require('node-telegram-bot-api');
15
```
16
17
For ES modules:
18
19
```javascript
20
import TelegramBot from 'node-telegram-bot-api';
21
```
22
23
## Basic Usage
24
25
```javascript
26
const TelegramBot = require('node-telegram-bot-api');
27
28
// Create a bot that uses 'polling' to fetch new updates
29
const bot = new TelegramBot('YOUR_BOT_TOKEN', { polling: true });
30
31
// Listen for any kind of message
32
bot.on('message', (msg) => {
33
const chatId = msg.chat.id;
34
bot.sendMessage(chatId, 'Received your message');
35
});
36
37
// Matches "/echo [whatever]"
38
bot.onText(/\/echo (.+)/, (msg, match) => {
39
const chatId = msg.chat.id;
40
const resp = match[1]; // the captured "whatever"
41
bot.sendMessage(chatId, resp);
42
});
43
44
// Handle callback queries from inline keyboards
45
bot.on('callback_query', (callbackQuery) => {
46
const message = callbackQuery.message;
47
const data = callbackQuery.data;
48
49
bot.answerCallbackQuery(callbackQuery.id, {
50
text: `You clicked: ${data}`
51
});
52
});
53
```
54
55
## Architecture
56
57
Node.js Telegram Bot API is built around several key components:
58
59
- **TelegramBot Class**: Main class extending EventEmitter for bot functionality
60
- **Connection Management**: Polling and webhook support for receiving updates
61
- **Event System**: EventEmitter-based architecture with custom message type events
62
- **File Handling**: Built-in support for file uploads, downloads, and streaming
63
- **Error Management**: Comprehensive error classes for different failure scenarios
64
- **Request System**: Automatic retrying and extensive configuration options
65
66
## Capabilities
67
68
### Bot Configuration and Connection
69
70
Core bot setup, connection management, and configuration options. Essential for initializing bots and managing polling or webhook connections.
71
72
```javascript { .api }
73
class TelegramBot extends EventEmitter {
74
constructor(token, options);
75
76
// Connection management
77
startPolling(options): Promise<void>;
78
stopPolling(options): Promise<void>;
79
isPolling(): boolean;
80
openWebHook(): Promise<void>;
81
closeWebHook(): Promise<void>;
82
hasOpenWebHook(): boolean;
83
}
84
85
// Static properties
86
TelegramBot.errors: Object;
87
TelegramBot.messageTypes: string[];
88
```
89
90
[Bot Configuration and Connection](./bot-setup.md)
91
92
### Message Handling and Events
93
94
Event-driven message processing with support for text pattern matching, reply handling, and custom event listeners for different message types.
95
96
```javascript { .api }
97
// Event handling
98
on(event, listener): void;
99
onText(regexp, callback): void;
100
removeTextListener(regexp): Object;
101
clearTextListeners(): void;
102
onReplyToMessage(chatId, messageId, callback): number;
103
removeReplyListener(replyListenerId): Object;
104
clearReplyListeners(): void;
105
106
// Update processing
107
processUpdate(update): void;
108
getUpdates(options): Promise<Update[]>;
109
```
110
111
[Message Handling and Events](./message-handling.md)
112
113
### Messaging and Communication
114
115
Core messaging functionality for sending text messages, handling replies, forwarding, and copying messages between chats.
116
117
```javascript { .api }
118
// Basic messaging
119
sendMessage(chatId, text, options): Promise<Message>;
120
forwardMessage(chatId, fromChatId, messageId, options): Promise<Message>;
121
forwardMessages(chatId, fromChatId, messageIds, options): Promise<MessageId[]>;
122
copyMessage(chatId, fromChatId, messageId, options): Promise<MessageId>;
123
copyMessages(chatId, fromChatId, messageIds, options): Promise<MessageId[]>;
124
125
// Message editing and deletion
126
editMessageText(text, options): Promise<Message|boolean>;
127
editMessageCaption(caption, options): Promise<Message|boolean>;
128
editMessageReplyMarkup(replyMarkup, options): Promise<Message|boolean>;
129
deleteMessage(chatId, messageId, options): Promise<boolean>;
130
deleteMessages(chatId, messageIds, options): Promise<boolean>;
131
```
132
133
[Messaging and Communication](./messaging.md)
134
135
### Media and File Operations
136
137
Comprehensive media handling including photos, videos, audio, documents, stickers, and voice messages with upload, download, and streaming capabilities.
138
139
```javascript { .api }
140
// Media sending
141
sendPhoto(chatId, photo, options, fileOptions): Promise<Message>;
142
sendAudio(chatId, audio, options, fileOptions): Promise<Message>;
143
sendDocument(chatId, doc, options, fileOptions): Promise<Message>;
144
sendVideo(chatId, video, options, fileOptions): Promise<Message>;
145
sendAnimation(chatId, animation, options, fileOptions): Promise<Message>;
146
sendVoice(chatId, voice, options, fileOptions): Promise<Message>;
147
sendVideoNote(chatId, videoNote, options, fileOptions): Promise<Message>;
148
sendMediaGroup(chatId, media, options): Promise<Message[]>;
149
sendSticker(chatId, sticker, options, fileOptions): Promise<Message>;
150
151
// File operations
152
getFile(fileId, options): Promise<File>;
153
getFileLink(fileId, options): Promise<string>;
154
getFileStream(fileId, options): stream.Readable;
155
downloadFile(fileId, downloadDir, options): Promise<string>;
156
```
157
158
[Media and File Operations](./media-files.md)
159
160
### Chat and User Management
161
162
Complete chat administration including member management, permissions, roles, and chat settings with support for groups, supergroups, and channels.
163
164
```javascript { .api }
165
// Chat information
166
getChat(chatId, options): Promise<Chat>;
167
getChatAdministrators(chatId, options): Promise<ChatMember[]>;
168
getChatMemberCount(chatId, options): Promise<number>;
169
getChatMember(chatId, userId, options): Promise<ChatMember>;
170
171
// Member management
172
banChatMember(chatId, userId, options): Promise<boolean>;
173
unbanChatMember(chatId, userId, options): Promise<boolean>;
174
restrictChatMember(chatId, userId, options): Promise<boolean>;
175
promoteChatMember(chatId, userId, options): Promise<boolean>;
176
setChatAdministratorCustomTitle(chatId, userId, customTitle, options): Promise<boolean>;
177
178
// Chat settings
179
setChatTitle(chatId, title, options): Promise<boolean>;
180
setChatDescription(chatId, description, options): Promise<boolean>;
181
setChatPhoto(chatId, photo, options, fileOptions): Promise<boolean>;
182
deleteChatPhoto(chatId, options): Promise<boolean>;
183
```
184
185
[Chat and User Management](./chat-management.md)
186
187
### Interactive Features
188
189
Interactive elements including polls, dice games, location sharing, contact sharing, and chat actions for enhanced user engagement.
190
191
```javascript { .api }
192
// Interactive elements
193
sendPoll(chatId, question, pollOptions, options): Promise<Message>;
194
stopPoll(chatId, pollId, options): Promise<Poll>;
195
sendDice(chatId, options): Promise<Message>;
196
sendLocation(chatId, latitude, longitude, options): Promise<Message>;
197
sendVenue(chatId, latitude, longitude, title, address, options): Promise<Message>;
198
sendContact(chatId, phoneNumber, firstName, options): Promise<Message>;
199
sendChatAction(chatId, action, options): Promise<boolean>;
200
setMessageReaction(chatId, messageId, options): Promise<boolean>;
201
202
// Location updates
203
editMessageLiveLocation(latitude, longitude, options): Promise<Message|boolean>;
204
stopMessageLiveLocation(options): Promise<Message|boolean>;
205
```
206
207
[Interactive Features](./interactive-features.md)
208
209
### Advanced Features
210
211
Advanced Telegram features including inline queries, payments, games, sticker management, forum topics, and business features for sophisticated bot implementations.
212
213
```javascript { .api }
214
// Inline queries
215
answerInlineQuery(inlineQueryId, results, options): Promise<boolean>;
216
answerWebAppQuery(webAppQueryId, result, options): Promise<SentWebAppMessage>;
217
218
// Payments
219
sendInvoice(chatId, title, description, payload, providerToken, currency, prices, options): Promise<Message>;
220
createInvoiceLink(title, description, payload, providerToken, currency, prices, options): Promise<string>;
221
answerShippingQuery(shippingQueryId, ok, options): Promise<boolean>;
222
answerPreCheckoutQuery(preCheckoutQueryId, ok, options): Promise<boolean>;
223
224
// Games
225
sendGame(chatId, gameShortName, options): Promise<Message>;
226
setGameScore(userId, score, options): Promise<Message|boolean>;
227
getGameHighScores(userId, options): Promise<GameHighScore[]>;
228
229
// Business features
230
getUserChatBoosts(chatId, userId, options): Promise<UserChatBoosts>;
231
getBusinessConnection(businessConnectionId, options): Promise<BusinessConnection>;
232
```
233
234
[Advanced Features](./advanced-features.md)
235
236
### Bot Information and Settings
237
238
Bot configuration and information management including commands, descriptions, menu buttons, and administrator rights.
239
240
```javascript { .api }
241
// Bot information
242
getMe(options): Promise<User>;
243
logOut(options): Promise<boolean>;
244
close(options): Promise<boolean>;
245
246
// Bot settings
247
setMyCommands(commands, options): Promise<boolean>;
248
deleteMyCommands(options): Promise<boolean>;
249
getMyCommands(options): Promise<BotCommand[]>;
250
setMyName(options): Promise<boolean>;
251
getMyName(options): Promise<BotName>;
252
setMyDescription(options): Promise<boolean>;
253
getMyDescription(options): Promise<BotDescription>;
254
setMyShortDescription(options): Promise<boolean>;
255
getMyShortDescription(options): Promise<BotShortDescription>;
256
setChatMenuButton(options): Promise<boolean>;
257
getChatMenuButton(options): Promise<MenuButton>;
258
setMyDefaultAdministratorRights(options): Promise<boolean>;
259
getMyDefaultAdministratorRights(options): Promise<ChatAdministratorRights>;
260
```
261
262
[Bot Information and Settings](./bot-settings.md)
263
264
## Types
265
266
```javascript { .api }
267
// Error classes
268
class BaseError extends Error {
269
constructor(code, message);
270
code: string;
271
toJSON(): { code: string, message: string };
272
}
273
274
class FatalError extends BaseError {
275
constructor(data);
276
}
277
278
class ParseError extends BaseError {
279
constructor(message, response);
280
response: http.IncomingMessage;
281
}
282
283
class TelegramError extends BaseError {
284
constructor(message, response);
285
response: http.IncomingMessage;
286
}
287
288
// Constructor options
289
interface TelegramBotOptions {
290
polling?: boolean | {
291
timeout?: number;
292
interval?: number;
293
autoStart?: boolean;
294
params?: {
295
timeout?: number;
296
limit?: number;
297
allowed_updates?: string[];
298
};
299
};
300
webHook?: boolean | {
301
host?: string;
302
port?: number;
303
key?: string;
304
cert?: string;
305
pfx?: string;
306
autoOpen?: boolean;
307
https?: object;
308
healthEndpoint?: string;
309
};
310
onlyFirstMatch?: boolean;
311
request?: object;
312
baseApiUrl?: string;
313
filepath?: boolean;
314
badRejection?: boolean;
315
testEnvironment?: boolean;
316
}
317
```