@patricktobias86/node-red-telegram-account 1.1.16 → 1.1.17

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/CHANGELOG.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.1.17] - 2026-01-05
6
+ ### Fixed
7
+ - Receiver node now listens to Raw MTProto updates and derives sender/chat identity safely so valid messages (channel posts, anonymous admins, service messages, missing fromId) are no longer dropped.
8
+
5
9
  ## [1.1.16] - 2025-09-22
6
10
  ### Added
7
11
  - Receiver node option to ignore configurable message types (such as videos or documents) to prevent oversized uploads.
package/README.md CHANGED
@@ -18,7 +18,7 @@ See [docs/NODES.md](docs/NODES.md) for a detailed description of every node. Bel
18
18
 
19
19
  - **config** – stores your API credentials and caches sessions for reuse.
20
20
  - **auth** – interactive login that outputs a `stringSession` (also set on `msg.stringSession`).
21
- - **receiver** – emits messages for every incoming update (with optional ignore list, message type filter, and media size limit). Event listeners are cleaned up on node close so redeploys won't duplicate messages.
21
+ - **receiver** – emits messages for every incoming Telegram message using Raw MTProto updates (with optional ignore list, message type filter, and media size limit), including channel posts and service messages. Event listeners are cleaned up on node close so redeploys won't duplicate messages.
22
22
  - **command** – triggers when an incoming message matches a command or regex. Event listeners are removed on redeploy to prevent duplicates.
23
23
  - **send-message** – sends text or media messages with rich options.
24
24
  - **send-files** – uploads one or more files with captions and buttons.
package/docs/NODES.md CHANGED
@@ -8,7 +8,7 @@ Below is a short description of each node. For a full list of configuration opti
8
8
  |------|-------------|
9
9
  | **config** | Configuration node storing API credentials and connection options. Other nodes reference this to share a Telegram client and reuse the session. Connections are tracked in a Map with a reference count so multiple nodes can wait for the same connection. |
10
10
  | **auth** | Starts an interactive login flow. Produces a `stringSession` (available in both <code>msg.payload.stringSession</code> and <code>msg.stringSession</code>) that can be reused with the `config` node. |
11
- | **receiver** | Emits an output message for every incoming Telegram message. Can ignore specific user IDs, skip selected message types (e.g. videos or documents), and optionally drop media above a configurable size. Event handlers are automatically removed when the node is closed. |
11
+ | **receiver** | Emits an output message for every incoming Telegram message using Raw MTProto updates (so channel posts, anonymous admins and service messages are not missed). Can ignore specific user IDs, skip selected message types (e.g. videos or documents), and optionally drop media above a configurable size. Output includes derived `peer`, `sender`, `senderType`, `senderId`, `chatId`, `isSilent`, and `messageTypes`. Event handlers are automatically removed when the node is closed. |
12
12
  | **command** | Listens for new messages and triggers when a message matches a configured command or regular expression. The event listener is cleaned up on node close to avoid duplicates. |
13
13
  | **send-message** | Sends text messages or media files to a chat. Supports parse mode, buttons, scheduling, and more. |
14
14
  | **send-files** | Uploads one or more files to a chat with optional caption, thumbnails and other parameters. |
package/nodes/receiver.js CHANGED
@@ -1,4 +1,4 @@
1
- const { NewMessage } = require("telegram/events");
1
+ const { Raw } = require("telegram/events");
2
2
  const util = require("util");
3
3
 
