forked from Lexus2016/claude-code-studio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelegram-bot.js
More file actions
3315 lines (2830 loc) · 139 KB
/
telegram-bot.js
File metadata and controls
3315 lines (2830 loc) · 139 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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ─── Telegram Bot Module for Claude Code Studio ─────────────────────────────
// Long-polling bot that runs alongside the main server.
// No external dependencies — uses Node 20 built-in fetch.
// Security: Telegram User ID whitelist via pairing codes, content sanitization.
'use strict';
const EventEmitter = require('events');
const crypto = require('crypto');
const TELEGRAM_API = 'https://api.telegram.org/bot';
const PAIRING_CODE_TTL = 5 * 60 * 1000; // 5 minutes
const PAIRING_CODE_LENGTH = 6;
const MAX_FAILED_ATTEMPTS = 3;
const BLOCK_DURATION = 15 * 60 * 1000; // 15 minutes after too many wrong codes
const POLL_TIMEOUT = 30; // seconds (Telegram long-polling)
const MAX_MESSAGE_LENGTH = 4000; // Telegram max ~4096, keep margin
const RATE_LIMIT_WINDOW = 60 * 1000; // 1 minute
const RATE_LIMIT_MAX = 30; // commands per minute
// Patterns that indicate sensitive content — never sent through Telegram
const SENSITIVE_FILE_PATTERNS = [
/\.env$/i, /\.env\.\w+$/i,
/auth\.json$/i, /sessions-auth\.json$/i,
/config\.json$/i,
/credentials/i, /secrets?\./i,
/\.pem$/i, /\.key$/i, /\.p12$/i, /\.pfx$/i,
/id_rsa/i, /id_ed25519/i,
];
const SECRET_PATTERNS = [
/(?:api[_-]?key|token|secret|password|passwd|pwd)\s*[:=]\s*['"]?[\w\-\.]{8,}/gi,
/sk-[a-zA-Z0-9]{20,}/g,
/ghp_[a-zA-Z0-9]{36}/g,
/glpat-[a-zA-Z0-9\-_]{20,}/g,
/xoxb-[a-zA-Z0-9\-]+/g,
/AKIA[0-9A-Z]{16}/g,
/Bearer\s+[a-zA-Z0-9\-_.~+/]{20,}/g,
];
// ─── Bot Internationalization ───────────────────────────────────────────────
const BOT_I18N = {
uk: {
// Pairing & auth
'rate_limit': '⚠️ Забагато запитів. Зачекайте хвилину.',
'notif_on': '🔔 Сповіщення увімкнено',
'notif_off': '🔕 Сповіщення вимкнено',
'blocked': '🔒 Забагато невдалих спроб. Спробуйте через 15 хвилин.',
'new_conn_disabled': '🔒 Нові підключення зараз вимкнено.\n\nЗверніться до адміністратора для активації режиму підключення.',
'start_pairing': '👋 <b>Claude Code Studio</b>\n\nДля підключення введіть 6-символьний код з панелі налаштувань вашого Studio.\n\n💡 Код має вигляд: <code>XXX·XXX</code>',
'new_conn_off': '🔒 Нові підключення вимкнено.',
'already_paired': '✅ Цей пристрій вже підключено!',
'paired_ok': '✅ <b>Пристрій підключено!</b>\n\n📱 {name}\n\nТепер ви будете отримувати сповіщення та зможете керувати Studio віддалено.\n\nВведіть /help для списку команд.',
'use_menu': '🏠 Використовуйте меню нижче або кнопки в повідомленнях.',
'invalid_code': '❌ Невірний або прострочений код.\n\nЗалишилось спроб: {remaining}',
// Keyboard buttons (persistent)
'kb_menu': '🏠 Меню',
'kb_status': '📊 Статус',
// Main menu
'main_title': '🤖 <b>Claude Code Studio</b>',
'main_project': '📁 Проект: <code>{name}</code>',
'main_chat': '💬 Чат: {title}',
'main_choose': '\nОберіть дію:',
'btn_projects': '📁 Проекти',
'btn_chats': '💬 Чати',
'btn_tasks': '📋 Задачі',
'btn_status': '📊 Статус',
'btn_settings': '⚙ Налаштування',
'btn_remote_access': '🌐 Remote Access',
'btn_back': '← Назад',
'btn_back_menu': '← Меню',
'btn_back_projects': '← Проекти',
'btn_back_chats': '← Чати',
'btn_back_overview': '← Огляд',
'btn_next': 'Далі →',
'btn_write': '📝 Написати',
'btn_all_messages': '📜 Всі повідомлення',
'btn_cancel': '❌ Скасувати',
'btn_write_chat': '✉ Написати в чат',
'btn_refresh': '🔄 Оновити',
'btn_full_msg': '📄 Повне повідомлення',
'btn_more': '📜 Ще більше',
'btn_full_response': '📄 Повна відповідь',
'btn_main_menu': '← Головне меню',
'btn_parent_dir': '↑ Батьківська папка',
'btn_all_tasks': '🌍 Всі задачі',
'btn_disable_notif': '🔕 Вимкнути сповіщення',
'btn_enable_notif': '🔔 Увімкнути сповіщення',
'btn_unlink_device': '🔓 Відключити пристрій',
'btn_confirm_unlink': '✅ Так, відключити',
// Projects
'projects_title': '📁 <b>Проекти</b> ({count})',
'projects_empty': '📁 Немає проектів з чатами.',
'project_not_found': '❌ Проект не знайдено.',
'project_choose': '\n\nОберіть розділ:',
'project_set': '✅ Проект: <code>{name}</code>\n\nВведіть /chats для перегляду чатів.',
'project_invalid': '❌ Невірний номер. Спочатку виконайте /projects',
'project_current': '📁 Поточний проект: <code>{name}</code>',
'project_hint': '💡 Спочатку виконайте /projects, потім /project <code><номер></code>',
'project_chats_label': '{count} чатів',
'project_select_hint': '💡 /project <code><номер></code> — вибрати проект',
// Chats
'chats_title_project': '💬 <b>Чати</b> — {project}',
'chats_title_all': '💬 <b>Всі чати</b>',
'chats_empty': '💬 Немає чатів.',
'chat_untitled': 'Без назви',
'chat_not_found': '❌ Чат не знайдено.',
'session_not_found': '❌ Сесію не знайдено.',
'chat_messages': '{count} повідомлень',
'chat_no_messages': '📭 Немає повідомлень в цьому чаті.',
'chat_active': '💬 Активний чат: {title}',
'chat_hint': '💡 Спочатку /chats, потім /chat <code><номер></code>',
'chat_select_hint': '💡 /chat <code><номер></code> — відкрити чат',
'chat_invalid': '❌ Невірний номер. Спочатку виконайте /chats',
'chat_select_hint2': '💡 Спочатку виберіть чат: /chats → /chat <code><n></code>',
// Dialog
'dialog_messages': '📄 {count} повідомлень',
'dialog_page': '📄 {count} повідомлень | Сторінка {page}/{total}',
'dialog_page_short': '📄 Сторінка {page}/{total} | {count} повідомлень',
'dialog_separator': '· · · <i>{count} повідомлень</i> · · ·',
'dialog_truncated': '...скорочено',
// Compose
'compose_mode': '✉ <b>Режим відправки</b>\n\nВведіть повідомлення — воно буде відправлене в чат Claude.\n\n<i>Будь-який текст без / піде як повідомлення.</i>',
'compose_hint': '📝 Пишіть повідомлення — воно піде в цей чат',
'compose_no_session': 'Після цього просто пишіть повідомлення — вони будуть відправлені в чат.',
'compose_select_first': '💡 Спочатку виберіть чат:\n/projects → /project <code><n></code> → /chats → /chat <code><n></code>\n\nПісля цього просто пишіть повідомлення — вони будуть відправлені в чат.',
'compose_sent': '⏳ Повідомлення відправлено{note}. Чекаю відповідь...',
// Tasks
'tasks_title': '📋 <b>Задачі</b> ({count})',
'tasks_empty': '📋 Немає задач.',
// Status
'status_title': '📊 <b>Studio Status</b>',
'status_uptime': '⏱ Аптайм: {hours}h {mins}m',
'status_sessions': '💬 Сесій: {count}',
'status_messages': '📝 Повідомлень: {count}',
'status_tasks_count': '📋 Задач: {count}',
'status_tasks_heading': '<b>Задачі:</b>',
'status_devices': '📱 Підключених пристроїв: {count}',
'status_new_conn': '🔒 Нові підключення: {status}',
'status_conn_on': 'увімкнено',
'status_conn_off': 'вимкнено',
'status_devices_short': '📱 Пристроїв: {count}',
'status_tasks_label': '📋 <b>Задачі</b>',
'status_active_chats': '🟢 <b>Активних чатів: {count}</b>',
'status_active_none': '⚪ Немає активних чатів',
'status_active_source_tg': 'TG',
'status_active_source_web': 'Web',
'status_updated': '<i>Оновлено: {time}</i>',
// Settings
'settings_title': '⚙ <b>Налаштування</b>',
'settings_paired': '📅 Підключено: {date}',
'settings_notif': '🔔 Сповіщення: <b>{status}</b>',
'settings_unlink_confirm': '⚠️ <b>Відключити пристрій?</b>\n\nВи більше не зможете керувати Studio з цього акаунту.\nДля повторного підключення знадобиться новий код.',
'settings_unlinked': '🔓 Пристрій відключено.\n\nДля повторного підключення знадобиться новий код.',
'unlink_done': '🔓 Пристрій відключено від Studio.\n\nДля повторного підключення знадобиться новий код.',
'unlink_admin': '🔓 Ваш пристрій було відключено адміністратором.',
// Files
'files_denied': '🔒 Доступ заборонено.',
'files_denied_workspace': '🔒 Доступ заборонено — шлях поза межами workspace.',
'files_sensitive': '🔒 Цей файл містить конфіденційні дані і не може бути переглянутий через Telegram.',
'files_sensitive_short': '🔒 Файл містить конфіденційні дані.',
'files_empty_dir': '📂 Порожня директорія.',
'files_empty_label': '<i>(порожня)</i>',
'files_truncated': '✂️ <i>(скорочено, {len} символів)</i>',
'files_truncated_short': '✂️ <i>(скорочено)</i>',
// Ask User
'ask_answered': '✅ Відповідь відправлена.',
'ask_skipped': '⏭ Пропущено — Claude продовжить самостійно.',
'ask_selected': '✅ Обрано: {option}',
'ask_no_pending': '💡 Немає активного питання.',
'ask_title': 'Claude запитує:',
'ask_skip_btn': '⏭ Пропустити',
'ask_choose_hint': 'Оберіть варіант або натисніть «Пропустити»:',
'ask_text_hint': 'Введіть відповідь текстом або натисніть «Пропустити»:',
'ask_timeout': '⏱ Час вичерпано — Claude продовжив самостійно.',
// Errors
'error_prefix': '❌ Помилка: {msg}',
'error_unknown_cmd': '❓ Невідома команда: <code>{cmd}</code>\n\nВведіть /help для списку команд.',
// Time
'time_ago_now': 'щойно',
'time_ago_min': '{n} хв тому',
'time_ago_hour': '{n} год тому',
'time_ago_day': '{n} д тому',
'time_ago_long': 'давно',
// Help
'help_text': '📖 <b>Команди Claude Code Studio</b>\n\n<b>Навігація:</b>\n/projects — список проектів\n/project <code><n></code> — вибрати проект\n/chats — чати поточного проекту\n/chat <code><n></code> — відкрити чат\n/back — повернутися назад\n\n<b>Перегляд:</b>\n/last <code>[n]</code> — останні N повідомлень (5)\n/full — повна остання відповідь\n/tasks — задачі (Kanban)\n/files <code>[path]</code> — файли в workspace\n/cat <code><file></code> — вміст файлу\n/diff — git diff в workspace\n/log <code>[n]</code> — останні git коміти\n\n<b>Дії:</b>\n/new <code>[title]</code> — нова сесія\n/stop — зупинити поточну задачу\n\n<b>Remote Access:</b>\n/tunnel — керування доступом\n/url — показати публічний URL\n\n<b>Налаштування:</b>\n/status — стан Studio\n/notify <code>on/off</code> — сповіщення\n/unlink — відключити цей пристрій',
// Back navigation
'back_to_chats': '↩️ Повернулися до списку чатів. Введіть /chats',
'back_to_projects': '↩️ Повернулися до списку проектів. Введіть /projects',
'back_at_top': '📍 Ви на верхньому рівні. Введіть /projects',
// Notify
'notify_on': '🔔 Сповіщення увімкнено.',
'notify_off': '🔕 Сповіщення вимкнено.',
'notify_current': '🔔 Сповіщення: <b>{status}</b>\n\n💡 /notify <code>on</code> або /notify <code>off</code>',
// Remote Access
'tn_btn_start': '▶ Увімкнути',
'tn_btn_stop': '⏹ Вимкнути',
'tn_btn_status': '📊 Статус',
'tn_screen_active': '🟢 <b>Remote Access активний</b>\n\n🔗 {url}',
'tn_screen_inactive': '⚪ <b>Remote Access</b>\n\nДоступ не запущено. Натисніть "Увімкнути" щоб відкрити доступ до Studio через інтернет.',
'tn_not_running': '⚪ Доступ не запущено.',
'tn_notify_started': '🟢 <b>Remote Access відкрито</b>\n\n🔗 {url}',
'tn_notify_stopped': '⬛ Remote Access закрито.',
// Git
'git_no_changes': '📊 Немає змін або не git-репозиторій.',
'git_not_repo': '📊 Не git-репозиторій.',
'git_last_commits': '📜 <b>Останні {n} комітів</b>',
// Misc
'no_responses': '📭 Немає відповідей в цьому чаті.',
'select_chat_first': '💡 Спочатку виберіть чат.',
'select_chat_hint': '💡 Спочатку виберіть чат: /chats → /chat <code><n></code>',
'cat_usage': '💡 Використання: /cat <code><файл></code>',
'msg_full_hint': '📎 /full — повна остання відповідь',
'msg_compose_hint': '📝 Пишіть повідомлення — воно піде в цей чат',
// Attach
'attach_cleared': '🗑 Вкладення очищено.',
// Project screen buttons
'btn_files': '📁 Файли',
'btn_git_log': '📜 Git Log',
'btn_diff': '📊 Diff',
// Compose
'compose_prompt': '📝 Надішліть ваше повідомлення:',
'compose_select_first_short': '❌ Спочатку виберіть сесію чату',
// File errors
'files_too_large': '❌ Файл занадто великий (макс. 10MB)',
'files_download_error': '❌ Неможливо завантажити файл',
'files_download_failed': '❌ Завантаження не вдалося',
'files_process_error': '❌ Не вдалося обробити файл',
// Stop / New
'error_no_session': '❌ Немає вибраної активної сесії',
'stop_sent': '🛑 Сигнал зупинки надіслано...',
'new_session_created': '✅ <b>Нову сесію створено</b> (#{id})\n\nНадішліть ваше повідомлення:',
},
en: {
'rate_limit': '⚠️ Too many requests. Please wait a minute.',
'notif_on': '🔔 Notifications enabled',
'notif_off': '🔕 Notifications disabled',
'blocked': '🔒 Too many failed attempts. Try again in 15 minutes.',
'new_conn_disabled': '🔒 New connections are currently disabled.\n\nContact the administrator to enable connection mode.',
'start_pairing': '👋 <b>Claude Code Studio</b>\n\nEnter the 6-character code from your Studio settings panel to connect.\n\n💡 Code format: <code>XXX·XXX</code>',
'new_conn_off': '🔒 New connections disabled.',
'already_paired': '✅ This device is already connected!',
'paired_ok': '✅ <b>Device connected!</b>\n\n📱 {name}\n\nYou will now receive notifications and can control Studio remotely.\n\nType /help for a list of commands.',
'use_menu': '🏠 Use the menu below or inline buttons.',
'invalid_code': '❌ Invalid or expired code.\n\nAttempts remaining: {remaining}',
'kb_menu': '🏠 Menu',
'kb_status': '📊 Status',
'main_title': '🤖 <b>Claude Code Studio</b>',
'main_project': '📁 Project: <code>{name}</code>',
'main_chat': '💬 Chat: {title}',
'main_choose': '\nChoose an action:',
'btn_projects': '📁 Projects',
'btn_chats': '💬 Chats',
'btn_tasks': '📋 Tasks',
'btn_status': '📊 Status',
'btn_settings': '⚙ Settings',
'btn_remote_access': '🌐 Remote Access',
'btn_back': '← Back',
'btn_back_menu': '← Menu',
'btn_back_projects': '← Projects',
'btn_back_chats': '← Chats',
'btn_back_overview': '← Overview',
'btn_next': 'Next →',
'btn_write': '📝 Write',
'btn_all_messages': '📜 All messages',
'btn_cancel': '❌ Cancel',
'btn_write_chat': '✉ Write to chat',
'btn_refresh': '🔄 Refresh',
'btn_full_msg': '📄 Full message',
'btn_more': '📜 Load more',
'btn_full_response': '📄 Full response',
'btn_main_menu': '← Main menu',
'btn_parent_dir': '↑ Parent directory',
'btn_all_tasks': '🌍 All tasks',
'btn_disable_notif': '🔕 Disable notifications',
'btn_enable_notif': '🔔 Enable notifications',
'btn_unlink_device': '🔓 Unlink device',
'btn_confirm_unlink': '✅ Yes, unlink',
'projects_title': '📁 <b>Projects</b> ({count})',
'projects_empty': '📁 No projects with chats.',
'project_not_found': '❌ Project not found.',
'project_choose': '\n\nChoose a section:',
'project_set': '✅ Project: <code>{name}</code>\n\nType /chats to view chats.',
'project_invalid': '❌ Invalid number. Run /projects first.',
'project_current': '📁 Current project: <code>{name}</code>',
'project_hint': '💡 Run /projects first, then /project <code><number></code>',
'project_chats_label': '{count} chats',
'project_select_hint': '💡 /project <code><number></code> — select project',
'chats_title_project': '💬 <b>Chats</b> — {project}',
'chats_title_all': '💬 <b>All chats</b>',
'chats_empty': '💬 No chats.',
'chat_untitled': 'Untitled',
'chat_not_found': '❌ Chat not found.',
'session_not_found': '❌ Session not found.',
'chat_messages': '{count} messages',
'chat_no_messages': '📭 No messages in this chat.',
'chat_active': '💬 Active chat: {title}',
'chat_hint': '💡 Run /chats first, then /chat <code><number></code>',
'chat_select_hint': '💡 /chat <code><number></code> — open chat',
'chat_invalid': '❌ Invalid number. Run /chats first.',
'chat_select_hint2': '💡 Select a chat first: /chats → /chat <code><n></code>',
'dialog_messages': '📄 {count} messages',
'dialog_page': '📄 {count} messages | Page {page}/{total}',
'dialog_page_short': '📄 Page {page}/{total} | {count} messages',
'dialog_separator': '· · · <i>{count} messages</i> · · ·',
'dialog_truncated': '...truncated',
'compose_mode': '✉ <b>Compose mode</b>\n\nType your message — it will be sent to the Claude chat.\n\n<i>Any text without / will be sent as a message.</i>',
'compose_hint': '📝 Type a message — it will be sent to this chat',
'compose_no_session': 'Now just type messages — they will be sent to the chat.',
'compose_select_first': '💡 Select a chat first:\n/projects → /project <code><n></code> → /chats → /chat <code><n></code>\n\nThen just type messages — they will be sent to the chat.',
'compose_sent': '⏳ Message sent{note}. Waiting for response...',
'tasks_title': '📋 <b>Tasks</b> ({count})',
'tasks_empty': '📋 No tasks.',
'status_title': '📊 <b>Studio Status</b>',
'status_uptime': '⏱ Uptime: {hours}h {mins}m',
'status_sessions': '💬 Sessions: {count}',
'status_messages': '📝 Messages: {count}',
'status_tasks_count': '📋 Tasks: {count}',
'status_tasks_heading': '<b>Tasks:</b>',
'status_devices': '📱 Connected devices: {count}',
'status_new_conn': '🔒 New connections: {status}',
'status_conn_on': 'enabled',
'status_conn_off': 'disabled',
'status_devices_short': '📱 Devices: {count}',
'status_tasks_label': '📋 <b>Tasks</b>',
'status_active_chats': '🟢 <b>Active chats: {count}</b>',
'status_active_none': '⚪ No active chats',
'status_active_source_tg': 'TG',
'status_active_source_web': 'Web',
'status_updated': '<i>Updated: {time}</i>',
'settings_title': '⚙ <b>Settings</b>',
'settings_paired': '📅 Connected: {date}',
'settings_notif': '🔔 Notifications: <b>{status}</b>',
'settings_unlink_confirm': '⚠️ <b>Unlink device?</b>\n\nYou will no longer be able to control Studio from this account.\nA new code will be required to reconnect.',
'settings_unlinked': '🔓 Device unlinked.\n\nA new code will be required to reconnect.',
'unlink_done': '🔓 Device unlinked from Studio.\n\nA new code will be required to reconnect.',
'unlink_admin': '🔓 Your device has been unlinked by the administrator.',
'files_denied': '🔒 Access denied.',
'files_denied_workspace': '🔒 Access denied — path outside workspace.',
'files_sensitive': '🔒 This file contains sensitive data and cannot be viewed via Telegram.',
'files_sensitive_short': '🔒 File contains sensitive data.',
'files_empty_dir': '📂 Empty directory.',
'files_empty_label': '<i>(empty)</i>',
'files_truncated': '✂️ <i>(truncated, {len} characters)</i>',
'files_truncated_short': '✂️ <i>(truncated)</i>',
'ask_answered': '✅ Answer sent.',
'ask_skipped': '⏭ Skipped — Claude will proceed on its own.',
'ask_selected': '✅ Selected: {option}',
'ask_no_pending': '💡 No active question.',
'ask_title': 'Claude asks:',
'ask_skip_btn': '⏭ Skip',
'ask_choose_hint': 'Choose an option or tap "Skip":',
'ask_text_hint': 'Type your answer or tap "Skip":',
'ask_timeout': '⏱ Timed out — Claude proceeded on its own.',
'error_prefix': '❌ Error: {msg}',
'error_unknown_cmd': '❓ Unknown command: <code>{cmd}</code>\n\nType /help for a list of commands.',
'time_ago_now': 'just now',
'time_ago_min': '{n}m ago',
'time_ago_hour': '{n}h ago',
'time_ago_day': '{n}d ago',
'time_ago_long': 'long ago',
'help_text': '📖 <b>Claude Code Studio Commands</b>\n\n<b>Navigation:</b>\n/projects — list projects\n/project <code><n></code> — select project\n/chats — chats of current project\n/chat <code><n></code> — open chat\n/back — go back\n\n<b>View:</b>\n/last <code>[n]</code> — last N messages (5)\n/full — full last response\n/tasks — tasks (Kanban)\n/files <code>[path]</code> — files in workspace\n/cat <code><file></code> — file contents\n/diff — git diff in workspace\n/log <code>[n]</code> — recent git commits\n\n<b>Actions:</b>\n/new <code>[title]</code> — new session\n/stop — stop current task\n\n<b>Remote Access:</b>\n/tunnel — manage remote access\n/url — show public URL\n\n<b>Settings:</b>\n/status — Studio status\n/notify <code>on/off</code> — notifications\n/unlink — unlink this device',
'back_to_chats': '↩️ Back to chat list. Type /chats',
'back_to_projects': '↩️ Back to project list. Type /projects',
'back_at_top': '📍 You are at the top level. Type /projects',
'notify_on': '🔔 Notifications enabled.',
'notify_off': '🔕 Notifications disabled.',
'notify_current': '🔔 Notifications: <b>{status}</b>\n\n💡 /notify <code>on</code> or /notify <code>off</code>',
// Remote Access
'tn_btn_start': '▶ Start',
'tn_btn_stop': '⏹ Stop',
'tn_btn_status': '📊 Status',
'tn_screen_active': '🟢 <b>Remote Access active</b>\n\n🔗 {url}',
'tn_screen_inactive': '⚪ <b>Remote Access</b>\n\nNot running. Tap "Start" to expose Studio to the internet.',
'tn_not_running': '⚪ Remote access is not running.',
'tn_notify_started': '🟢 <b>Remote Access opened</b>\n\n🔗 {url}',
'tn_notify_stopped': '⬛ Remote access closed.',
'git_no_changes': '📊 No changes or not a git repository.',
'git_not_repo': '📊 Not a git repository.',
'git_last_commits': '📜 <b>Last {n} commits</b>',
'no_responses': '📭 No responses in this chat.',
'select_chat_first': '💡 Select a chat first.',
'select_chat_hint': '💡 Select a chat first: /chats → /chat <code><n></code>',
'cat_usage': '💡 Usage: /cat <code><file></code>',
'msg_full_hint': '📎 /full — full last response',
'msg_compose_hint': '📝 Type a message — it will be sent to this chat',
'attach_cleared': '🗑 Attachments cleared.',
// Project screen buttons
'btn_files': '📁 Files',
'btn_git_log': '📜 Git Log',
'btn_diff': '📊 Diff',
// Compose
'compose_prompt': '📝 Send your message:',
'compose_select_first_short': '❌ Select a chat session first',
// File errors
'files_too_large': '❌ File too large (max 10MB)',
'files_download_error': '❌ Cannot download file',
'files_download_failed': '❌ Download failed',
'files_process_error': '❌ Failed to process file',
// Stop / New
'error_no_session': '❌ No active session selected',
'stop_sent': '🛑 Stop signal sent...',
'new_session_created': '✅ <b>New session created</b> (#{id})\n\nSend your message:',
},
ru: {
'rate_limit': '⚠️ Слишком много запросов. Подождите минуту.',
'notif_on': '🔔 Уведомления включены',
'notif_off': '🔕 Уведомления отключены',
'blocked': '🔒 Слишком много неудачных попыток. Попробуйте через 15 минут.',
'new_conn_disabled': '🔒 Новые подключения сейчас отключены.\n\nОбратитесь к администратору для активации режима подключения.',
'start_pairing': '👋 <b>Claude Code Studio</b>\n\nДля подключения введите 6-символьный код из панели настроек вашего Studio.\n\n💡 Код имеет вид: <code>XXX·XXX</code>',
'new_conn_off': '🔒 Новые подключения отключены.',
'already_paired': '✅ Это устройство уже подключено!',
'paired_ok': '✅ <b>Устройство подключено!</b>\n\n📱 {name}\n\nТеперь вы будете получать уведомления и сможете управлять Studio удалённо.\n\nВведите /help для списка команд.',
'use_menu': '🏠 Используйте меню внизу или кнопки в сообщениях.',
'invalid_code': '❌ Неверный или просроченный код.\n\nОсталось попыток: {remaining}',
'kb_menu': '🏠 Меню',
'kb_status': '📊 Статус',
'main_title': '🤖 <b>Claude Code Studio</b>',
'main_project': '📁 Проект: <code>{name}</code>',
'main_chat': '💬 Чат: {title}',
'main_choose': '\nВыберите действие:',
'btn_projects': '📁 Проекты',
'btn_chats': '💬 Чаты',
'btn_tasks': '📋 Задачи',
'btn_status': '📊 Статус',
'btn_settings': '⚙ Настройки',
'btn_remote_access': '🌐 Remote Access',
'btn_back': '← Назад',
'btn_back_menu': '← Меню',
'btn_back_projects': '← Проекты',
'btn_back_chats': '← Чаты',
'btn_back_overview': '← Обзор',
'btn_next': 'Далее →',
'btn_write': '📝 Написать',
'btn_all_messages': '📜 Все сообщения',
'btn_cancel': '❌ Отмена',
'btn_write_chat': '✉ Написать в чат',
'btn_refresh': '🔄 Обновить',
'btn_full_msg': '📄 Полное сообщение',
'btn_more': '📜 Ещё больше',
'btn_full_response': '📄 Полный ответ',
'btn_main_menu': '← Главное меню',
'btn_parent_dir': '↑ Родительская папка',
'btn_all_tasks': '🌍 Все задачи',
'btn_disable_notif': '🔕 Отключить уведомления',
'btn_enable_notif': '🔔 Включить уведомления',
'btn_unlink_device': '🔓 Отключить устройство',
'btn_confirm_unlink': '✅ Да, отключить',
'projects_title': '📁 <b>Проекты</b> ({count})',
'projects_empty': '📁 Нет проектов с чатами.',
'project_not_found': '❌ Проект не найден.',
'project_choose': '\n\nВыберите раздел:',
'project_set': '✅ Проект: <code>{name}</code>\n\nВведите /chats для просмотра чатов.',
'project_invalid': '❌ Неверный номер. Сначала выполните /projects',
'project_current': '📁 Текущий проект: <code>{name}</code>',
'project_hint': '💡 Сначала выполните /projects, потом /project <code><номер></code>',
'project_chats_label': '{count} чатов',
'project_select_hint': '💡 /project <code><номер></code> — выбрать проект',
'chats_title_project': '💬 <b>Чаты</b> — {project}',
'chats_title_all': '💬 <b>Все чаты</b>',
'chats_empty': '💬 Нет чатов.',
'chat_untitled': 'Без названия',
'chat_not_found': '❌ Чат не найден.',
'session_not_found': '❌ Сессия не найдена.',
'chat_messages': '{count} сообщений',
'chat_no_messages': '📭 Нет сообщений в этом чате.',
'chat_active': '💬 Активный чат: {title}',
'chat_hint': '💡 Сначала /chats, потом /chat <code><номер></code>',
'chat_select_hint': '💡 /chat <code><номер></code> — открыть чат',
'chat_invalid': '❌ Неверный номер. Сначала выполните /chats',
'chat_select_hint2': '💡 Сначала выберите чат: /chats → /chat <code><n></code>',
'dialog_messages': '📄 {count} сообщений',
'dialog_page': '📄 {count} сообщений | Страница {page}/{total}',
'dialog_page_short': '📄 Страница {page}/{total} | {count} сообщений',
'dialog_separator': '· · · <i>{count} сообщений</i> · · ·',
'dialog_truncated': '...сокращено',
'compose_mode': '✉ <b>Режим отправки</b>\n\nВведите сообщение — оно будет отправлено в чат Claude.\n\n<i>Любой текст без / пойдёт как сообщение.</i>',
'compose_hint': '📝 Пишите сообщение — оно пойдёт в этот чат',
'compose_no_session': 'Теперь просто пишите сообщения — они будут отправлены в чат.',
'compose_select_first': '💡 Сначала выберите чат:\n/projects → /project <code><n></code> → /chats → /chat <code><n></code>\n\nТеперь просто пишите сообщения — они будут отправлены в чат.',
'compose_sent': '⏳ Сообщение отправлено{note}. Ожидаю ответ...',
'tasks_title': '📋 <b>Задачи</b> ({count})',
'tasks_empty': '📋 Нет задач.',
'status_title': '📊 <b>Studio Status</b>',
'status_uptime': '⏱ Аптайм: {hours}h {mins}m',
'status_sessions': '💬 Сессий: {count}',
'status_messages': '📝 Сообщений: {count}',
'status_tasks_count': '📋 Задач: {count}',
'status_tasks_heading': '<b>Задачи:</b>',
'status_devices': '📱 Подключённых устройств: {count}',
'status_new_conn': '🔒 Новые подключения: {status}',
'status_conn_on': 'включены',
'status_conn_off': 'отключены',
'status_devices_short': '📱 Устройств: {count}',
'status_tasks_label': '📋 <b>Задачи</b>',
'status_active_chats': '🟢 <b>Активных чатов: {count}</b>',
'status_active_none': '⚪ Нет активных чатов',
'status_active_source_tg': 'TG',
'status_active_source_web': 'Web',
'status_updated': '<i>Обновлено: {time}</i>',
'settings_title': '⚙ <b>Настройки</b>',
'settings_paired': '📅 Подключено: {date}',
'settings_notif': '🔔 Уведомления: <b>{status}</b>',
'settings_unlink_confirm': '⚠️ <b>Отключить устройство?</b>\n\nВы больше не сможете управлять Studio с этого аккаунта.\nДля повторного подключения понадобится новый код.',
'settings_unlinked': '🔓 Устройство отключено.\n\nДля повторного подключения понадобится новый код.',
'unlink_done': '🔓 Устройство отключено от Studio.\n\nДля повторного подключения понадобится новый код.',
'unlink_admin': '🔓 Ваше устройство было отключено администратором.',
'files_denied': '🔒 Доступ запрещён.',
'files_denied_workspace': '🔒 Доступ запрещён — путь вне workspace.',
'files_sensitive': '🔒 Этот файл содержит конфиденциальные данные и не может быть просмотрен через Telegram.',
'files_sensitive_short': '🔒 Файл содержит конфиденциальные данные.',
'files_empty_dir': '📂 Пустая директория.',
'files_empty_label': '<i>(пусто)</i>',
'files_truncated': '✂️ <i>(сокращено, {len} символов)</i>',
'files_truncated_short': '✂️ <i>(сокращено)</i>',
'ask_answered': '✅ Ответ отправлен.',
'ask_skipped': '⏭ Пропущено — Claude продолжит самостоятельно.',
'ask_selected': '✅ Выбрано: {option}',
'ask_no_pending': '💡 Нет активного вопроса.',
'ask_title': 'Claude спрашивает:',
'ask_skip_btn': '⏭ Пропустить',
'ask_choose_hint': 'Выберите вариант или нажмите «Пропустить»:',
'ask_text_hint': 'Введите ответ текстом или нажмите «Пропустить»:',
'ask_timeout': '⏱ Время вышло — Claude продолжил самостоятельно.',
'error_prefix': '❌ Ошибка: {msg}',
'error_unknown_cmd': '❓ Неизвестная команда: <code>{cmd}</code>\n\nВведите /help для списка команд.',
'time_ago_now': 'только что',
'time_ago_min': '{n} мин назад',
'time_ago_hour': '{n} ч назад',
'time_ago_day': '{n} д назад',
'time_ago_long': 'давно',
'help_text': '📖 <b>Команды Claude Code Studio</b>\n\n<b>Навигация:</b>\n/projects — список проектов\n/project <code><n></code> — выбрать проект\n/chats — чаты текущего проекта\n/chat <code><n></code> — открыть чат\n/back — вернуться назад\n\n<b>Просмотр:</b>\n/last <code>[n]</code> — последние N сообщений (5)\n/full — полный последний ответ\n/tasks — задачи (Kanban)\n/files <code>[path]</code> — файлы в workspace\n/cat <code><file></code> — содержимое файла\n/diff — git diff в workspace\n/log <code>[n]</code> — последние git коммиты\n\n<b>Действия:</b>\n/new <code>[title]</code> — новая сессия\n/stop — остановить текущую задачу\n\n<b>Remote Access:</b>\n/tunnel — управление доступом\n/url — показать публичный URL\n\n<b>Настройки:</b>\n/status — состояние Studio\n/notify <code>on/off</code> — уведомления\n/unlink — отключить это устройство',
'back_to_chats': '↩️ Вернулись к списку чатов. Введите /chats',
'back_to_projects': '↩️ Вернулись к списку проектов. Введите /projects',
'back_at_top': '📍 Вы на верхнем уровне. Введите /projects',
'notify_on': '🔔 Уведомления включены.',
'notify_off': '🔕 Уведомления отключены.',
'notify_current': '🔔 Уведомления: <b>{status}</b>\n\n💡 /notify <code>on</code> или /notify <code>off</code>',
// Remote Access
'tn_btn_start': '▶ Включить',
'tn_btn_stop': '⏹ Выключить',
'tn_btn_status': '📊 Статус',
'tn_screen_active': '🟢 <b>Remote Access активен</b>\n\n🔗 {url}',
'tn_screen_inactive': '⚪ <b>Remote Access</b>\n\nНе запущен. Нажмите "Включить" чтобы открыть доступ к Studio через интернет.',
'tn_not_running': '⚪ Доступ не запущен.',
'tn_notify_started': '🟢 <b>Remote Access открыт</b>\n\n🔗 {url}',
'tn_notify_stopped': '⬛ Remote Access закрыт.',
'git_no_changes': '📊 Нет изменений или не git-репозиторий.',
'git_not_repo': '📊 Не git-репозиторий.',
'git_last_commits': '📜 <b>Последние {n} коммитов</b>',
'no_responses': '📭 Нет ответов в этом чате.',
'select_chat_first': '💡 Сначала выберите чат.',
'select_chat_hint': '💡 Сначала выберите чат: /chats → /chat <code><n></code>',
'cat_usage': '💡 Использование: /cat <code><файл></code>',
'msg_full_hint': '📎 /full — полный последний ответ',
'msg_compose_hint': '📝 Пишите сообщение — оно пойдёт в этот чат',
'attach_cleared': '🗑 Вложения очищены.',
// Project screen buttons
'btn_files': '📁 Файлы',
'btn_git_log': '📜 Git Log',
'btn_diff': '📊 Diff',
// Compose
'compose_prompt': '📝 Отправьте ваше сообщение:',
'compose_select_first_short': '❌ Сначала выберите сессию чата',
// File errors
'files_too_large': '❌ Файл слишком большой (макс. 10MB)',
'files_download_error': '❌ Невозможно скачать файл',
'files_download_failed': '❌ Загрузка не удалась',
'files_process_error': '❌ Не удалось обработать файл',
// Stop / New
'error_no_session': '❌ Нет выбранной активной сессии',
'stop_sent': '🛑 Сигнал остановки отправлен...',
'new_session_created': '✅ <b>Новая сессия создана</b> (#{id})\n\nОтправьте ваше сообщение:',
},
};
class TelegramBot extends EventEmitter {
/**
* @param {import('better-sqlite3').Database} db
* @param {object} opts
* @param {object} opts.log - Logger instance { info, warn, error, debug }
*/
constructor(db, opts = {}) {
super();
this.db = db;
this.log = opts.log || console;
this.token = null;
this.running = false;
this._pollTimer = null;
this._offset = 0;
this._acceptNewConnections = true;
this.lang = opts.lang || 'uk';
// In-memory state
this._pairingCodes = new Map(); // code → { createdAt, expiresAt }
this._failedAttempts = new Map(); // telegramUserId → { count, blockedUntil }
this._userContext = new Map(); // telegramUserId → { sessionId, projectWorkdir }
this._rateLimit = new Map(); // telegramUserId → { count, resetAt }
// DB setup
this._initDb();
this._prepareStmts();
}
// ─── i18n ─────────────────────────────────────────────────────────────────
_t(key, params = {}) {
const dict = BOT_I18N[this.lang] || BOT_I18N.uk;
let text = dict[key] || BOT_I18N.uk[key] || key;
for (const [k, v] of Object.entries(params)) {
text = text.replace(new RegExp(`\\{${k}\\}`, 'g'), String(v));
}
return text;
}
// ─── Database ──────────────────────────────────────────────────────────────
_initDb() {
this.db.exec(`
CREATE TABLE IF NOT EXISTS telegram_devices (
id INTEGER PRIMARY KEY AUTOINCREMENT,
telegram_user_id INTEGER NOT NULL UNIQUE,
telegram_chat_id INTEGER NOT NULL,
display_name TEXT,
username TEXT,
paired_at TEXT NOT NULL DEFAULT (datetime('now')),
last_active TEXT,
notifications_enabled INTEGER DEFAULT 1
);
`);
// Phase 2: session persistence columns
try { this.db.exec("ALTER TABLE telegram_devices ADD COLUMN last_session_id TEXT"); } catch(e) {}
try { this.db.exec("ALTER TABLE telegram_devices ADD COLUMN last_workdir TEXT"); } catch(e) {}
}
_prepareStmts() {
this._stmts = {
getDevice: this.db.prepare('SELECT * FROM telegram_devices WHERE telegram_user_id = ?'),
getAllDevices: this.db.prepare('SELECT * FROM telegram_devices ORDER BY paired_at DESC'),
addDevice: this.db.prepare('INSERT INTO telegram_devices (telegram_user_id, telegram_chat_id, display_name, username) VALUES (?, ?, ?, ?)'),
removeDevice: this.db.prepare('DELETE FROM telegram_devices WHERE id = ?'),
removeByUserId: this.db.prepare('DELETE FROM telegram_devices WHERE telegram_user_id = ?'),
updateLastActive: this.db.prepare('UPDATE telegram_devices SET last_active = datetime(\'now\') WHERE telegram_user_id = ?'),
getDeviceById: this.db.prepare('SELECT * FROM telegram_devices WHERE id = ?'),
updateNotifications: this.db.prepare('UPDATE telegram_devices SET notifications_enabled = ? WHERE telegram_user_id = ?'),
};
}
// ─── Lifecycle ─────────────────────────────────────────────────────────────
/**
* Start the bot with the given token.
* @param {string} botToken
*/
async start(botToken) {
if (this.running) return;
this.token = botToken;
if (!this.token) throw new Error('Bot token is required');
// Validate token and ensure clean polling state
try {
const me = await this._callApi('getMe');
this._botInfo = me;
// Delete any stale webhook — Telegram ignores getUpdates if webhook is set
await this._callApi('deleteWebhook', { drop_pending_updates: false });
this.log.info(`[telegram] Bot started: @${me.username} (${me.first_name})`);
} catch (err) {
this.log.error(`[telegram] Invalid bot token: ${err.message}`);
throw new Error(`Invalid bot token: ${err.message}`);
}
this.running = true;
this._poll();
// Periodic cleanup of in-memory Maps to prevent unbounded growth
this._cleanupInterval = setInterval(() => {
const now = Date.now();
for (const [k, v] of this._pairingCodes) if (now > v.expiresAt) this._pairingCodes.delete(k);
for (const [k, v] of this._failedAttempts) if (now > v.blockedUntil) this._failedAttempts.delete(k);
for (const [k, v] of this._rateLimit) if (now > v.resetAt) this._rateLimit.delete(k);
}, 10 * 60 * 1000); // every 10 minutes
return this._botInfo;
}
stop() {
this.running = false;
if (this._pollTimer) {
clearTimeout(this._pollTimer);
this._pollTimer = null;
}
if (this._cleanupInterval) {
clearInterval(this._cleanupInterval);
this._cleanupInterval = null;
}
this.log.info('[telegram] Bot stopped');
}
isRunning() { return this.running; }
getBotInfo() { return this._botInfo || null; }
// ─── Lock Mode ─────────────────────────────────────────────────────────────
get acceptNewConnections() { return this._acceptNewConnections; }
set acceptNewConnections(val) {
this._acceptNewConnections = !!val;
if (!val) {
// Clear all pending pairing codes when locking
this._pairingCodes.clear();
}
}
// ─── Polling ───────────────────────────────────────────────────────────────
async _poll() {
if (!this.running) return;
try {
const updates = await this._callApi('getUpdates', {
offset: this._offset,
timeout: POLL_TIMEOUT,
allowed_updates: JSON.stringify(['message', 'callback_query']),
});
if (updates && updates.length > 0) {
for (const update of updates) {
this._offset = update.update_id + 1;
try {
await this._handleUpdate(update);
} catch (err) {
this.log.error(`[telegram] Error handling update: ${err.message}`);
}
}
}
} catch (err) {
// Network errors — retry after delay
if (!err.message?.includes('Invalid bot token')) {
this.log.warn(`[telegram] Poll error (retrying in 5s): ${err.message}`);
this._pollTimer = setTimeout(() => this._poll(), 5000);
return;
}
this.log.error(`[telegram] Fatal poll error: ${err.message}`);
this.stop();
return;
}
// Schedule next poll immediately (long-polling handles the wait)
if (this.running) {
this._pollTimer = setTimeout(() => this._poll(), 100);
}
}
// ─── Telegram API ──────────────────────────────────────────────────────────
async _callApi(method, params = {}) {
const url = `${TELEGRAM_API}${this.token}/${method}`;
const body = {};
for (const [k, v] of Object.entries(params)) {
if (v !== undefined && v !== null) body[k] = v;
}
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal: AbortSignal.timeout(POLL_TIMEOUT * 1000 + 10000), // poll timeout + margin
});
const data = await res.json();
if (!data.ok) {
throw new Error(data.description || `Telegram API error: ${method}`);
}
return data.result;
}
async _sendMessage(chatId, text, options = {}) {
// Truncate long messages
let safeText = text;
if (safeText.length > MAX_MESSAGE_LENGTH) {
safeText = safeText.substring(0, MAX_MESSAGE_LENGTH) + '\n\n' + this._t('files_truncated_short');
}
const params = {
chat_id: chatId,
text: safeText,
parse_mode: 'HTML',
...options,
};
try {
return await this._callApi('sendMessage', params);
} catch (err) {
// Retry without parse_mode if HTML parsing fails
if (err.message?.includes("can't parse")) {
params.parse_mode = undefined;
return await this._callApi('sendMessage', params);
}
throw err;
}
}
async _editScreen(chatId, msgId, text, keyboard) {
if (!msgId) {
// No message to edit — send a new one
return this._showScreen(chatId, null, text, keyboard);
}
const params = {
chat_id: chatId,
message_id: msgId,
text: text.length > MAX_MESSAGE_LENGTH ? text.substring(0, MAX_MESSAGE_LENGTH) + '\n\n' + this._t('files_truncated_short') : text,
parse_mode: 'HTML',
};
if (keyboard) params.reply_markup = JSON.stringify({ inline_keyboard: keyboard });
try {
return await this._callApi('editMessageText', params);
} catch (err) {
if (err.message?.includes('message is not modified')) return null;
if (err.message?.includes("can't parse")) {
params.parse_mode = undefined;
try { return await this._callApi('editMessageText', params); } catch { /* fall through */ }
}
// Any edit failure — fall back to sending a new message
this.log.warn(`[telegram] editScreen fallback to new message: ${err.message}`);
return this._showScreen(chatId, null, text, keyboard);
}
}
async _showScreen(chatId, userId, text, keyboard) {
const params = {};
if (keyboard) params.reply_markup = JSON.stringify({ inline_keyboard: keyboard });
const sent = await this._sendMessage(chatId, text, params);
if (sent && userId !== null) {
const ctx = this._getContext(userId);
ctx.screenMsgId = sent.message_id;
ctx.screenChatId = chatId;
}
return sent;
}
async _answerCallback(callbackQueryId, text) {
try {
await this._callApi('answerCallbackQuery', { callback_query_id: callbackQueryId, text });
} catch {}
}
// ─── Pairing ───────────────────────────────────────────────────────────────
/**
* Generate a new 6-character pairing code.
* @returns {{ code: string, formattedCode: string, expiresAt: number } | { error: string }}
*/
generatePairingCode() {
if (!this._acceptNewConnections) {
return { error: 'New connections are disabled' };
}
if (!this.running) {
return { error: 'Bot is not running' };
}
// Clear expired codes
const now = Date.now();
for (const [code, data] of this._pairingCodes) {
if (now > data.expiresAt) this._pairingCodes.delete(code);
}
// Generate unique code
let code;
do {
code = crypto.randomBytes(4).toString('hex').substring(0, PAIRING_CODE_LENGTH).toUpperCase();
} while (this._pairingCodes.has(code));
const expiresAt = now + PAIRING_CODE_TTL;
this._pairingCodes.set(code, { createdAt: now, expiresAt });
// Format as "XXX·XXX"
const formattedCode = `${code.slice(0, 3)}·${code.slice(3)}`;
return { code, formattedCode, expiresAt };
}
/**
* Validate a pairing code submitted by a Telegram user.
* @returns {boolean}
*/
_validatePairingCode(code) {
const clean = code.replace(/[\s·\-\.]/g, '').toUpperCase();
const data = this._pairingCodes.get(clean);
if (!data) return false;
if (Date.now() > data.expiresAt) {
this._pairingCodes.delete(clean);
return false;
}
// One-time use
this._pairingCodes.delete(clean);
return true;
}
// ─── Rate Limiting ─────────────────────────────────────────────────────────
_checkRateLimit(userId) {
const now = Date.now();
const entry = this._rateLimit.get(userId);
if (!entry || now > entry.resetAt) {
this._rateLimit.set(userId, { count: 1, resetAt: now + RATE_LIMIT_WINDOW });
return true;
}
entry.count++;
return entry.count <= RATE_LIMIT_MAX;
}
_isBlocked(userId) {
const entry = this._failedAttempts.get(userId);
if (!entry) return false;
if (Date.now() > entry.blockedUntil) {
this._failedAttempts.delete(userId);
return false;
}
return entry.count >= MAX_FAILED_ATTEMPTS;
}