0
# Message Handling and Events
1
2
Event-driven message processing with support for text pattern matching, reply handling, and custom event listeners for different message types.
3
4
## Capabilities
5
6
### Event Listeners
7
8
Methods for handling different types of Telegram updates through the EventEmitter interface.
9
10
```javascript { .api }
11
/**
12
* Add event listener for specified event type
13
* @param {string} event - Event name (message, callback_query, etc.)
14
* @param {function} listener - Event handler function
15
*/
16
on(event, listener): void;
17
18
/**
19
* Add one-time event listener
20
* @param {string} event - Event name
21
* @param {function} listener - Event handler function
22
*/
23
once(event, listener): void;
24
25
/**
26
* Remove event listener
27
* @param {string} event - Event name
28
* @param {function} listener - Event handler function to remove
29
*/
30
removeListener(event, listener): void;
31
```
32
33
**Usage Example:**
34
35
```javascript
36
// Listen for all messages
37
bot.on('message', (msg) => {
38
console.log('Received message:', msg.text);
39
console.log('From user:', msg.from.first_name);
40
console.log('Chat ID:', msg.chat.id);
41
});
42
43
// Listen for specific message types
44
bot.on('photo', (msg) => {
45
console.log('Received photo:', msg.photo);
46
});
47
48
bot.on('document', (msg) => {
49
console.log('Received document:', msg.document.file_name);
50
});
51
52
// Listen for callback queries from inline keyboards
53
bot.on('callback_query', (callbackQuery) => {
54
const message = callbackQuery.message;
55
const data = callbackQuery.data;
56
57
console.log('Callback data:', data);
58
bot.answerCallbackQuery(callbackQuery.id);
59
});
60
61
// Listen for inline queries
62
bot.on('inline_query', (inlineQuery) => {
63
console.log('Inline query:', inlineQuery.query);
64
});
65
```
66
67
### Text Pattern Matching
68
69
Methods for matching text messages against regular expressions and handling command-like interactions.
70
71
```javascript { .api }
72
/**
73
* Register RegExp to test against incoming text messages
74
* @param {RegExp} regexp - Regular expression to match
75
* @param {function} callback - Callback function (msg, match)
76
*/
77
onText(regexp, callback): void;
78
79
/**
80
* Remove text listener registered with onText()
81
* @param {RegExp} regexp - Regular expression to remove
82
* @returns {object|null} Removed listener object or null
83
*/
84
removeTextListener(regexp): object|null;
85
86
/**
87
* Remove all text listeners
88
*/
89
clearTextListeners(): void;
90
```
91
92
**Usage Example:**
93
94
```javascript
95
// Match commands with parameters
96
bot.onText(/\/start (.+)/, (msg, match) => {
97
const chatId = msg.chat.id;
98
const parameter = match[1];
99
100
bot.sendMessage(chatId, `Welcome! Parameter: ${parameter}`);
101
});
102
103
// Match echo command
104
bot.onText(/\/echo (.+)/, (msg, match) => {
105
const chatId = msg.chat.id;
106
const resp = match[1];
107
108
bot.sendMessage(chatId, resp);
109
});
110
111
// Match help command
112
const helpRegex = /\/help/;
113
bot.onText(helpRegex, (msg) => {
114
const chatId = msg.chat.id;
115
bot.sendMessage(chatId, 'Available commands: /start, /echo, /help');
116
});
117
118
// Remove specific text listener
119
bot.removeTextListener(helpRegex);
120
121
// Clear all text listeners
122
bot.clearTextListeners();
123
```
124
125
### Reply Handling
126
127
Methods for handling replies to specific messages with callback registration and management.
128
129
```javascript { .api }
130
/**
131
* Register callback for replies to specific message
132
* @param {number|string} chatId - Chat identifier
133
* @param {number} messageId - Message identifier
134
* @param {function} callback - Callback function for replies
135
* @returns {number} Listener ID for removal
136
*/
137
onReplyToMessage(chatId, messageId, callback): number;
138
139
/**
140
* Remove reply listener by ID
141
* @param {number} replyListenerId - Listener ID returned by onReplyToMessage
142
* @returns {object|null} Removed listener object or null
143
*/
144
removeReplyListener(replyListenerId): object|null;
145
146
/**
147
* Remove all reply listeners
148
* @returns {array} Array of removed listeners
149
*/
150
clearReplyListeners(): array;
151
```
152
153
**Usage Example:**
154
155
```javascript
156
// Ask for user input and handle reply
157
bot.sendMessage(chatId, 'What is your name?')
158
.then((sentMessage) => {
159
// Wait for reply to this specific message
160
const listenerId = bot.onReplyToMessage(chatId, sentMessage.message_id, (replyMsg) => {
161
const userName = replyMsg.text;
162
bot.sendMessage(chatId, `Nice to meet you, ${userName}!`);
163
164
// Remove the listener after use
165
bot.removeReplyListener(listenerId);
166
});
167
});
168
169
// Multiple step conversation
170
let step = 0;
171
const conversationSteps = ['name', 'age', 'city'];
172
173
bot.sendMessage(chatId, 'What is your name?')
174
.then((sentMessage) => {
175
const userData = {};
176
177
const listenerId = bot.onReplyToMessage(chatId, sentMessage.message_id, function handleStep(replyMsg) {
178
const currentStep = conversationSteps[step];
179
userData[currentStep] = replyMsg.text;
180
step++;
181
182
if (step < conversationSteps.length) {
183
const nextStep = conversationSteps[step];
184
bot.sendMessage(chatId, `What is your ${nextStep}?`)
185
.then((nextMessage) => {
186
bot.removeReplyListener(listenerId);
187
bot.onReplyToMessage(chatId, nextMessage.message_id, handleStep);
188
});
189
} else {
190
bot.sendMessage(chatId, `Summary: ${JSON.stringify(userData, null, 2)}`);
191
bot.removeReplyListener(listenerId);
192
}
193
});
194
});
195
```
196
197
### Update Processing
198
199
Methods for handling raw updates and retrieving updates manually.
200
201
```javascript { .api }
202
/**
203
* Process incoming update and emit appropriate events
204
* @param {object} update - Telegram update object
205
*/
206
processUpdate(update): void;
207
208
/**
209
* Get updates using long polling
210
* @param {object} [options] - Options for getUpdates
211
* @param {number} [options.offset] - Identifier of first update to return
212
* @param {number} [options.limit] - Max number of updates (1-100)
213
* @param {number} [options.timeout] - Timeout for long polling
214
* @param {string[]} [options.allowed_updates] - Update types to receive
215
* @returns {Promise<Update[]>}
216
*/
217
getUpdates(options): Promise<Update[]>;
218
```
219
220
**Usage Example:**
221
222
```javascript
223
// Manually process updates (advanced usage)
224
const updates = await bot.getUpdates({
225
offset: lastUpdateId + 1,
226
limit: 100,
227
timeout: 30,
228
allowed_updates: ['message', 'callback_query']
229
});
230
231
updates.forEach(update => {
232
bot.processUpdate(update);
233
lastUpdateId = update.update_id;
234
});
235
236
// Custom update processing
237
bot.processUpdate({
238
update_id: 12345,
239
message: {
240
message_id: 1,
241
date: Math.floor(Date.now() / 1000),
242
chat: { id: chatId, type: 'private' },
243
from: { id: userId, first_name: 'Test' },
244
text: 'Hello, Bot!'
245
}
246
});
247
```
248
249
## Event Types
250
251
The bot emits the following events based on Telegram update types:
252
253
### Message Events
254
255
- `message` - Any message
256
- `text` - Text message
257
- `photo` - Photo message
258
- `video` - Video message
259
- `audio` - Audio message
260
- `document` - Document message
261
- `sticker` - Sticker message
262
- `voice` - Voice message
263
- `video_note` - Video note message
264
- `animation` - Animation/GIF message
265
- `contact` - Contact message
266
- `location` - Location message
267
- `venue` - Venue message
268
- `poll` - Poll message
269
- `dice` - Dice message
270
- `game` - Game message
271
- `invoice` - Invoice message
272
273
### Chat Events
274
275
- `new_chat_members` - New members joined
276
- `left_chat_member` - Member left
277
- `new_chat_title` - Chat title changed
278
- `new_chat_photo` - Chat photo changed
279
- `delete_chat_photo` - Chat photo deleted
280
- `group_chat_created` - Group chat created
281
- `supergroup_chat_created` - Supergroup created
282
- `channel_chat_created` - Channel created
283
- `message_auto_delete_timer_changed` - Auto-delete timer changed
284
- `migrate_to_chat_id` - Group migrated to supergroup
285
- `migrate_from_chat_id` - Supergroup migrated from group
286
- `pinned_message` - Message pinned
287
288
### Interaction Events
289
290
- `callback_query` - Inline keyboard button pressed
291
- `inline_query` - Inline query received
292
- `chosen_inline_result` - Inline result chosen
293
- `shipping_query` - Shipping query for payments
294
- `pre_checkout_query` - Pre-checkout query for payments
295
- `successful_payment` - Payment completed
296
297
### Other Events
298
299
- `passport_data` - Telegram Passport data
300
- `web_app_data` - Web App data
301
- `video_chat_started` - Video chat started
302
- `video_chat_ended` - Video chat ended
303
- `video_chat_participants_invited` - Participants invited to video chat
304
- `video_chat_scheduled` - Video chat scheduled
305
- `chat_member_updated` - Chat member status updated
306
- `my_chat_member` - Bot's chat member status updated
307
- `chat_join_request` - Chat join request
308
- `message_reaction` - Message reaction changed
309
310
## Types
311
312
```javascript { .api }
313
interface Update {
314
update_id: number;
315
message?: Message;
316
edited_message?: Message;
317
channel_post?: Message;
318
edited_channel_post?: Message;
319
inline_query?: InlineQuery;
320
chosen_inline_result?: ChosenInlineResult;
321
callback_query?: CallbackQuery;
322
shipping_query?: ShippingQuery;
323
pre_checkout_query?: PreCheckoutQuery;
324
poll?: Poll;
325
poll_answer?: PollAnswer;
326
my_chat_member?: ChatMemberUpdated;
327
chat_member?: ChatMemberUpdated;
328
chat_join_request?: ChatJoinRequest;
329
message_reaction?: MessageReactionUpdated;
330
message_reaction_count?: MessageReactionCountUpdated;
331
chat_boost?: ChatBoostUpdated;
332
removed_chat_boost?: ChatBoostRemoved;
333
business_connection?: BusinessConnection;
334
business_message?: Message;
335
edited_business_message?: Message;
336
deleted_business_messages?: BusinessMessagesDeleted;
337
}
338
339
interface Message {
340
message_id: number;
341
message_thread_id?: number;
342
from?: User;
343
sender_chat?: Chat;
344
date: number;
345
chat: Chat;
346
forward_origin?: MessageOrigin;
347
is_topic_message?: boolean;
348
is_automatic_forward?: boolean;
349
reply_to_message?: Message;
350
external_reply?: ExternalReplyInfo;
351
quote?: TextQuote;
352
reply_to_story?: Story;
353
via_bot?: User;
354
edit_date?: number;
355
has_protected_content?: boolean;
356
media_group_id?: string;
357
author_signature?: string;
358
text?: string;
359
entities?: MessageEntity[];
360
// ... additional message fields
361
}
362
```