4
4
  const splitList = (value) => {
@@ -148,6 +148,184 @@ const collectMessageTypes = (message) => {
148
148
  return types;
149
149
  };
150
150
 
151
+ const getClassName = (value) => {
152
+ if (!value || typeof value !== 'object') {
153
+ return undefined;
154
+ }
155
+ return value.className || value._;
156
+ };
157
+
158
+ const toPeerInfo = (peer) => {
159
+ if (!peer || typeof peer !== 'object') {
160
+ return null;
161
+ }
162
+
163
+ const className = getClassName(peer);
164
+ const userId = peer.userId ?? peer.user_id;
165
+ const chatId = peer.chatId ?? peer.chat_id;
166
+ const channelId = peer.channelId ?? peer.channel_id;
167
+
168
+ // GramJS TL objects represent peers as PeerUser / PeerChat / PeerChannel.
169
+ // MTProto updates can omit fromId (anonymous admins, channel posts, etc.), so
170
+ // we normalize peer identity from whichever peer object we have.
171
+ if (userId != null) {
172
+ return { type: 'user', userId, chatId: null, channelId: null, peer };
173
+ }
174
+ if (chatId != null) {
175
+ return { type: 'chat', userId: null, chatId, channelId: null, peer };
176
+ }
177
+ if (channelId != null) {
178
+ return { type: 'channel', userId: null, chatId: null, channelId, peer };
179
+ }
180
+
181
+ if (className) {
182
+ return { type: className, userId: null, chatId: null, channelId: null, peer };
183
+ }
184
+ return { type: 'unknown', userId: null, chatId: null, channelId: null, peer };
185
+ };
186
+
187
+ const toSafeNumber = (value) => {
188
+ if (typeof value === 'number') {
189
+ return Number.isFinite(value) ? value : null;
190
+ }
191
+ if (typeof value === 'bigint') {
192
+ const result = Number(value);
193
+ return Number.isFinite(result) ? result : Number.MAX_SAFE_INTEGER;
194
+ }
195
+ return null;
196
+ };
197
+
198
+ const peerChatId = (peerInfo) => {
199
+ if (!peerInfo) {
200
+ return null;
201
+ }
202
+ // For Node-RED flows "chatId" typically means "the conversation identifier".
203
+ // For private chats that's the userId; for groups it's chatId; for channels it's channelId.
204
+ if (peerInfo.type === 'user') {
205
+ return toSafeNumber(peerInfo.userId);
206
+ }
207
+ if (peerInfo.type === 'chat') {
208
+ return toSafeNumber(peerInfo.chatId);
209
+ }
210
+ if (peerInfo.type === 'channel') {
211
+ return toSafeNumber(peerInfo.channelId);
212
+ }
213
+ return null;
214
+ };
215
+
216
+ const buildPeerUser = (userId) => ({ className: 'PeerUser', userId });
217
+ const buildPeerChat = (chatId) => ({ className: 'PeerChat', chatId });
218
+
219
+ const toDerivedMessage = (update) => {
220
+ const className = getClassName(update);
221
+ if (className === 'UpdateShortMessage') {
222
+ const userId = update.userId ?? update.user_id;
223
+ return {
224
+ className: 'Message',
225
+ id: update.id,
226
+ date: update.date,
227
+ out: update.out,
228
+ silent: update.silent,
229
+ // In UpdateShortMessage, userId is the peer and also the sender for incoming messages.
230
+ peerId: userId != null ? buildPeerUser(userId) : undefined,
231
+ fromId: userId != null ? buildPeerUser(userId) : undefined,
232
+ message: update.message,
233
+ entities: update.entities,
234
+ fwdFrom: update.fwdFrom,
235
+ viaBotId: update.viaBotId,
236
+ replyTo: update.replyTo,
237
+ ttlPeriod: update.ttlPeriod,
238
+ media: update.media
239
+ };
240
+ }
241
+
242
+ if (className === 'UpdateShortChatMessage') {
243
+ const chatId = update.chatId ?? update.chat_id;
244
+ const fromId = update.fromId ?? update.from_id;
245
+ return {
246
+ className: 'Message',
247
+ id: update.id,
248
+ date: update.date,
249
+ out: update.out,
250
+ silent: update.silent,
251
+ peerId: chatId != null ? buildPeerChat(chatId) : undefined,
252
+ fromId: fromId != null ? buildPeerUser(fromId) : undefined,
253
+ message: update.message,
254
+ entities: update.entities,
255
+ fwdFrom: update.fwdFrom,
256
+ viaBotId: update.viaBotId,
257
+ replyTo: update.replyTo,
258
+ ttlPeriod: update.ttlPeriod,
259
+ media: update.media
260
+ };
261
+ }
262
+
263
+ if (className === 'UpdateShortSentMessage') {
264
+ // This update doesn't include a peer; it's still a real MTProto message update.
265
+ // We emit it with a best-effort message shape so flows can still react.
266
+ return {
267
+ className: 'Message',
268
+ id: update.id,
269
+ date: update.date,
270
+ out: true,
271
+ silent: update.silent,
272
+ message: update.message,
273
+ entities: update.entities,
274
+ media: update.media
275
+ };
276
+ }
277
+
278
+ return null;
279
+ };
280
+
281
+ const extractMessageEvents = (rawUpdate) => {
282
+ // Raw MTProto updates can be nested (Updates / UpdatesCombined / UpdateShort).
283
+ // We must unwrap them here instead of relying on NewMessage(), which can miss
284
+ // valid message updates (e.g. channel posts, edits, anonymous admins).
285
+ const results = [];
286
+
287
+ const walk = (update) => {
288
+ if (!update || typeof update !== 'object') {
289
+ return;
290
+ }
291
+
292
+ const className = getClassName(update);
293
+
294
+ if (Array.isArray(update.updates)) {
295
+ for (const nested of update.updates) {
296
+ walk(nested);
297
+ }
298
+ return;
299
+ }
300
+
301
+ if (update.update) {
302
+ walk(update.update);
303
+ return;
304
+ }
305
+
306
+ if (className === 'UpdateNewMessage' ||
307
+ className === 'UpdateNewChannelMessage' ||
308
+ className === 'UpdateEditMessage' ||
309
+ className === 'UpdateEditChannelMessage') {
310
+ if (update.message) {
311
+ results.push({ update, message: update.message });
312
+ } else {
313
+ results.push({ update, message: null });
314
+ }
315
+ return;
316
+ }
317
+
318
+ const derived = toDerivedMessage(update);
319
+ if (derived) {
320
+ results.push({ update, message: derived });
321
+ return;
322
+ }
323
+ };
324
+
325
+ walk(rawUpdate);
326
+ return results;
327
+ };
328
+
151
329
  module.exports = function (RED) {
152
330
  function Receiver(config) {
153
331
  RED.nodes.createNode(this, config);
@@ -162,17 +340,6 @@ module.exports = function (RED) {
162
340
  ? maxFileSizeMb * 1024 * 1024
163
341
  : null;
164
342
 
165
- const toNumber = (value) => {
166
- if (typeof value === 'number') {
167
- return value;
168
- }
169
- if (typeof value === 'bigint') {
170
- const result = Number(value);
171
- return Number.isFinite(result) ? result : Number.MAX_SAFE_INTEGER;
172
- }
173
- return undefined;
174
- };
175
-
176
343
  const extractPhotoSize = (photo) => {
177
344
  if (!photo || !Array.isArray(photo.sizes)) {
178
345
  return null;
@@ -184,13 +351,13 @@ module.exports = function (RED) {
184
351
  }
185
352
  if (Array.isArray(size.sizes)) {
186
353
  for (const nested of size.sizes) {
187
- const nestedValue = toNumber(nested);
354
+ const nestedValue = toSafeNumber(nested);
188
355
  if (nestedValue != null && nestedValue > max) {
189
356
  max = nestedValue;
190
357
  }
191
358
  }
192
359
  }
193
- const value = toNumber(size.size ?? size.length ?? size.bytes);
360
+ const value = toSafeNumber(size.size ?? size.length ?? size.bytes);
194
361
  if (value != null && value > max) {
195
362
  max = value;
196
363
  }
@@ -204,7 +371,7 @@ module.exports = function (RED) {
204
371
  }
205
372
 
206
373
  if (media.document && media.document.size != null) {
207
- const value = toNumber(media.document.size);
374
+ const value = toSafeNumber(media.document.size);
208
375
  if (value != null) {
209
376
  return value;
210
377
  }
@@ -219,7 +386,7 @@ module.exports = function (RED) {
219
386
 
220
387
  if (media.webpage) {
221
388
  const { document, photo } = media.webpage;
222
- const docSize = document && toNumber(document.size);
389
+ const docSize = document && toSafeNumber(document.size);
223
390
  if (docSize != null) {
224
391
  return docSize;
225
392
  }
@@ -231,7 +398,7 @@ module.exports = function (RED) {
231
398
 
232
399
  const className = media.className || media._;
233
400
  if ((className === 'MessageMediaDocument' || className === 'MessageMediaPhoto') && media.size != null) {
234
- const value = toNumber(media.size);
401
+ const value = toSafeNumber(media.size);
235
402
  if (value != null) {
236
403
  return value;
237
404
  }
@@ -240,45 +407,94 @@ module.exports = function (RED) {
240
407
  return null;
241
408
  };
242
409
 
243
- const event = new NewMessage();
244
- const handler = (update) => {
410
+ const debugLog = (message) => {
411
+ if (node.debugEnabled) {
412
+ node.log(message);
413
+ }
414
+ };
415
+
416
+ const event = new Raw({});
417
+ const handler = (rawUpdate) => {
245
418
  const debug = node.debugEnabled;
246
419
  if (debug) {
247
- node.log('receiver update: ' + util.inspect(update, { depth: null }));
420
+ node.log('receiver raw update: ' + util.inspect(rawUpdate, { depth: null }));
248
421
  }
249
- const message = update && update.message;
250
- if (!message) {
422
+
423
+ const extracted = extractMessageEvents(rawUpdate);
424
+ if (extracted.length === 0) {
425
+ // Raw emits *all* MTProto updates; many are not message-bearing updates (typing, reads, etc.).
426
+ // We do not output those by default, but we also do not silently hide that they occurred.
427
+ debugLog(`receiver ignoring non-message MTProto update: ${getClassName(rawUpdate) || 'unknown'}`);
251
428
  return;
252
429
  }
253
430
 
254
- if (ignoredMessageTypes.size > 0) {
431
+ for (const { update, message } of extracted) {
432
+ if (!message) {
433
+ debugLog(`receiver ignoring message update without message payload: ${getClassName(update) || 'unknown'}`);
434
+ continue;
435
+ }
436
+
255
437
  const messageTypes = collectMessageTypes(message);
256
- const shouldIgnoreType = Array.from(messageTypes).some((type) => ignoredMessageTypes.has(type));
257
- if (shouldIgnoreType) {
258
- if (debug) {
259
- node.log(`receiver ignoring update with types: ${Array.from(messageTypes).join(', ')}`);
438
+ const isSilent = Boolean(message.silent || update.silent);
439
+
440
+ const peer = toPeerInfo(message.peerId || message.toId);
441
+
442
+ // Do NOT assume message.fromId.userId exists.
443
+ // fromId can be PeerUser / PeerChat / PeerChannel, can be missing (channel posts),
444
+ // and can represent anonymous admins. Prefer fromId when present; otherwise fall back
445
+ // to the chat peer for channel posts to avoid dropping valid messages.
446
+ const sender =
447
+ toPeerInfo(message.fromId) ||
448
+ (message.senderId != null ? toPeerInfo(buildPeerUser(message.senderId)) : null) ||
449
+ (message.post ? peer : null);
450
+
451
+ const senderType = sender ? sender.type : 'unknown';
452
+ const senderId =
453
+ senderType === 'user' ? toSafeNumber(sender.userId) :
454
+ senderType === 'chat' ? toSafeNumber(sender.chatId) :
455
+ senderType === 'channel' ? toSafeNumber(sender.channelId) :
456
+ null;
457
+
458
+ const chatId = peerChatId(peer);
459
+
460
+ if (ignoredMessageTypes.size > 0) {
461
+ const shouldIgnoreType = Array.from(messageTypes).some((type) => ignoredMessageTypes.has(type));
462
+ if (shouldIgnoreType) {
463
+ debugLog(`receiver ignoring message due to ignoreMessageTypes; types=${Array.from(messageTypes).join(', ')}`);
464
+ continue;
260
465
  }
261
- return;
262
466
  }
263
- }
264
467
 
265
- if (maxFileSizeBytes != null) {
266
- const mediaSize = extractMediaSize(message.media);
267
- if (mediaSize != null && mediaSize > maxFileSizeBytes) {
268
- if (debug) {
269
- node.log(`receiver ignoring update with media size ${mediaSize} bytes exceeding limit ${maxFileSizeBytes}`);
468
+ if (maxFileSizeBytes != null) {
469
+ const mediaSize = extractMediaSize(message.media);
470
+ if (mediaSize != null && mediaSize > maxFileSizeBytes) {
471
+ debugLog(`receiver ignoring message due to maxFileSizeMb; mediaSize=${mediaSize} limitBytes=${maxFileSizeBytes}`);
472
+ continue;
270
473
  }
271
- return;
272
474
  }
273
- }
274
475
 
275
- const senderId = message.fromId && message.fromId.userId;
276
- if (senderId != null && ignore.includes(senderId.toString())) {
277
- return;
278
- }
476
+ // Preserve existing behavior: ignore list is a list of user IDs.
477
+ // Previously the node assumed message.fromId.userId always existed, which dropped valid updates.
478
+ // Now we only apply the ignore list when we can confidently identify a user sender.
479
+ if (senderType === 'user' && senderId != null && ignore.includes(String(senderId))) {
480
+ debugLog(`receiver ignoring message due to ignore list; userId=${senderId}`);
481
+ continue;
482
+ }
483
+
484
+ const out = {
485
+ payload: {
486
+ update,
487
+ message,
488
+ peer,
489
+ sender,
490
+ senderType,
491
+ senderId,
492
+ chatId,
493
+ isSilent,
494
+ messageTypes: Array.from(messageTypes)
495
+ }
496
+ };
279
497
 
280
- if (message.fromId != null && message.fromId.userId != null) {
281
- const out = { payload: { update } };
282
498
  node.send(out);
283
499
  if (debug) {
284
500
  node.log('receiver output: ' + util.inspect(out, { depth: null }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@patricktobias86/node-red-telegram-account",
3
- "version": "1.1.16",
3
+ "version": "1.1.17",
4
4
  "description": "Node-RED nodes to communicate with GramJS.",
5
5
  "main": "nodes/config.js",
6
6
  "keywords": [
@@ -8,7 +8,7 @@ function load() {
8
8
  addEventHandler(fn, event) { addCalls.push({fn, event}); }
9
9
  removeEventHandler() {}
10
10
  }
11
- class NewMessageStub {}
11
+ class RawStub {}
12
12
 
13
13
  let NodeCtor;
14
14
  const configNode = { client: new TelegramClientStub() };
@@ -26,7 +26,7 @@ function load() {
26
26
  };
27
27
 
28
28
  proxyquire('../nodes/receiver.js', {
29
- 'telegram/events': { NewMessage: NewMessageStub }
29
+ 'telegram/events': { Raw: RawStub }
30
30
  })(RED);
31
31
 
32
32
  return { NodeCtor, addCalls, logs };
@@ -37,8 +37,11 @@ describe('Receiver node debug with BigInt', function() {
37
37
  const { NodeCtor, addCalls, logs } = load();
38
38
  const node = new NodeCtor({config:'c', ignore:'', debug:true});
39
39
  const handler = addCalls[0].fn;
40
- assert.doesNotThrow(() => handler({ message: { fromId:{userId:1n} } }));
41
- assert(logs.some(l => l.includes('receiver update')));
40
+ assert.doesNotThrow(() => handler({
41
+ className: 'UpdateNewMessage',
42
+ message: { fromId:{userId:1n}, peerId:{userId:1n}, message:'hi' }
43
+ }));
44
+ assert(logs.some(l => l.includes('receiver raw update')));
42
45
  assert(logs.some(l => l.includes('receiver output')));
43
46
  });
44
47
  });
@@ -8,7 +8,7 @@ function load() {
8
8
  addEventHandler(fn, event) { addCalls.push({fn, event}); }
9
9
  removeEventHandler(fn, event) { removeCalls.push({fn, event}); }
10
10
  }
11
- class NewMessageStub {}
11
+ class RawStub {}
12
12
 
13
13
  let NodeCtor;
14
14
  const configNode = { client: new TelegramClientStub() };
@@ -24,7 +24,7 @@ function load() {
24
24
  };
25
25
 
26
26
  proxyquire('../nodes/receiver.js', {
27
- 'telegram/events': { NewMessage: NewMessageStub }
27
+ 'telegram/events': { Raw: RawStub }
28
28
  })(RED);
29
29
 
30
30
  return { NodeCtor, addCalls, removeCalls };
@@ -48,7 +48,10 @@ describe('Receiver node', function() {
48
48
  node.send = (msg) => sent.push(msg);
49
49
  const handler = addCalls[0].fn;
50
50
 
51
- handler({ message: { fromId: { userId: 123 }, media: { document: { size: 6 * 1024 * 1024 } } } });
51
+ handler({
52
+ className: 'UpdateNewMessage',
53
+ message: { fromId: { userId: 123 }, peerId:{ userId: 123 }, media: { document: { size: 6 * 1024 * 1024 } } }
54
+ });
52
55
 
53
56
  assert.strictEqual(sent.length, 0);
54
57
  });
@@ -60,7 +63,10 @@ describe('Receiver node', function() {
60
63
  node.send = (msg) => sent.push(msg);
61
64
  const handler = addCalls[0].fn;
62
65
 
63
- handler({ message: { fromId: { userId: 123 }, media: { document: { size: 3 * 1024 * 1024 } } } });
66
+ handler({
67
+ className: 'UpdateNewMessage',
68
+ message: { fromId: { userId: 123 }, peerId:{ userId: 123 }, media: { document: { size: 3 * 1024 * 1024 } } }
69
+ });
64
70
 
65
71
  assert.strictEqual(sent.length, 1);
66
72
  });
@@ -72,7 +78,10 @@ describe('Receiver node', function() {
72
78
  node.send = (msg) => sent.push(msg);
73
79
  const handler = addCalls[0].fn;
74
80
 
75
- handler({ message: { fromId: { userId: 123 }, media: { document: { mimeType: 'video/mp4', attributes: [{ className: 'DocumentAttributeVideo' }] } } } });
81
+ handler({
82
+ className: 'UpdateNewMessage',
83
+ message: { fromId: { userId: 123 }, peerId:{ userId: 123 }, media: { document: { mimeType: 'video/mp4', attributes: [{ className: 'DocumentAttributeVideo' }] } } }
84
+ });
76
85
 
77
86
  assert.strictEqual(sent.length, 0);
78
87
  });
@@ -84,7 +93,10 @@ describe('Receiver node', function() {
84
93
  node.send = (msg) => sent.push(msg);
85
94
  const handler = addCalls[0].fn;
86
95
 
87
- handler({ message: { fromId: { userId: 123 }, media: { document: { mimeType: 'video/mp4', attributes: [{ className: 'DocumentAttributeVideo' }] } } } });
96
+ handler({
97
+ className: 'UpdateNewMessage',
98
+ message: { fromId: { userId: 123 }, peerId:{ userId: 123 }, media: { document: { mimeType: 'video/mp4', attributes: [{ className: 'DocumentAttributeVideo' }] } } }
99
+ });
88
100
 
89
101
  assert.strictEqual(sent.length, 1);
90
102
  });