-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbot_handlers.py
More file actions
5794 lines (5340 loc) · 276 KB
/
Copy pathbot_handlers.py
File metadata and controls
5794 lines (5340 loc) · 276 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
"""
פקודות מתקדמות לבוט שומר קבצי קוד
Advanced Bot Handlers for Code Keeper Bot
"""
import asyncio
import hashlib
import os
import io
import logging
import re
import html
import secrets
import telegram.error
import sys
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Tuple
from telegram import (InlineKeyboardButton, InlineKeyboardMarkup, InputFile,
Update, ReplyKeyboardMarkup)
from telegram.constants import ParseMode
from telegram.ext import (
CallbackQueryHandler,
CommandHandler,
ContextTypes,
MessageHandler,
filters,
)
from telegram.ext import ApplicationHandlerStop
from services import code_service as code_processor
from utils import TelegramUtils, TextUtils # עריכות בטוחות + אסקייפ ל-Markdown
try:
from services.image_generator import CodeImageGenerator
except Exception: # pragma: no cover
CodeImageGenerator = None # type: ignore
from rate_limiter import RateLimiter
from config import config
from conversation_handlers import MAIN_KEYBOARD
from pathlib import Path
try:
import yaml # type: ignore
except Exception: # pragma: no cover
yaml = None # type: ignore
# Reporter מוזרק בזמן ריצה כדי למנוע יצירה בזמן import
class _NoopReporter:
def report_activity(self, user_id):
return None
reporter = _NoopReporter()
def set_activity_reporter(new_reporter):
global reporter
reporter = new_reporter or _NoopReporter()
# ---- DB access via composition facade --------------------------------------
def _get_files_facade_or_none():
"""Best-effort access to FilesFacade without breaking older tests."""
try:
from src.infrastructure.composition import get_files_facade # type: ignore
return get_files_facade()
except Exception:
return None
def _call_files_api(method_name: str, *args, **kwargs):
"""
Invoke FilesFacade method by name (no legacy DB fallback).
"""
facade = _get_files_facade_or_none()
if facade is None:
return None
method = getattr(facade, method_name, None)
if not callable(method):
return None
try:
return method(*args, **kwargs)
except Exception:
return None
# Rate limiter לפיצ'ר יצירת תמונות (10 פעולות בדקה למשתמש)
image_rate_limiter = RateLimiter(max_per_minute=10)
# טעינת קונפיגורציית תמונות (אופציונלי)
def _load_image_config() -> dict:
try:
cfg_path = Path(__file__).parent / 'config' / 'image_settings.yaml'
if yaml is None or not cfg_path.exists():
return {}
data = yaml.safe_load(cfg_path.read_text(encoding='utf-8')) or {}
return dict(data.get('image_generation') or {})
except Exception:
return {}
IMAGE_CONFIG = _load_image_config()
import json
try:
import aiohttp # for GitHub rate limit check
except Exception: # pragma: no cover
aiohttp = None # type: ignore
# ChatOps helpers: sensitive command throttling and permissions integration
try:
from chatops.ratelimit import limit_sensitive # type: ignore
except Exception: # pragma: no cover
def limit_sensitive(_name: str): # type: ignore
def _decorator(fn):
return fn
return _decorator
# ChatOps – time range parsing (best-effort)
try:
from chatops.time_range import parse_time_range, TimeRangeParseError # type: ignore
except Exception: # pragma: no cover
parse_time_range = None # type: ignore
TimeRangeParseError = ValueError # type: ignore
try:
from chatops.permissions import (
admin_required,
chat_allowlist_required,
is_admin as _perm_is_admin,
) # type: ignore
except Exception: # pragma: no cover
_perm_is_admin = None # type: ignore
def admin_required(fn): # type: ignore
return fn
def chat_allowlist_required(fn): # type: ignore
return fn
logger = logging.getLogger(__name__)
import os as _os
class AdvancedBotHandlers:
"""פקודות מתקדמות של הבוט"""
def __init__(self, application):
self.application = application
self.setup_advanced_handlers()
def setup_advanced_handlers(self):
"""הגדרת handlers מתקדמים"""
# פקודות ניהול קבצים
self.application.add_handler(CommandHandler("show", self.show_command))
self.application.add_handler(CommandHandler("edit", self.edit_command))
self.application.add_handler(CommandHandler("delete", self.delete_command))
# self.application.add_handler(CommandHandler("rename", self.rename_command))
# self.application.add_handler(CommandHandler("copy", self.copy_command))
# מועדפים
self.application.add_handler(CommandHandler("favorite", self.favorite_command))
self.application.add_handler(CommandHandler("fav", self.favorite_command)) # קיצור דרך
self.application.add_handler(CommandHandler("favorites", self.favorites_command))
# פקודות גרסאות
self.application.add_handler(CommandHandler("versions", self.versions_command))
# self.application.add_handler(CommandHandler("restore", self.restore_command))
# self.application.add_handler(CommandHandler("diff", self.diff_command))
# פקודות שיתוף
self.application.add_handler(CommandHandler("share", self.share_command))
self.application.add_handler(CommandHandler("share_help", self.share_help_command))
# self.application.add_handler(CommandHandler("export", self.export_command))
self.application.add_handler(CommandHandler("download", self.download_command))
# יצירת תמונות מקוד – רישום עמיד: כל פקודה נרשמת בנפרד
for _cmd, _fn in (
("image", self.image_command),
("preview", self.preview_command),
("image_all", self.image_all_command),
):
try:
self.application.add_handler(CommandHandler(_cmd, _fn))
except Exception as e:
# אל תעצור רישום פקודות אחרות; דווח והמשך
try:
logger.error(f"Failed to register /{_cmd}: {e}")
except Exception:
pass
# פקודות ניתוח
self.application.add_handler(CommandHandler("analyze", self.analyze_command))
self.application.add_handler(CommandHandler("validate", self.validate_command))
# self.application.add_handler(CommandHandler("minify", self.minify_command))
# פקודות ארגון
self.application.add_handler(CommandHandler("tags", self.tags_command))
# self.application.add_handler(CommandHandler("languages", self.languages_command))
self.application.add_handler(CommandHandler("recent", self.recent_command))
self.application.add_handler(CommandHandler("info", self.info_command))
self.application.add_handler(CommandHandler("broadcast", self.broadcast_command))
# פקודת DM למנהלים – שליחת הודעה פרטית עם שימור רווחים (HTML <pre>)
self.application.add_handler(CommandHandler("dm", self.dm_command))
# חיפוש
self.application.add_handler(CommandHandler("search", self.search_command))
# ChatOps MVP + Stage 2 commands
self.application.add_handler(CommandHandler(
"status",
chat_allowlist_required(admin_required(self.status_command))
))
# Alias for detailed health check via chat (same as /status for now)
self.application.add_handler(CommandHandler(
"health",
chat_allowlist_required(admin_required(self.status_command))
))
self.application.add_handler(CommandHandler(
"observe",
chat_allowlist_required(admin_required(self.observe_command))
))
self.application.add_handler(CommandHandler(
"triage",
chat_allowlist_required(admin_required(limit_sensitive("triage")(self.triage_command)))
))
# מערכת: מידע ומדדים
self.application.add_handler(CommandHandler(
"system_info",
chat_allowlist_required(admin_required(self.system_info_command))
))
self.application.add_handler(CommandHandler(
"metrics",
chat_allowlist_required(admin_required(self.metrics_command))
))
# Observability v6 – Predictive Health
self.application.add_handler(CommandHandler("predict", self.predict_command))
# Observability v7 – Prediction accuracy
self.application.add_handler(CommandHandler("accuracy", self.accuracy_command))
# פקודת מנהל להצגת קישור ל-Sentry
self.application.add_handler(CommandHandler(
"sen",
chat_allowlist_required(admin_required(self.sentry_command))
))
self.application.add_handler(CommandHandler(
"errors",
chat_allowlist_required(admin_required(limit_sensitive("errors")(self.errors_command)))
))
self.application.add_handler(CommandHandler(
"rate_limit",
chat_allowlist_required(admin_required(limit_sensitive("rate_limit")(self.rate_limit_command)))
))
self.application.add_handler(CommandHandler(
"cache_clear_stale",
chat_allowlist_required(admin_required(limit_sensitive("cache_clear_stale")(self.cache_clear_stale_command)))
))
self.application.add_handler(CommandHandler(
"status_worker",
chat_allowlist_required(admin_required(limit_sensitive("status_worker")(self.status_worker_command)))
))
self.application.add_handler(CommandHandler(
"version_history",
chat_allowlist_required(admin_required(self.version_history_command))
))
# GitHub Backoff controls (admins)
self.application.add_handler(CommandHandler(
"enable_backoff",
chat_allowlist_required(admin_required(limit_sensitive("enable_backoff")(self.enable_backoff_command)))
))
self.application.add_handler(CommandHandler(
"disable_backoff",
chat_allowlist_required(admin_required(limit_sensitive("disable_backoff")(self.disable_backoff_command)))
))
self.application.add_handler(CommandHandler(
"uptime",
chat_allowlist_required(admin_required(self.uptime_command))
))
self.application.add_handler(CommandHandler(
"alerts",
chat_allowlist_required(admin_required(self.alerts_command))
))
# Observability v5 – incident memory
self.application.add_handler(CommandHandler(
"incidents",
chat_allowlist_required(admin_required(self.incidents_command))
))
# ChatOps – Silences management
self.application.add_handler(CommandHandler(
"silence",
chat_allowlist_required(admin_required(limit_sensitive("silence")(self.silence_command)))
))
self.application.add_handler(CommandHandler(
"unsilence",
chat_allowlist_required(admin_required(limit_sensitive("unsilence")(self.unsilence_command)))
))
self.application.add_handler(CommandHandler(
"silences",
chat_allowlist_required(admin_required(self.silences_command))
))
# ChatOps – Language detection (פתוח לכל המשתמשים)
self.application.add_handler(CommandHandler("lang", self.lang_command))
# מותר בטלגרם: אותיות/ספרות/קו תחתון בלבד
self.application.add_handler(CommandHandler(["lang_debug", "langdebug"], self.lang_debug_command))
# Callback handlers לכפתורים
# Guard הגלובלי התשתיתי מתווסף ב-main.py; כאן נשאר רק ה-handler הכללי
# חשוב: הוספה בקבוצה מאוחרת, כדי לתת עדיפות ל-handlers ספציפיים (למשל מועדפים)
try:
self.application.add_handler(CallbackQueryHandler(self.handle_callback_query), group=5)
except TypeError:
# סביבת בדיקות עם add_handler ללא פרמטר group
self.application.add_handler(CallbackQueryHandler(self.handle_callback_query))
# Handler מוקדם וממוקד לטוגל מועדפים כדי להבטיח קליטה מיידית
toggle_pattern = r'^(fav_toggle_id:|fav_toggle_tok:)'
toggle_handler = CallbackQueryHandler(self.handle_callback_query, pattern=toggle_pattern)
try:
self.application.add_handler(toggle_handler, group=-5)
except TypeError:
self.application.add_handler(toggle_handler)
except Exception as e:
logger.error(f"Failed to register favorites toggle CallbackQueryHandler: {e}")
# Handler ממוקד עם קדימות גבוהה לכפתורי /share
share_pattern = r'^(share_gist_|share_pastebin_|share_internal_|share_gist_multi:|share_internal_multi:|cancel_share)'
share_handler = CallbackQueryHandler(self.handle_callback_query, pattern=share_pattern)
try:
self.application.add_handler(share_handler, group=-5)
except TypeError:
# סביבת בדיקות/סטאב שבה add_handler לא תומך בפרמטר group
self.application.add_handler(share_handler)
except Exception as e:
# אל תבלע חריגות שקטות – דווח ללוג כדי לא לשבור את כפתורי השיתוף
logger.error(f"Failed to register share CallbackQueryHandler: {e}")
# Handler מוקדם לכפתורי /image (צור מחדש/עריכת הגדרות/Drive/פונטים/סגנון/שמירה)
image_pattern = r'^(regenerate_image_|edit_image_settings_|img_set_theme:|img_set_style:|img_set_width:|img_set_font:|img_note_prompt:|img_note_clear:|img_settings_done:|save_to_drive_|img_section:)'
image_handler = CallbackQueryHandler(self.handle_callback_query, pattern=image_pattern)
try:
self.application.add_handler(image_handler, group=-5)
except TypeError:
self.application.add_handler(image_handler)
except Exception as e:
logger.error(f"Failed to register image CallbackQueryHandler: {e}")
# קלט טקסט לפתקית תמונה (לפני מסננים כלליים)
try:
note_handler = MessageHandler(
filters.TEXT & (~filters.COMMAND),
self._handle_image_note_input,
block=False,
)
self.application.add_handler(note_handler, group=-2)
except Exception as e:
logger.error(f"Failed to register image note MessageHandler: {e}")
def _get_image_settings(self, context: ContextTypes.DEFAULT_TYPE, file_name: str) -> Dict[str, Any]:
try:
settings_map = context.user_data.setdefault('img_settings', {})
return dict(settings_map.get(file_name) or {})
except Exception:
return {}
def _set_image_setting(self, context: ContextTypes.DEFAULT_TYPE, file_name: str, key: str, value: Any) -> None:
try:
settings_map = context.user_data.setdefault('img_settings', {})
entry = dict(settings_map.get(file_name) or {})
if value is None:
entry.pop(key, None)
else:
entry[key] = value
if entry:
settings_map[file_name] = entry
else:
settings_map.pop(file_name, None)
except Exception:
pass
# --- Image callbacks tokenization helpers (to stay under Telegram's 64B limit) ---
def _get_or_create_image_token(self, context: ContextTypes.DEFAULT_TYPE, file_name: str) -> str:
"""Return a short stable token for a file name, storing mapping in user_data.
We avoid leaking long names into callback_data which has a 64 bytes limit.
"""
try:
tokens = context.user_data.setdefault('img_name_by_tok', {})
reverse = context.user_data.setdefault('img_tok_by_name', {})
tok = reverse.get(file_name)
if tok:
return tok
# Generate 8-hex token; prefix with 'tok:' when used in callback
tok = secrets.token_hex(4)
# Ensure uniqueness
while tok in tokens:
tok = secrets.token_hex(4)
tokens[tok] = file_name
reverse[file_name] = tok
return tok
except Exception:
# Fallback – if something goes wrong, return sanitized short name tail
return (file_name or 'file')[-40:]
def _resolve_image_target(self, context: ContextTypes.DEFAULT_TYPE, suffix: str) -> str:
"""Resolve a callback suffix back to the original file name.
Supports either a raw file name or a token prefixed with 'tok:'.
"""
try:
if suffix.startswith('tok:'):
token = suffix.split(':', 1)[1]
else:
token = suffix
# Try token lookup first
name = (context.user_data.get('img_name_by_tok') or {}).get(token)
if name:
return str(name)
# Not a known token – assume it's a direct file name
return suffix
except Exception:
return suffix
def _make_safe_suffix(self, context: ContextTypes.DEFAULT_TYPE, action_prefix: str, file_name: str) -> str:
"""Return a safe suffix for callback_data for given action.
If the combined callback would exceed 64 bytes, return a 'tok:<token>' suffix.
"""
try:
cb = f"{action_prefix}{file_name}"
if len(cb.encode('utf-8')) <= 64:
return file_name
tok = self._get_or_create_image_token(context, file_name)
return f"tok:{tok}"
except Exception:
return file_name
def _parse_image_args(self, args: List[str]) -> Tuple[str, Optional[str], bool]:
"""מפצל פרמטרים של /image לשם קובץ ואופציונלית הערה קצרה (--note)."""
if not args:
return "", None, False
file_tokens: List[str] = []
note_tokens: List[str] = []
note_mode = False
note_explicit = False
clear_requested = False
for token in args:
if token == '--note-clear':
note_tokens = []
note_mode = False
note_explicit = True
clear_requested = True
continue
if note_mode:
note_tokens.append(token)
continue
if token == '--note':
note_mode = True
note_explicit = True
continue
if token.startswith('--note='):
note_mode = True
note_explicit = True
note_tokens.append(token.split('=', 1)[1])
continue
file_tokens.append(token)
file_name = " ".join(file_tokens).strip()
if clear_requested:
return file_name, "", True
note = " ".join(note_tokens).strip() if note_tokens else None
if note:
note = note[:220]
return file_name, note or None, note_explicit
async def _handle_image_note_input(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""קולט טקסט חופשי לאחר שלחיצה על 'פתקית' ביקשה קלט."""
state = context.user_data.get('waiting_for_image_note')
if not state:
return False
# הוצא את הדגל כדי למנוע טריגרים כפולים
context.user_data.pop('waiting_for_image_note', None)
message = getattr(update, 'message', None)
if message is None:
# החזר דגל כדי שלא לאבד את מצב הפתקית, ומנע המשך עיבוד
context.user_data['waiting_for_image_note'] = state
raise ApplicationHandlerStop()
file_name = (state.get('file_name') or state.get('file') or '').strip()
if not file_name:
await message.reply_text("⚠️ לא הצלחתי לאתר את הקובץ לעדכון הפתקית.")
raise ApplicationHandlerStop()
text = (message.text or '').strip()
if not text:
# תחזיר את הדגל כדי לאסוף שוב תשובה
context.user_data['waiting_for_image_note'] = state
await message.reply_text("ℹ️ ההודעה ריקה. שלח טקסט עד 220 תווים או כתוב 'בטל'.")
raise ApplicationHandlerStop()
lowered = text.lower()
cancel_tokens = {"בטל", "cancel", "ביטול", "דלג", "skip"}
clear_tokens = {"מחק", "delete", "clear", "ללא", "נקה", "remove", "מחיקה"}
if lowered in cancel_tokens:
await message.reply_text("❎ בוטל – הפתקית לא שונתה.")
raise ApplicationHandlerStop()
if lowered in clear_tokens:
self._set_image_setting(context, file_name, 'note', None)
await message.reply_text(f"🧹 הפתקית הוסרה עבור {file_name}.")
else:
trimmed = text[:220]
if len(text) > 220:
await message.reply_text("✂️ הפתקית קוצרה ל-220 תווים ונשמרה.")
else:
await message.reply_text("✅ הפתקית נשמרה.")
self._set_image_setting(context, file_name, 'note', trimmed)
chat_id = state.get('chat_id')
message_id = state.get('message_id')
if chat_id and message_id:
try:
kb = self._build_image_settings_keyboard(update.effective_user.id, context, file_name)
await context.bot.edit_message_reply_markup(
chat_id=chat_id,
message_id=message_id,
reply_markup=kb,
)
except Exception:
pass
raise ApplicationHandlerStop()
def _build_image_settings_keyboard(self, user_id: int, context: ContextTypes.DEFAULT_TYPE, file_name: str) -> InlineKeyboardMarkup:
"""בנה מקלדת הגדרות תמונה (תמה/סגנון/רוחב/פונט) תוך סימון הבחירה הנוכחית.
עדכון: כוללת תמות נוספות (Gruvbox, One Dark, Dracula), בחירת סגנון (Pygments) ושורת בחירת פונט.
"""
# העדפות אפקטיביות: פר-משתמש (DB) עם דריסה פר-קובץ (context)
settings = self._get_effective_image_settings(user_id, context, file_name)
current_theme = str(settings.get('theme') or IMAGE_CONFIG.get('default_theme') or 'dark')
current_style = str(settings.get('style') or IMAGE_CONFIG.get('default_style') or 'monokai')
try:
current_width = int(settings.get('width') or IMAGE_CONFIG.get('default_width') or 1200)
except Exception:
current_width = 1200
current_font = str(settings.get('font') or 'dejavu')
current_note = str(settings.get('note') or '').strip()
# suffixes בטוחים עבור callback_data קצרים
theme_suffix = self._make_safe_suffix(context, "img_set_theme:", file_name)
style_suffix = self._make_safe_suffix(context, "img_set_style:", file_name)
width_suffix = self._make_safe_suffix(context, "img_set_width:", file_name)
font_suffix = self._make_safe_suffix(context, "img_set_font:", file_name)
note_suffix = self._make_safe_suffix(context, "img_note_prompt:", file_name)
clear_suffix = self._make_safe_suffix(context, "img_note_clear:", file_name)
done_suffix = self._make_safe_suffix(context, "img_settings_done:", file_name)
def _mk_theme_cb(val: str) -> str:
return f"img_set_theme:{val}:{theme_suffix}"
def _mk_style_cb(val: str) -> str:
return f"img_set_style:{val}:{style_suffix}"
def _mk_width_cb(val: int) -> str:
return f"img_set_width:{val}:{width_suffix}"
def _lbl(selected: bool, selected_label: str, default_label: str) -> str:
return (f"✅ {selected_label}" if selected else default_label)
def _section_row(label: str, key: str) -> List[InlineKeyboardButton]:
return [InlineKeyboardButton(label, callback_data=f"img_section:{key}")]
rows: List[List[InlineKeyboardButton]] = [
_section_row("ערכות תמה", "themes"),
[
InlineKeyboardButton(
_lbl(current_theme == 'dark', 'Dark', '🎨 Dark'),
callback_data=_mk_theme_cb('dark')
),
InlineKeyboardButton(
_lbl(current_theme == 'light', 'Light', '🌤️ Light'),
callback_data=_mk_theme_cb('light')
),
],
[
InlineKeyboardButton(
_lbl(current_theme == 'github', 'GitHub', '🐙 GitHub'),
callback_data=_mk_theme_cb('github')
),
InlineKeyboardButton(
_lbl(current_theme == 'monokai', 'Monokai', '🎯 Monokai'),
callback_data=_mk_theme_cb('monokai')
),
],
[
InlineKeyboardButton(
_lbl(current_theme == 'gruvbox', 'Gruvbox', '🟤 Gruvbox'),
callback_data=_mk_theme_cb('gruvbox')
),
InlineKeyboardButton(
_lbl(current_theme == 'one_dark', 'One Dark', '🌑 One Dark'),
callback_data=_mk_theme_cb('one_dark')
),
],
[
InlineKeyboardButton(
_lbl(current_theme == 'dracula', 'Dracula', '🧛 Dracula'),
callback_data=_mk_theme_cb('dracula')
),
InlineKeyboardButton(
_lbl(current_theme == 'banner_tech', 'Banner Tech', '💜 Banner Tech'),
callback_data=_mk_theme_cb('banner_tech')
),
],
]
# שורת "סגנון" (Pygments) – אחראית על צבעי התחביר.
rows.extend([
_section_row("צבעי תחביר", "syntax"),
[
InlineKeyboardButton(
_lbl(current_style == 'banner_tech', 'Tech Guide', '💜 Tech Guide'),
callback_data=_mk_style_cb('banner_tech')
),
InlineKeyboardButton(
_lbl(current_style == 'monokai', 'Monokai', '🎯 Monokai'),
callback_data=_mk_style_cb('monokai')
),
],
[
InlineKeyboardButton(
_lbl(current_style == 'default', 'Default', '🧩 Default'),
callback_data=_mk_style_cb('default')
),
InlineKeyboardButton(
_lbl(current_style == 'dracula', 'Dracula', '🧛 Dracula'),
callback_data=_mk_style_cb('dracula')
),
],
])
rows.append(_section_row("גודל תמונה", "size"))
width_buttons: List[InlineKeyboardButton] = []
for opt in self._get_configured_width_options():
width_buttons.append(
InlineKeyboardButton(
_lbl(current_width == opt, f"{opt}px", f"{opt}px"),
callback_data=_mk_width_cb(opt)
)
)
for i in range(0, len(width_buttons), 2):
rows.append(width_buttons[i:i + 2])
note_label = "🗒️ הוסף פתקית" if not current_note else "🗒️ ערוך פתקית"
note_row = [
InlineKeyboardButton(
note_label,
callback_data=f"img_note_prompt:{note_suffix}"
)
]
if current_note:
note_row.append(
InlineKeyboardButton(
"🧹 נקה",
callback_data=f"img_note_clear:{clear_suffix}"
)
)
rows.append(note_row)
rows.append(_section_row("סוגי פונטים", "fonts"))
rows.append([
InlineKeyboardButton(
_lbl(current_font == 'dejavu', 'DejaVu', '📝 DejaVu Sans Mono'),
callback_data=f"img_set_font:dejavu:{font_suffix}"
),
InlineKeyboardButton(
_lbl(current_font == 'jetbrains', 'JetBrains', '🚀 JetBrains Mono'),
callback_data=f"img_set_font:jetbrains:{font_suffix}"
),
InlineKeyboardButton(
_lbl(current_font == 'cascadia', 'Cascadia', '💻 Cascadia Code'),
callback_data=f"img_set_font:cascadia:{font_suffix}"
),
])
rows.append([InlineKeyboardButton("שמור", callback_data=f"img_settings_done:{done_suffix}")])
return InlineKeyboardMarkup(rows)
def _get_configured_width_options(self) -> List[int]:
"""הפקת רשימת רוחבים זמינים (מסוננת וממוינת)."""
fallback = [800, 1200, 1400, 1800, 2000]
try:
raw = IMAGE_CONFIG.get('width_options')
if not raw:
return fallback
if isinstance(raw, int):
raw = [raw]
widths: List[int] = []
for val in raw:
try:
w = int(val)
if w >= 600 and w <= 2600:
widths.append(w)
except Exception:
continue
if not widths:
return fallback
return sorted(dict.fromkeys(widths))
except Exception:
return fallback
def _get_effective_image_settings(self, user_id: int, context: ContextTypes.DEFAULT_TYPE, file_name: str) -> Dict[str, Any]:
"""מאחד העדפות פר-משתמש (DB) עם העדפות פר-קובץ (context)."""
try:
# בסיס: העדפות משתמש גלובליות
base = _call_files_api("get_image_prefs", user_id) or {}
except Exception:
base = {}
# דריסה פר-קובץ בזיכרון
try:
overrides = self._get_image_settings(context, file_name)
except Exception:
overrides = {}
merged = dict(base)
merged.update(overrides)
return merged
def _build_image_error_hint(self, requested_width: Optional[int], code_length: int) -> str:
"""טקסט עזרה עדין לשגיאות, עם הדגשה על הורדת רזולוציה/קיצור קובץ."""
try:
suggestions: List[str] = []
if requested_width and requested_width >= 1600:
suggestions.append("נסה לבחור רוחב נמוך יותר דרך הכפתור \"📝 ערוך הגדרות\" (למשל 1200px או 1400px).")
if code_length > 12000:
suggestions.append("לקבצים ארוכים במיוחד כדאי ליצור תמונה רק לחלק מהשורות או לקצר מעט.")
if not suggestions:
suggestions.append("אפשר לנסות שוב אחרי הקטנת הרוחב או קיצור הקובץ.")
return "\n💡 " + " ".join(suggestions)
except Exception:
return "\n💡 נסה שוב אחרי הקטנת הרוחב או קיצור הקובץ."
async def _edit_message_with_media_fallback(
self,
query,
text: str,
*,
parse_mode: Optional[str] = None,
reply_markup: Optional[InlineKeyboardMarkup] = None,
) -> None:
"""Edit הודעה, עם fallback להודעות מדיה (caption) או reply חדש במידת הצורך."""
try:
await query.edit_message_text(
text=text,
parse_mode=parse_mode,
reply_markup=reply_markup,
)
return
except telegram.error.BadRequest as exc:
desc = str(exc).lower()
# אם אין שינוי ממשי – אין צורך לפעול
if "message is not modified" in desc:
return
# תמיכת fallback גם בשגיאה הנפוצה: "There is no text in the message to edit"
needs_fallback = any(
key in desc
for key in (
"message can't be edited",
"message to edit not found",
"message to edit has no text",
"there is no text in the message to edit",
"no text in the message to edit",
"can't edit message",
)
)
if not needs_fallback:
raise
except Exception:
# חריגות אחרות יטופלו ע"י fallback מתחת
pass
# ניסיון לערוך caption (במיוחד עבור הודעות תמונה)
try:
await query.edit_message_caption(
caption=text,
parse_mode=parse_mode,
reply_markup=reply_markup,
)
return
except telegram.error.BadRequest as exc:
desc = str(exc).lower()
if "message is not modified" in desc:
return
needs_reply = any(
key in desc
for key in (
"message can't be edited",
"message to edit not found",
"can't edit message",
)
)
if not needs_reply:
raise
except Exception:
pass
# שליחת הודעה חדשה כהודעת fallback סופית
try:
await query.message.reply_text(
text,
parse_mode=parse_mode,
reply_markup=reply_markup,
)
except Exception:
# בשלב זה אין עוד מה לעשות – נבלע חריגה כדי לא לשבור את הזרימה
logger.warning("Fallback reply_text כשל עבור לחצן תמונה", exc_info=True)
async def show_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""הצגת קטע קוד עם הדגשת תחביר"""
reporter.report_activity(update.effective_user.id)
user_id = update.effective_user.id
if not context.args:
await update.message.reply_text(
"📄 אנא ציין שם קובץ:\n"
"דוגמה: `/show script.py`",
parse_mode=ParseMode.MARKDOWN
)
return
file_name = " ".join(context.args)
file_data = _call_files_api("get_latest_version", user_id, file_name)
if not file_data:
await update.message.reply_text(
f"❌ קובץ `{file_name}` לא נמצא.",
parse_mode=ParseMode.MARKDOWN
)
return
# קבל את הקוד המקורי בבטחה; ודא שתמיד יש מחרוזת קוד
code_raw = str((file_data.get('code') or ""))
language = str((file_data.get('programming_language') or ""))
try:
# highlight_code עשוי להחזיר מחרוזת ריקה במקרי קצה — ניפול חזרה לקוד המקורי
original_code = code_processor.highlight_code(code_raw, language)
except Exception:
original_code = code_raw
if not isinstance(original_code, str) or original_code == "":
original_code = code_raw
# בצע הימלטות לתוכן הקוד כדי למנוע שגיאות
escaped_code = html.escape(original_code)
language_html = html.escape(language)
# עטוף את הקוד הנקי בתגיות <pre><code> שטלגרם תומך בהן
response_text = f"""<b>File:</b> <code>{html.escape(str(file_data.get('file_name', file_name)))}</code>
<b>Language:</b> {language_html}
<pre><code>{escaped_code}</code></pre>
"""
# --- מבנה הכפתורים החדש והנקי ---
file_id = str(file_data.get('_id', file_name))
# כפתור מועדפים בהתאם למצב הנוכחי
try:
checked = _call_files_api("is_favorite", user_id, file_name)
is_fav_now = bool(checked) if checked is not None else False
except Exception:
is_fav_now = False
fav_text = ("💔 הסר ממועדפים" if is_fav_now else "⭐ הוסף למועדפים")
# הקפדה על מגבלת 64 בתים ב-callback_data + הימנעות מתווים בעייתיים
# העדפה ל-ID אם קיים; אחרת טוקן קצר עם מיפוי ב-user_data
has_id = True
try:
_raw_id = file_data.get('_id')
if _raw_id is None:
has_id = False
else:
file_id_str = str(_raw_id)
except Exception:
has_id = False
file_id_str = ""
if has_id and (len("fav_toggle_id:") + len(file_id_str)) <= 60:
fav_cb = f"fav_toggle_id:{file_id_str}"
else:
try:
token = secrets.token_urlsafe(6)
except Exception:
token = "t" # fallback קצר
# קיצור טוקן לשימוש ב-callback_data ושמירת המיפוי תחת המפתח המקוצר
short_tok = (token[:24] if isinstance(token, str) else "t")
try:
tokens_map = context.user_data.get('fav_tokens') or {}
tokens_map[short_tok] = file_name
context.user_data['fav_tokens'] = tokens_map
except Exception:
pass
fav_cb = f"fav_toggle_tok:{short_tok}"
buttons = [
[
InlineKeyboardButton("🗑️ מחיקה", callback_data=f"delete_{file_id}"),
InlineKeyboardButton("✏️ עריכה", callback_data=f"edit_{file_id}")
],
[
InlineKeyboardButton("📝 ערוך הערה", callback_data=f"edit_note_{file_id}"),
InlineKeyboardButton("💾 הורדה", callback_data=f"download_{file_id}")
],
[
InlineKeyboardButton("🌐 שיתוף", callback_data=f"share_{file_id}")
],
[
InlineKeyboardButton(fav_text, callback_data=fav_cb)
]
]
reply_markup = InlineKeyboardMarkup(buttons)
# ---------------------------------
await update.message.reply_text(response_text, parse_mode='HTML', reply_markup=reply_markup)
async def favorite_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""הוספה/הסרה של קובץ מהמועדפים: /favorite <file_name>"""
reporter.report_activity(update.effective_user.id)
user_id = update.effective_user.id
if not context.args:
await update.message.reply_text(
"🔖 <b>הוספה/הסרה ממועדפים</b>\n\n"
"שימוש: <code>/favorite <file_name></code>\n\n"
"דוגמה:\n"
"<code>/favorite config.py</code>\n\n"
"או שלח <code>/favorites</code> לצפייה בכל המועדפים",
parse_mode=ParseMode.HTML
)
return
file_name = " ".join(context.args)
snippet = _call_files_api("get_latest_version", user_id, file_name)
if not snippet:
await update.message.reply_text(
f"❌ הקובץ <code>{html.escape(file_name)}</code> לא נמצא.\n"
"שלח <code>/list</code> לרשימת הקבצים שלך.",
parse_mode=ParseMode.HTML
)
return
new_state = _call_files_api("toggle_favorite", user_id, file_name)
# אם המתודה מחזירה None, זו שגיאה
if new_state is None:
await update.message.reply_text("❌ שגיאה בעדכון מועדפים. נסה שוב מאוחר יותר.")
return
language = snippet.get('programming_language', '') or ''
emoji = ''
try:
from utils import get_language_emoji
emoji = get_language_emoji(language)
except Exception:
emoji = ''
if new_state:
msg = (
f"⭐ <b>נוסף למועדפים!</b>\n\n"
f"📁 קובץ: <code>{html.escape(file_name)}</code>\n"
f"{emoji} שפה: {html.escape(language or 'לא ידוע')}\n\n"
f"💡 גש במהירות עם <code>/favorites</code>"
)
else:
msg = (
f"💔 <b>הוסר מהמועדפים</b>\n\n"
f"📁 קובץ: <code>{html.escape(file_name)}</code>\n\n"
f"ניתן להוסיף שוב מאוחר יותר."
)
# כפתורים מהירים
keyboard = [
[
InlineKeyboardButton("📋 הצג קובץ", callback_data=f"view_direct_{file_name}"),
InlineKeyboardButton("⭐ כל המועדפים", callback_data="favorites_list"),
]
]
await update.message.reply_text(msg, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(keyboard))
async def favorites_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""רשימת המועדפים של המשתמש: /favorites"""
reporter.report_activity(update.effective_user.id)
user_id = update.effective_user.id
favorites = _call_files_api("get_favorites", user_id, limit=50) or []
if not favorites:
await update.message.reply_text(
"💭 אין לך מועדפים כרגע.\n"
"✨ הוסף מועדף ראשון עם <code>/favorite <שם></code>",
parse_mode=ParseMode.HTML
)
return
lines = ["⭐ <b>המועדפים שלך</b>"]
from utils import TimeUtils, get_language_emoji
for idx, fav in enumerate(favorites[:10], 1):
fname = fav.get('file_name', '')
lang = fav.get('programming_language', '')
rel = ''
try:
fa = fav.get('favorited_at') or fav.get('updated_at') or fav.get('created_at')
if fa:
rel = TimeUtils.format_relative_time(fa)
except Exception:
rel = ''
emoji = get_language_emoji(lang)
line = f"{idx}. {emoji} <code>{html.escape(str(fname))}</code>"
if rel:
line += f" • {rel}"
lines.append(line)
if len(favorites) > 10:
lines.append(f"\n➕ ועוד {len(favorites) - 10} קבצים...")
message = "\n".join(lines)
# כפתורי קיצור לקבצים (עד 5 ראשונים)
buttons: list[list[InlineKeyboardButton]] = []
for fav in favorites[:5]:
fname = fav.get('file_name', '')
try:
latest = _call_files_api("get_latest_version", user_id, fname) or {}
fid = str(latest.get('_id') or '')
except Exception:
fid = ''
if fid:
cb = f"view_direct_id:{fid}"
else:
safe_name = (fname[:45] + '...') if len(fname) > 48 else fname
cb = f"view_direct_{safe_name}"
buttons.append([InlineKeyboardButton(f"📄 {fname[:20]}", callback_data=cb)])