-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
7118 lines (6453 loc) · 323 KB
/
Copy pathmain.py
File metadata and controls
7118 lines (6453 loc) · 323 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
#!/usr/bin/env python3
"""
בוט שומר קבצי קוד - Code Keeper Bot
נקודת הכניסה הראשית לבוט
"""
from __future__ import annotations
# חשוב: gevent חייב לרוץ לפני ייבוא ספריות סטנדרטיות כדי ש-sockets ייסגרו נכון ב-shutdown.
from gevent import monkey as _gevent_monkey
import os as _os
def _should_patch_gevent() -> bool:
disable = str(_os.getenv("CODEBOT_DISABLE_GEVENT_PATCH", "")).strip().lower()
return disable not in {"1", "true", "yes"}
# חשוב: patch מוקדם כדי שסוקטים ייסגרו נכון; בבדיקות אפשר לכבות כדי למנוע התנגשויות.
if _should_patch_gevent():
_gevent_monkey.patch_all()
# הגדרות מתקדמות
import os
import functools
import inspect
import logging
import asyncio
import warnings
import json
import random
import threading
from pathlib import Path
from typing import Any, Optional, TypedDict
try:
from typing import NotRequired # type: ignore[attr-defined]
except ImportError: # pragma: no cover
try:
from typing_extensions import NotRequired # type: ignore[assignment]
except Exception: # pragma: no cover
class _NotRequiredShim:
def __class_getitem__(cls, item):
return item
NotRequired = _NotRequiredShim # type: ignore[misc,assignment]
from datetime import datetime
# הפחתת רעש בלוגים: DeprecationWarnings ספרייתיים (למשל httplib2/pyparsing)
# לא משפיע על התנהגות ריצה, רק על פלט אזהרות.
warnings.filterwarnings("ignore", category=DeprecationWarning, module=r"httplib2\.auth")
import signal
import socket
import sys
import time
from urllib.parse import urlparse
try:
import pymongo
_HAS_PYMONGO = True
except Exception:
pymongo = None # fallback ללא type: ignore
_HAS_PYMONGO = False
from datetime import datetime, timezone, timedelta
import atexit
try:
import pymongo.errors
from pymongo.errors import DuplicateKeyError
except Exception:
class _DummyErr(Exception):
pass
class _DummyErrors:
InvalidOperation = _DummyErr
OperationFailure = _DummyErr
DuplicateKeyError = _DummyErr
pymongo = type("_PM", (), {"errors": _DummyErrors})()
import os
from telegram import Update, ReplyKeyboardMarkup, InlineKeyboardButton, InlineKeyboardMarkup, BotCommand, BotCommandScopeChat
from telegram.constants import ParseMode
from telegram.ext import (Application, CommandHandler, ContextTypes,
MessageHandler, filters, Defaults, ConversationHandler, CallbackQueryHandler,
PicklePersistence, InlineQueryHandler, ApplicationHandlerStop, TypeHandler)
from config import config
try:
import observability as _observability
except Exception:
_observability = None
def _noop(*_a, **_k): # type: ignore[unused-argument]
return None
def _default_generate_request_id() -> str:
try:
return str(int(time.time() * 1000))[-8:]
except Exception:
return ""
def _observability_attr(name: str, default):
if _observability is None:
return default
try:
return getattr(_observability, name)
except AttributeError:
return default
setup_structlog_logging = _observability_attr("setup_structlog_logging", _noop)
init_sentry = _observability_attr("init_sentry", _noop)
get_log_level_from_env = _observability_attr(
"get_log_level_from_env",
lambda default="INFO": (str(os.getenv("LOG_LEVEL") or default)).strip().upper() or "INFO",
)
bind_request_id = _observability_attr("bind_request_id", _noop)
generate_request_id = _observability_attr("generate_request_id", _default_generate_request_id)
emit_event = _observability_attr("emit_event", _noop)
bind_user_context = _observability_attr("bind_user_context", _noop)
bind_command = _observability_attr("bind_command", _noop)
get_observability_context = _observability_attr("get_observability_context", lambda: {})
from metrics import (
telegram_updates_total,
track_file_saved,
track_search_performed,
track_performance,
errors_total,
record_request_outcome,
)
from rate_limiter import RateLimiter
try:
# Optional advanced limits backend (limits + Redis)
from limits import RateLimitItemPerMinute
from limits.storage import RedisStorage, MemoryStorage
from limits.strategies import MovingWindowRateLimiter
_LIMITS_AVAILABLE = True
except Exception:
RateLimitItemPerMinute = None # type: ignore[assignment]
RedisStorage = None # type: ignore[assignment]
MemoryStorage = None # type: ignore[assignment]
MovingWindowRateLimiter = None # type: ignore[assignment]
_LIMITS_AVAILABLE = False
from database import CodeSnippet, DatabaseManager, db
from services import code_service as code_processor
from bot_handlers import AdvancedBotHandlers # still used by legacy code
from bot_handlers import set_activity_reporter as set_bh_activity_reporter
from conversation_handlers import MAIN_KEYBOARD, get_save_conversation_handler
from conversation_handlers import set_activity_reporter as set_ch_activity_reporter
# ייבוא דחוי של ה-activity_reporter בתוך ה-run-time בלבד כדי למנוע יצירת חיבורים בזמן import
from github_menu_handler import GitHubMenuHandler
from backup_menu_handler import BackupMenuHandler
from skill_menu_handler import SkillMenuHandler
from handlers.drive.menu import GoogleDriveMenuHandler
from handlers.drive.utils import extract_schedule_key as drive_extract_schedule_key
def get_drive_handler_from_application(application: Application) -> tuple[Any, bool]:
"""
החזר את מופע GoogleDriveMenuHandler מתוך application.
Returns (handler, restored_flag). restored_flag מציין אם נאלצנו לשחזר את
ההפניה דרך המאפיין `_drive_handler` לאחר ש-bot_data איבד את המפתח.
"""
handler = None
restored = False
try:
bot_data = getattr(application, "bot_data", None)
except Exception:
bot_data = None
if isinstance(bot_data, dict):
handler = bot_data.get("drive_handler")
if handler:
return handler, restored
fallback = getattr(application, "_drive_handler", None)
if fallback:
if isinstance(bot_data, dict):
try:
bot_data["drive_handler"] = fallback
except Exception:
pass
handler = fallback
restored = True
return handler, restored
from handlers.documents import DocumentHandler
from file_manager import backup_manager
from large_files_handler import large_files_handler
from user_stats import user_stats
from cache_commands import setup_cache_handlers # enabled
# from enhanced_commands import setup_enhanced_handlers # disabled
from batch_commands import setup_batch_handlers
from html import escape as html_escape
try:
from aiohttp import web # for internal web server
except Exception:
class _DummyWeb:
class Application:
def __init__(self, *a, **k): pass
class AppRunner:
def __init__(self, *a, **k): pass
async def setup(self): pass
class TCPSite:
def __init__(self, *a, **k): pass
async def start(self): pass
async def json_response(*a, **k):
return None
web = _DummyWeb()
# (Lock mechanism constants removed)
# הגדרת לוגים בסיסית + structlog + Sentry
_LOG_LEVEL_NAME = get_log_level_from_env("INFO")
try:
_LOG_LEVEL = int(_LOG_LEVEL_NAME) if str(_LOG_LEVEL_NAME).isdigit() else getattr(logging, str(_LOG_LEVEL_NAME).upper(), logging.INFO)
except Exception:
_LOG_LEVEL_NAME = "INFO"
_LOG_LEVEL = logging.INFO
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=_LOG_LEVEL,
handlers=[logging.StreamHandler(sys.stdout)],
)
try:
from utils import install_sensitive_filter
install_sensitive_filter()
except Exception:
pass
try:
setup_structlog_logging(_LOG_LEVEL_NAME)
init_sentry()
except Exception:
# אל תכשיל את האפליקציה אם תצורת observability נכשלה
pass
# OpenTelemetry (best-effort, fail-open)
try:
from observability_otel import setup_telemetry as _setup_otel # type: ignore
_setup_otel(
service_name=str(os.getenv("OTEL_SERVICE_NAME") or "codebot-bot"),
service_version=os.getenv("SERVICE_VERSION") or os.getenv("RENDER_GIT_COMMIT") or None,
environment=os.getenv("ENVIRONMENT") or os.getenv("ENV") or None,
flask_app=None,
)
except Exception:
pass
# סגירת סשן aiohttp משותף בסיום התהליך (best-effort)
@atexit.register
def _shutdown_http_shared_session() -> None:
try:
from http_async import close_session # type: ignore
except Exception:
return
loop: asyncio.AbstractEventLoop | None = None
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = None
if loop is not None and not loop.is_closed():
try:
running = bool(loop.is_running())
except Exception:
running = False
if not running:
try:
coro = close_session()
except Exception:
coro = None
if coro is not None:
try:
loop.run_until_complete(coro)
except Exception:
try:
coro.close() # type: ignore[attr-defined]
except Exception:
pass
else:
return
# אם הלולאה פעילה אי אפשר להמתין לה כאן – נשתמש בלולאה זמנית
try:
tmp_loop = asyncio.new_event_loop()
original_loop: asyncio.AbstractEventLoop | None = None
try:
try:
original_loop = asyncio.get_event_loop()
except RuntimeError:
original_loop = None
try:
asyncio.set_event_loop(tmp_loop)
except Exception:
pass
try:
coro = close_session()
except Exception:
coro = None
if coro is not None:
try:
tmp_loop.run_until_complete(coro)
except Exception:
try:
coro.close() # type: ignore[attr-defined]
except Exception:
pass
finally:
tmp_loop.close()
try:
if original_loop is None or (original_loop.is_closed() if original_loop else True):
asyncio.set_event_loop(None)
else:
asyncio.set_event_loop(original_loop)
except Exception:
pass
except Exception:
# אל תהרוס כיבוי
pass
# Optional: Initialize OpenTelemetry for the bot process as well (no Flask app here)
try:
from observability_otel import setup_telemetry as _setup_otel
_setup_otel(
service_name="code-keeper-bot",
service_version=os.getenv("APP_VERSION", ""),
environment=os.getenv("ENVIRONMENT", os.getenv("ENV", "production")),
flask_app=None,
)
except Exception:
pass
logger = logging.getLogger(__name__)
def _command_label_from_handler(handler) -> str:
"""הפקת שם פקודה ידידותי למדדים מתוך CommandHandler."""
try:
commands = list(getattr(handler, "commands", []) or [])
except Exception:
commands = []
if commands:
name = sorted(str(cmd).lstrip('/') for cmd in commands if cmd)[:1]
if name:
return f"/{name[0]}"
try:
base = getattr(handler.callback, "__name__", "")
except Exception:
base = ""
base = (base or "command").lstrip('_')
return f"/{base}" if not base.startswith('/') else base
def _wrap_command_callback(callback, command_label: str):
if getattr(callback, "_metrics_wrapped", False):
return callback
if inspect.iscoroutinefunction(callback):
async def _wrapped(update, context, *args, __orig=callback):
start = time.perf_counter()
status_code = 200
status_label: str | None = None
try:
return await __orig(update, context, *args)
except ApplicationHandlerStop:
status_code = 499
status_label = "cancelled"
raise
except Exception:
status_code = 500
status_label = "error"
raise
finally:
try:
record_request_outcome(
status_code,
max(0.0, time.perf_counter() - start),
source="telegram",
command=command_label,
cache_hit=None,
status_label=status_label,
)
except Exception:
pass
_wrapped._metrics_wrapped = True # type: ignore[attr-defined]
try:
_wrapped.__name__ = getattr(callback, "__name__", "wrapped_command")
except Exception:
pass
return _wrapped
def _wrapped_sync(update, context, *args, __orig=callback):
start = time.perf_counter()
status_code = 200
status_label: str | None = None
try:
return __orig(update, context, *args)
except ApplicationHandlerStop:
status_code = 499
status_label = "cancelled"
raise
except Exception:
status_code = 500
status_label = "error"
raise
finally:
try:
record_request_outcome(
status_code,
max(0.0, time.perf_counter() - start),
source="telegram",
command=command_label,
cache_hit=None,
status_label=status_label,
)
except Exception:
pass
_wrapped_sync._metrics_wrapped = True # type: ignore[attr-defined]
return _wrapped_sync
def _instrument_command_handlers(application) -> None:
from telegram.ext import CommandHandler as _CommandHandler # local import to avoid cycles
try:
raw_handlers = getattr(application, "handlers", None)
except Exception:
return
handlers: list[Any] = []
if isinstance(raw_handlers, dict):
for group in raw_handlers.values():
try:
handlers.extend(list(group or []))
except TypeError:
continue
elif raw_handlers:
try:
handlers = list(raw_handlers)
except TypeError:
handlers = [raw_handlers]
for handler in handlers:
if not isinstance(handler, _CommandHandler):
continue
try:
callback = handler.callback
except Exception:
continue
if getattr(callback, "_metrics_wrapped", False):
continue
label = _command_label_from_handler(handler)
wrapped = _wrap_command_callback(callback, label)
try:
handler.callback = wrapped
except Exception:
pass
def _wrap_github_callback(callback):
if getattr(callback, "_metrics_wrapped", False):
return callback
async def _wrapped(update, context, *args, __orig=callback):
query = getattr(update, "callback_query", None)
raw = str(getattr(query, "data", "") or "")
action = (raw.split(":", 1)[0] or "unknown").strip() or "unknown"
start = time.perf_counter()
status_code = 200
status_label: str | None = None
try:
return await __orig(update, context, *args)
except ApplicationHandlerStop:
status_code = 499
status_label = "cancelled"
raise
except Exception:
status_code = 500
status_label = "error"
raise
finally:
try:
record_request_outcome(
status_code,
max(0.0, time.perf_counter() - start),
source="telegram",
handler=f"github:{action}",
cache_hit=None,
status_label=status_label,
)
except Exception:
pass
_wrapped._metrics_wrapped = True # type: ignore[attr-defined]
try:
_wrapped.__name__ = getattr(callback, "__name__", "github_callback")
except Exception:
pass
return _wrapped
def _wrap_handler_callback(callback, handler_label: str):
if getattr(callback, "_metrics_wrapped", False):
return callback
if inspect.iscoroutinefunction(callback):
async def _wrapped(update, context, *args, __orig=callback):
start = time.perf_counter()
status_code = 200
status_label: str | None = None
try:
return await __orig(update, context, *args)
except ApplicationHandlerStop:
status_code = 499
status_label = "cancelled"
raise
except Exception:
status_code = 500
status_label = "error"
raise
finally:
try:
record_request_outcome(
status_code,
max(0.0, time.perf_counter() - start),
source="telegram",
handler=handler_label,
cache_hit=None,
status_label=status_label,
)
except Exception:
pass
_wrapped._metrics_wrapped = True # type: ignore[attr-defined]
return _wrapped
def _wrapped_sync(update, context, *args, __orig=callback):
start = time.perf_counter()
status_code = 200
status_label: str | None = None
try:
return __orig(update, context, *args)
except ApplicationHandlerStop:
status_code = 499
status_label = "cancelled"
raise
except Exception:
status_code = 500
status_label = "error"
raise
finally:
try:
record_request_outcome(
status_code,
max(0.0, time.perf_counter() - start),
source="telegram",
handler=handler_label,
cache_hit=None,
status_label=status_label,
)
except Exception:
pass
_wrapped_sync._metrics_wrapped = True # type:ignore[attr-defined]
return _wrapped_sync
async def _cancel_command_fallback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
"""Handler אסינכרוני אחיד לסיום שיחה כאשר המשתמש מפעיל /cancel."""
return ConversationHandler.END
def _redis_socket_available(redis_url: str, timeout: float = 0.25) -> bool:
"""
בדיקת reachability בסיסית ל-Redis כדי להימנע מהמתנה ארוכה בזמן טסטים/CI.
אם לא ניתן להגיע ל-Redis במהירות, נחזור False ונשתמש בפולבק.
"""
if not redis_url:
return False
try:
parsed = urlparse(str(redis_url))
except Exception:
return False
scheme = (parsed.scheme or "").lower()
default_ports = {
"redis": 6379,
"rediss": 6379,
"redis+sentinel": 26379,
}
default_port = default_ports.get(scheme)
if default_port is None:
return False
host = parsed.hostname
try:
port = parsed.port
except ValueError:
port = None
if host is None:
netloc = parsed.netloc
if not netloc:
return False
if "@" in netloc:
netloc = netloc.split("@", 1)[1]
first_endpoint = netloc.split(",", 1)[0]
first_endpoint = first_endpoint.strip()
if not first_endpoint:
return False
if first_endpoint.startswith("[") and "]" in first_endpoint:
end_idx = first_endpoint.find("]")
host = first_endpoint[1:end_idx]
remainder = first_endpoint[end_idx + 1:]
if remainder.startswith(":"):
try:
port = int(remainder[1:])
except ValueError:
port = None
else:
if ":" in first_endpoint:
host_part, port_part = first_endpoint.rsplit(":", 1)
host = host_part
try:
port = int(port_part)
except ValueError:
port = None
else:
host = first_endpoint
if not host:
return False
port = port or default_port
if not port:
return False
try:
sock = socket.create_connection((host, int(port)), timeout=timeout)
except Exception:
return False
try:
sock.close()
except Exception:
pass
return True
# הבטחת לולאת asyncio כברירת מחדל (תמיכה ב-Python 3.11 בסביבת טסטים)
# מתקין Policy חסין שמייצר לולאה חדשה אם אין אחת זמינה, גם אם asyncio.run() ניקה את הלולאה.
try:
class _ResilientEventLoopPolicy(asyncio.DefaultEventLoopPolicy):
def get_event_loop(self): # type: ignore[override]
try:
return super().get_event_loop()
except RuntimeError:
loop = self.new_event_loop()
self.set_event_loop(loop)
return loop
# התקנה חד-פעמית של ה-Policy. אם כבר הותקן Policy חיצוני (כגון uvloop) לא ננסה להחליף בכוח.
try:
current_policy = asyncio.get_event_loop_policy()
# נתקין רק אם זו ה-DefaultPolicy כדי לא לשבור קונפיג קיים
if isinstance(current_policy, asyncio.DefaultEventLoopPolicy):
asyncio.set_event_loop_policy(_ResilientEventLoopPolicy())
except Exception:
# במידה והקריאה get_event_loop_policy עצמה נכשלת, ננסה להתקין ישירות
try:
asyncio.set_event_loop_policy(_ResilientEventLoopPolicy())
except Exception:
pass
# fail-safe: נסה לוודא שיש לולאה נוכחית גם כעת
try:
asyncio.get_event_loop()
except RuntimeError:
try:
_loop = asyncio.new_event_loop()
asyncio.set_event_loop(_loop)
except Exception:
# Fail-open: אין להפיל בזמן import
pass
except Exception:
# לא נכשיל את ה-import אם יש בעיה במדיניות הלולאה
pass
# רשימת קידודים לניסיון קריאת קבצים (ניתנת לדריסה בטסטים)
ENCODINGS_TO_TRY = [
'utf-8',
'windows-1255',
'iso-8859-8',
'cp1255',
'utf-16',
'latin-1',
]
def _register_catch_all_callback(application, callback_fn) -> None:
"""רישום CallbackQueryHandler כללי בקבוצה מאוחרת, עם fallback כשה-API לא תומך ב-group.
נועד להימנע מכשלי טסטים/סטאבים (TypeError על group), ובו בזמן לשמר קדימויות בפרודקשן.
"""
handler = CallbackQueryHandler(callback_fn)
try:
application.add_handler(handler, group=5)
except TypeError:
# סביבת טסט/סטאב ללא תמיכה בפרמטר group
application.add_handler(handler)
except Exception as e:
# דווח חריגה כדי שלא נבלע שגיאות רישום שקטות
logger.error(f"Failed to register catch-all CallbackQueryHandler: {e}")
# הודעת התחלה מרשימה
logger.info("🚀 מפעיל בוט קוד מתקדם - גרסה פרו!")
try:
emit_event("bot_start", msg_he="מפעיל את הבוט", severity="info")
except Exception:
pass
# הפחתת רעש בלוגים
logging.getLogger("httpx").setLevel(logging.ERROR) # רק שגיאות קריטיות
logging.getLogger("telegram.ext.Updater").setLevel(logging.ERROR)
logging.getLogger("telegram.ext.Application").setLevel(logging.WARNING)
# Reporter יווצר ויוזרק בזמן ריצה לאחר בניית האפליקציה והקונפיג
reporter = None
# ===== עזר: שליחת הודעת אדמין =====
def get_admin_ids() -> list[int]:
try:
raw = os.getenv('ADMIN_USER_IDS')
if not raw:
return []
return [int(x.strip()) for x in raw.split(',') if x.strip().isdigit()]
except Exception:
return []
async def notify_admins(context: ContextTypes.DEFAULT_TYPE, text: str) -> bool:
try:
# Alert Pipeline Consolidation:
# לא שולחים הודעות "אדמין" ישירות דרך bot.send_message (זה עוקף suppress/Rule Engine).
# במקום זה, מפיקים internal_alert ומאפשרים למנוע הכללים להחליט אם/לאן לשלוח.
try:
from internal_alerts import emit_internal_alert # type: ignore
except Exception:
emit_internal_alert = None # type: ignore
if emit_internal_alert is None:
return False
# שומרים את הטקסט בתור summary; פרטים נוספים (כמו רשימת אדמינים) רק להקשר.
# NOTE: לא מעבירים token/chat_id וכד' כדי לא להדליף מידע רגיש.
admin_ids = get_admin_ids()
emit_internal_alert(
"admin_notification",
severity="info",
summary=str(text or ""),
source="main.notify_admins",
admin_ids=admin_ids,
)
return True
except Exception:
return False
async def _send_direct_admins(context: ContextTypes.DEFAULT_TYPE, text: str) -> bool:
"""Fallback לשליחת הודעה ישירה לאדמינים בטלגרם."""
try:
admin_ids = get_admin_ids()
if not admin_ids:
return False
bot = getattr(context, "bot", None)
if bot is None:
return False
sent_any = False
for admin_id in admin_ids:
try:
await bot.send_message(chat_id=admin_id, text=str(text or ""))
sent_any = True
except Exception:
continue
return sent_any
except Exception:
return False
async def connect_claude_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""מנפיק טוקן אישי (PAT) לחיבור הקבצים של המשתמש ל‑Claude דרך MCP (קריאה בלבד)."""
try:
message = update.message or update.effective_message
if message is None:
return
# אבטחה: הטוקן סודי — מנפיקים רק בצ'אט פרטי כדי שלא ידלוף בקבוצה.
chat = update.effective_chat
if getattr(chat, "type", "private") != "private":
await message.reply_text("🔒 הפקודה זמינה בצ'אט פרטי בלבד (הטוקן סודי).")
return
user = update.effective_user
user_id = getattr(user, "id", None)
if not user_id:
await message.reply_text("לא זוהה משתמש.")
return
# /connect_claude write מנפיק טוקן עם הרשאת כתיבה; בלי ארגומנט — קריאה בלבד.
want_write = any(str(a).strip().lower() == "write" for a in (context.args or []))
scopes = ("read", "write") if want_write else ("read",)
label = "Claude (write)" if want_write else "Claude"
raw = None
try:
from src.infrastructure.composition.webapp_container import get_files_facade
raw = get_files_facade().issue_mcp_token(int(user_id), label=label, scopes=scopes)
except Exception:
logger.error("connect_claude: token issue failed", exc_info=True)
raw = None
if not raw:
await message.reply_text("אירעה שגיאה ביצירת הטוקן. נסו שוב מאוחר יותר.")
return
base = (os.getenv("MCP_SERVER_URL") or "https://YOUR-MCP-HOST").rstrip("/")
add_cmd = (
f'claude mcp add --transport http codekeeper {base}/mcp '
f'--header "Authorization: Bearer {raw}"'
)
if want_write:
access_line = (
"⚠️ אל תשתפו את הטוקן — הוא נותן גישת <b>קריאה וכתיבה</b> "
"(יצירה/עדכון קבצים) למאגר שלכם."
)
else:
access_line = (
"⚠️ אל תשתפו את הטוקן — הוא נותן גישת <b>קריאה בלבד</b> לקבצים שלכם.\n"
"✍️ לטוקן עם הרשאת כתיבה (יצירה/עדכון) שלחו <code>/connect_claude write</code>."
)
text = (
"🔌 <b>חיבור הקבצים שלך ל‑Claude (MCP)</b>\n\n"
"הטוקן האישי שלך (יוצג פעם אחת בלבד — שמור אותו):\n"
f"<code>{raw}</code>\n\n"
"לחיבור מ‑Claude Code / Desktop (העתק‑הדבק):\n"
f"<code>{add_cmd}</code>\n\n"
"💡 ל‑Claude.ai <b>אין צורך בטוקן</b>: ב‑Settings → Connectors → "
"Add custom connector הזינו את הכתובת\n"
f"<code>{base}/mcp</code>\n"
"וההתחברות תתבצע אוטומטית (דרך התחברות טלגרם).\n\n"
f"{access_line}"
)
try:
await message.reply_text(text, parse_mode=ParseMode.HTML)
except Exception:
# נפילת פרסום HTML לא תגרום לאובדן הטוקן — שולחים גרסת טקסט.
plain = (
text.replace("<b>", "")
.replace("</b>", "")
.replace("<code>", "")
.replace("</code>", "")
)
await message.reply_text(plain)
except Exception:
logger.error("connect_claude_command failed", exc_info=True)
try:
if update and update.message:
await update.message.reply_text("אירעה שגיאה. נסו שוב מאוחר יותר.")
except Exception:
pass
async def admin_report_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""קבלת דיווח משתמש ושליחה לאדמינים."""
try:
message = update.message or update.effective_message
if message is None:
return
args_text = ""
try:
args_text = " ".join(getattr(context, "args", None) or []).strip()
except Exception:
args_text = ""
if not args_text:
await message.reply_text(
"כדי לדווח לאדמין, כתבו: /admin <תיאור הבעיה>\n"
"דוגמה: /admin קיבלתי 500 בדפדפן הריפו"
)
return
user = update.effective_user
user_id = getattr(user, "id", None)
username = getattr(user, "username", None)
full_name = getattr(user, "full_name", None)
display = f"@{username}" if username else (full_name or "unknown")
report = (
"📣 דיווח משתמש\n"
f"• משתמש: {display}\n"
f"• user_id: {user_id}\n"
f"• הודעה: {args_text}"
)
sent = await notify_admins(context, report)
if not sent:
sent = await _send_direct_admins(context, report)
if sent:
await message.reply_text("תודה! הדיווח נשלח לאדמין.")
else:
await message.reply_text("לא הצלחתי לשלוח את הדיווח כרגע.")
except Exception:
try:
if update and update.message:
await update.message.reply_text("לא הצלחתי לשלוח את הדיווח כרגע.")
except Exception:
pass
# ===== Admin: /recycle_backfill =====
async def recycle_backfill_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""ממלא deleted_at ו-deleted_expires_at לרשומות מחוקות רכות וחושב TTL.
שימוש: /recycle_backfill [X]
X = ימים לתוקף סל (ברירת מחדל מהקונפיג RECYCLE_TTL_DAYS)
הפקודה זמינה למנהלים בלבד.
"""
try:
user_id = update.effective_user.id if update and update.effective_user else 0
admin_ids = get_admin_ids()
if not admin_ids or user_id not in admin_ids:
try:
await update.message.reply_text("❌ פקודה זמינה למנהלים בלבד")
except Exception:
pass
return
# קביעת TTL בימים
try:
ttl_days = int(context.args[0]) if context.args else int(getattr(config, 'RECYCLE_TTL_DAYS', 7) or 7)
except Exception:
ttl_days = int(getattr(config, 'RECYCLE_TTL_DAYS', 7) or 7)
ttl_days = max(1, ttl_days)
now = datetime.now(timezone.utc)
expires = now + timedelta(days=ttl_days)
# ודא אינדקסי TTL ואח"כ Backfill בשתי הקולקציות
from database import db as _db
results = []
for coll_name, friendly in (("collection", "קבצים רגילים"), ("large_files_collection", "קבצים גדולים")):
coll = getattr(_db, coll_name, None)
# חשוב: אל תשתמשו ב-truthiness על קולקציה של PyMongo
if coll is None:
results.append((friendly, 0, 0, "collection-missing"))
continue
# ensure TTL index idempotently
try:
coll.create_index("deleted_expires_at", expireAfterSeconds=0, name="deleted_ttl")
except Exception:
# לא קריטי; נמשיך
pass
modified_deleted_at = 0
modified_deleted_exp = 0
# backfill deleted_at where missing
try:
if hasattr(coll, 'update_many'):
r1 = coll.update_many({"is_active": False, "deleted_at": {"$exists": False}}, {"$set": {"deleted_at": now}})
modified_deleted_at = int(getattr(r1, 'modified_count', 0) or 0)
except Exception:
pass
# backfill deleted_expires_at where missing
try:
if hasattr(coll, 'update_many'):
r2 = coll.update_many({"is_active": False, "deleted_expires_at": {"$exists": False}}, {"$set": {"deleted_expires_at": expires}})
modified_deleted_exp = int(getattr(r2, 'modified_count', 0) or 0)
except Exception:
pass
results.append((friendly, modified_deleted_at, modified_deleted_exp, ""))
# דו"ח
lines = [
f"🧹 Backfill סל מיחזור (TTL={ttl_days} ימים)",
]
for friendly, c_at, c_exp, err in results:
if err:
lines.append(f"• {friendly}: דילוג ({err})")
else:
lines.append(f"• {friendly}: deleted_at={c_at}, deleted_expires_at={c_exp}")
try:
await update.message.reply_text("\n".join(lines))
except Exception:
pass
except Exception as e:
try:
await update.message.reply_text(f"❌ שגיאה ב-backfill: {html_escape(str(e))}")
except Exception:
pass
async def log_user_activity(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""
רישום פעילות משתמש במערכת.
Args:
update: אובייקט Update מטלגרם
context: הקונטקסט של השיחה