-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelegram-e2e-driver.js
More file actions
622 lines (522 loc) · 15.5 KB
/
Copy pathtelegram-e2e-driver.js
File metadata and controls
622 lines (522 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
import { loadE2EConfig, loadTelegramSession } from '../config.js';
import { resolveBotUsername } from './bot-api.js';
import { createTelegramUserClient } from './telegram-user-client.js';
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function getTimestamp(value) {
if (value == null) {
return 0;
}
if (value instanceof Date) {
return value.getTime();
}
if (typeof value === 'number') {
return value < 10_000_000_000 ? value * 1000 : value;
}
const parsed = new Date(value);
return Number.isNaN(parsed.getTime()) ? 0 : parsed.getTime();
}
function normalizePeerId(peerId) {
return peerId == null ? null : peerId.toString();
}
function expandChatIdVariants(chatId) {
const normalized = normalizePeerId(chatId);
if (!normalized) {
return [];
}
const variants = new Set([normalized]);
const unsigned = normalized.startsWith('-') ? normalized.slice(1) : normalized;
variants.add(unsigned);
variants.add(`-${unsigned}`);
if (!unsigned.startsWith('100')) {
variants.add(`-100${unsigned}`);
}
if (unsigned.startsWith('100')) {
const withoutPrefix = unsigned.slice(3);
variants.add(withoutPrefix);
variants.add(`-${withoutPrefix}`);
variants.add(`-100${withoutPrefix}`);
}
return [...variants];
}
function buildContainsPredicate(contains, predicate) {
return message => {
const text = message?.message || '';
if (contains != null && !text.includes(contains)) {
return false;
}
if (predicate && !predicate(message)) {
return false;
}
return true;
};
}
export class TelegramE2EDriver {
constructor({
botToken,
primaryGroupId,
userClient,
pollingIntervalMs = 1500,
defaultTimeoutMs = 30000,
userMessageDelayMs = 350
}) {
if (!botToken) {
throw new Error('TelegramE2EDriver requires a bot token');
}
this.botToken = botToken;
this.primaryGroupId = primaryGroupId;
this.userClient = userClient;
this.pollingIntervalMs = pollingIntervalMs;
this.defaultTimeoutMs = defaultTimeoutMs;
this.userMessageDelayMs = userMessageDelayMs;
this.chatEntityCache = new Map();
this.botUsername = null;
this.botEntity = null;
this.botPeerId = null;
this.lastUserMessageAt = 0;
}
async connect() {
await this.userClient.connect();
if (!(await this.userClient.isAuthorized())) {
throw new Error('Telegram user session is not authorized. Run npm run e2e:bootstrap-session first.');
}
this.botUsername = await resolveBotUsername(this.botToken);
this.botEntity = await this.userClient.client.getEntity(this.botUsername);
this.botPeerId = normalizePeerId(
await this.userClient.client.getPeerId(this.botEntity)
);
return this;
}
async disconnect() {
await this.userClient.disconnect();
}
async getPrimaryGroupEntity() {
return this.getChatEntity(this.primaryGroupId);
}
async getChatEntity(chatId) {
const cacheKey = normalizePeerId(chatId);
if (this.chatEntityCache.has(cacheKey)) {
return this.chatEntityCache.get(cacheKey);
}
const candidateIds = expandChatIdVariants(cacheKey);
if (cacheKey.startsWith('-')) {
const entity = await this.resolveChatEntityFromDialogs(candidateIds);
this.chatEntityCache.set(cacheKey, entity);
return entity;
}
try {
const entity = await this.userClient.client.getEntity(chatId);
this.chatEntityCache.set(cacheKey, entity);
return entity;
} catch (error) {
const entity = await this.resolveChatEntityFromDialogs(candidateIds, error);
this.chatEntityCache.set(cacheKey, entity);
return entity;
}
}
async resolveChatEntityFromDialogs(candidateIds, originalError = null) {
const dialogs = await this.userClient.client.getDialogs({ limit: 200 });
const candidates = new Set(candidateIds);
for (const dialog of dialogs) {
const dialogId = normalizePeerId(dialog?.id);
const entityId = normalizePeerId(dialog?.entity?.id);
const peerId = dialog?.entity
? normalizePeerId(await this.userClient.client.getPeerId(dialog.entity))
: null;
if (candidates.has(dialogId) || candidates.has(entityId) || candidates.has(peerId)) {
return dialog.entity;
}
}
throw originalError || new Error(`Could not resolve Telegram chat entity for ${candidateIds[0]}`);
}
async capturePrivateCheckpoint() {
const message = await this.getLatestMessageFromEntity(this.botEntity);
return message?.id || 0;
}
async captureChatCheckpoint({ chatId }) {
const message = await this.getLatestMessageInChat({ chatId });
return message?.id || 0;
}
async sendPrivateCommand(text) {
await this.paceUserMessage();
return this.userClient.client.sendMessage(this.botEntity, {
message: text,
parseMode: undefined
});
}
async sendPrivateText(text) {
return this.sendPrivateCommand(text);
}
async sendMessageToChat({ chatId, text, replyToMessageId }) {
await this.paceUserMessage();
const entity = await this.getChatEntity(chatId);
const sendOptions = {
message: text,
parseMode: undefined
};
if (replyToMessageId) {
sendOptions.replyTo = replyToMessageId;
}
return this.userClient.client.sendMessage(entity, sendOptions);
}
async deleteMessageInChat({ chatId, messageId, revoke = true }) {
const entity = await this.getChatEntity(chatId);
await this.userClient.client.deleteMessages(entity, [messageId], { revoke });
}
async deletePrivateMessage({ messageId, revoke = true }) {
await this.userClient.client.deleteMessages(this.botEntity, [messageId], { revoke });
}
async getRecentPrivateMessages({ limit = 100 } = {}) {
const messages = await this.userClient.client.getMessages(this.botEntity, { limit });
return messages.filter(Boolean);
}
async deletePrivateMessagesSince({
afterMessageId = 0,
includeBoundary = false,
limit = 200,
batchSize = 50,
revoke = true
} = {}) {
const messages = await this.getRecentPrivateMessages({ limit });
const messageIds = messages
.filter(message => includeBoundary ? message.id >= afterMessageId : message.id > afterMessageId)
.map(message => message.id)
.sort((left, right) => right - left);
for (let index = 0; index < messageIds.length; index += batchSize) {
const batch = messageIds.slice(index, index + batchSize);
await this.userClient.client.deleteMessages(this.botEntity, batch, { revoke });
}
return messageIds.length;
}
async waitForBotPrivateMessage({
contains,
predicate,
afterMessageId = 0,
timeoutMs = this.defaultTimeoutMs
} = {}) {
return this.waitForBotMessageInEntity({
entity: this.botEntity,
contains,
predicate,
afterMessageId,
timeoutMs
});
}
async waitForEditedBotPrivateMessage({
messageId,
contains,
predicate,
afterEditTimestamp = 0,
timeoutMs = this.defaultTimeoutMs
}) {
return this.waitForEditedBotMessageInEntity({
entity: this.botEntity,
messageId,
contains,
predicate,
afterEditTimestamp,
timeoutMs
});
}
async waitForBotPrivateMessageState({
messageId,
contains,
predicate,
timeoutMs = this.defaultTimeoutMs
}) {
return this.waitForBotMessageStateInEntity({
entity: this.botEntity,
messageId,
contains,
predicate,
timeoutMs,
errorContext: 'private chat'
});
}
async waitForPrivateMessageDeleted({
messageId,
timeoutMs = this.defaultTimeoutMs
}) {
return this.waitForMessageDeletedInEntity({
entity: this.botEntity,
messageId,
timeoutMs
});
}
async assertNoBotPrivateMessage({
afterMessageId = 0,
contains,
predicate,
timeoutMs = 3000
} = {}) {
return this.assertNoBotMessageInEntity({
entity: this.botEntity,
afterMessageId,
contains,
predicate,
timeoutMs
});
}
async waitForBotMessageInChat({
chatId,
contains,
predicate,
afterMessageId = 0,
timeoutMs = this.defaultTimeoutMs
}) {
const entity = await this.getChatEntity(chatId);
return this.waitForBotMessageInEntity({
entity,
contains,
predicate,
afterMessageId,
timeoutMs
});
}
async waitForEditedBotMessageInChat({
chatId,
messageId,
contains,
predicate,
afterEditTimestamp = 0,
timeoutMs = this.defaultTimeoutMs
}) {
const entity = await this.getChatEntity(chatId);
return this.waitForEditedBotMessageInEntity({
entity,
messageId,
contains,
predicate,
afterEditTimestamp,
timeoutMs,
errorContext: `chat ${chatId}`
});
}
async waitForMessageDeletedInChat({
chatId,
messageId,
timeoutMs = this.defaultTimeoutMs
}) {
const entity = await this.getChatEntity(chatId);
return this.waitForMessageDeletedInEntity({
entity,
messageId,
timeoutMs,
errorContext: `chat ${chatId}`
});
}
async clickButtonInPrivateMessage({
messageId,
buttonText,
callbackDataPattern
}) {
return this.clickButtonInEntity({
entity: this.botEntity,
messageId,
buttonText,
callbackDataPattern,
errorContext: 'private chat'
});
}
async clickButtonInChat({
chatId,
messageId,
buttonText,
callbackDataPattern
}) {
const entity = await this.getChatEntity(chatId);
return this.clickButtonInEntity({
entity,
messageId,
buttonText,
callbackDataPattern,
errorContext: `chat ${chatId}`
});
}
async clickButtonInEntity({
entity,
messageId,
buttonText,
callbackDataPattern,
errorContext
}) {
const message = await this.getMessageById({ entity, messageId });
if (!message) {
throw new Error(`Message ${messageId} was not found in ${errorContext}`);
}
if (buttonText) {
return message.click({ text: buttonText });
}
if (callbackDataPattern) {
const pattern = callbackDataPattern instanceof RegExp
? callbackDataPattern
: new RegExp(callbackDataPattern);
return message.click({
filter: button => {
const data = button?.data ? Buffer.from(button.data).toString('utf8') : '';
return pattern.test(data);
}
});
}
throw new Error('clickButtonInChat requires buttonText or callbackDataPattern');
}
async getLatestMessageInChat({ chatId, limit = 1 }) {
const entity = await this.getChatEntity(chatId);
const messages = await this.userClient.client.getMessages(entity, { limit });
return messages[0] || null;
}
async getPrivateMessageById(messageId) {
return this.getMessageById({ entity: this.botEntity, messageId });
}
async getLatestMessageFromEntity(entity, limit = 1) {
const messages = await this.userClient.client.getMessages(entity, { limit });
return messages[0] || null;
}
async getRecentBotMessagesInChat({ chatId, limit = 10 }) {
const entity = await this.getChatEntity(chatId);
const messages = await this.userClient.client.getMessages(entity, { limit });
return messages.filter(message => this.isFromBot(message));
}
async waitForBotMessageInEntity({
entity,
contains,
predicate,
afterMessageId = 0,
timeoutMs = this.defaultTimeoutMs
}) {
const matcher = buildContainsPredicate(contains, predicate);
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const messages = await this.userClient.client.getMessages(entity, { limit: 20 });
const matchedMessage = messages.find(message =>
message.id > afterMessageId &&
this.isFromBot(message) &&
matcher(message)
);
if (matchedMessage) {
return matchedMessage;
}
await sleep(this.pollingIntervalMs);
}
throw new Error(`Timed out waiting for bot message after message ${afterMessageId}`);
}
async waitForEditedBotMessageInEntity({
entity,
messageId,
contains,
predicate,
afterEditTimestamp = 0,
timeoutMs = this.defaultTimeoutMs,
errorContext = 'entity'
}) {
const matcher = buildContainsPredicate(contains, predicate);
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const message = await this.getMessageById({ entity, messageId });
const editTimestamp = getTimestamp(message?.editDate);
if (
message &&
this.isFromBot(message) &&
editTimestamp > afterEditTimestamp &&
matcher(message)
) {
return message;
}
await sleep(this.pollingIntervalMs);
}
throw new Error(`Timed out waiting for edited bot message ${messageId} in ${errorContext}`);
}
async waitForBotMessageStateInEntity({
entity,
messageId,
contains,
predicate,
timeoutMs = this.defaultTimeoutMs,
errorContext = 'entity'
}) {
const matcher = buildContainsPredicate(contains, predicate);
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const message = await this.getMessageById({ entity, messageId });
if (message && this.isFromBot(message) && matcher(message)) {
return message;
}
await sleep(this.pollingIntervalMs);
}
throw new Error(`Timed out waiting for bot message ${messageId} state in ${errorContext}`);
}
async waitForMessageDeletedInEntity({
entity,
messageId,
timeoutMs = this.defaultTimeoutMs,
errorContext = 'entity'
}) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const message = await this.getMessageById({ entity, messageId });
if (!message) {
return true;
}
await sleep(this.pollingIntervalMs);
}
throw new Error(`Timed out waiting for message ${messageId} to be deleted in ${errorContext}`);
}
async assertNoBotMessageInEntity({
entity,
contains,
predicate,
afterMessageId = 0,
timeoutMs = 3000
}) {
const matcher = buildContainsPredicate(contains, predicate);
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const messages = await this.userClient.client.getMessages(entity, { limit: 20 });
const matchedMessage = messages.find(message =>
message.id > afterMessageId &&
this.isFromBot(message) &&
matcher(message)
);
if (matchedMessage) {
throw new Error(`Unexpected bot message ${matchedMessage.id} appeared after ${afterMessageId}`);
}
await sleep(this.pollingIntervalMs);
}
return true;
}
async getMessageById({ entity, messageId }) {
const messages = await this.userClient.client.getMessages(entity, { ids: messageId });
return messages[0] || null;
}
isFromBot(message) {
return normalizePeerId(message?.senderId) === this.botPeerId;
}
async paceUserMessage() {
if (!this.userMessageDelayMs) {
return;
}
const now = Date.now();
const waitMs = this.userMessageDelayMs - (now - this.lastUserMessageAt);
if (waitMs > 0) {
await sleep(waitMs);
}
this.lastUserMessageAt = Date.now();
}
}
export async function createTelegramE2EDriverFromEnv(options = {}) {
const config = loadE2EConfig();
const sessionString = await loadTelegramSession(config);
const userClient = createTelegramUserClient({
...config,
telegramSession: sessionString
});
const driver = new TelegramE2EDriver({
botToken: config.botToken,
primaryGroupId: config.primaryGroupId,
userClient,
...options
});
await driver.connect();
return driver;
}