utils module

פונקציות עזר כלליות לבוט שומר קבצי קוד General Utility Functions for Code Keeper Bot

class utils.CodeErrorLogger[source]

Bases: object

מערכת לוגים ייעודית לשגיאות עיבוד קוד

__init__()[source]
log_code_processing_error(user_id, error_type, error_message, context=None)[source]

רישום שגיאות עיבוד קוד

Return type:

None

Parameters:
log_code_activity(user_id, activity_type, details=None)[source]

רישום פעילות עיבוד קוד

Return type:

None

Parameters:
log_validation_failure(user_id, code_length, error_reason)[source]

רישום כשל באימות קוד

Parameters:
  • user_id (int)

  • code_length (int)

  • error_reason (str)

log_sanitization_success(user_id, original_length, cleaned_length)[source]

רישום הצלחה בסניטציה

Parameters:
  • user_id (int)

  • original_length (int)

  • cleaned_length (int)

class utils.TimeUtils[source]

Bases: object

כלים לעבודה עם זמן ותאריכים

static format_relative_time(dt)[source]

פורמט זמן יחסי (לפני 5 דקות, אתמול וכו’)

Return type:

str

Parameters:

dt (datetime)

static parse_date_string(date_str)[source]

פרסור מחרוזת תאריך לאובייקט datetime

Return type:

Optional[datetime]

Parameters:

date_str (str)

static get_time_ranges(period)[source]

קבלת טווח זמנים לפי תקופה

Return type:

Tuple[datetime, datetime]

Parameters:

period (str)

class utils.TextUtils[source]

Bases: object

כלים לעבודה עם טקסט

static truncate_text(text, max_length=100, suffix='...')[source]

קיצור טקסט עם סיומת

Return type:

str

Parameters:
static escape_markdown(text, version=2)[source]

הגנה על תווים מיוחדים ב-Markdown

Return type:

str

Parameters:
static clean_filename(filename)[source]

ניקוי שם קובץ מתווים לא חוקיים

Return type:

str

Parameters:

filename (str)

static extract_hashtags(text)[source]

חילוץ תגיות מטקסט

Return type:

List[str]

Parameters:

text (str)

static highlight_text(text, query, tag='**')[source]

הדגשת מילות חיפוש בטקסט

Return type:

str

Parameters:
static format_file_size(size_bytes)[source]

פורמט גודל קובץ (bytes -> KB/MB/GB)

Return type:

str

Parameters:

size_bytes (int)

static pluralize_hebrew(count, singular, plural)[source]

צורת רבים עבריות

Return type:

str

Parameters:
class utils.SecurityUtils[source]

Bases: object

כלים אמינות ובטיחות

static generate_secure_token(length=32)[source]

יצירת טוקן מאובטח

Return type:

str

Parameters:

length (int)

static hash_content(content, algorithm='sha256')[source]

יצירת hash לתוכן

Return type:

str

Parameters:
  • content (str)

  • algorithm (str)

static validate_user_input(text, max_length=10000, forbidden_patterns=None)[source]

בדיקת קלט משתמש

Return type:

bool

Parameters:
  • text (str)

  • max_length (int)

  • forbidden_patterns (List[str] | None)

static sanitize_code(code)[source]

ניקוי קוד מתוכן מסוכן (בסיסי)

Return type:

str

Parameters:

code (str)

class utils.TelegramUtils[source]

Bases: object

כלים לעבודה עם Telegram

async static send_typing_action(update, context)[source]

שליחת אקשן ‘כותב…’

Parameters:
  • update (telegram.Update)

  • context (telegram.ext.ContextTypes.DEFAULT_TYPE)

async static send_document_action(update, context)[source]

שליחת אקשן ‘שולח מסמך…’

Parameters:
  • update (telegram.Update)

  • context (telegram.ext.ContextTypes.DEFAULT_TYPE)

async static safe_answer(query, text=None, show_alert=False, cache_time=None)[source]

מענה בטוח ל-CallbackQuery: מתעלם משגיאות ‘Query is too old’/’query_id_invalid’.

Return type:

None

Parameters:
  • text (str | None)

  • show_alert (bool)

  • cache_time (int | None)

static get_user_mention(user)[source]

קבלת מנשן למשתמש

Return type:

str

Parameters:

user (telegram.User)

static split_long_message(text, max_length=4096)[source]

חלוקת הודעה ארוכה לחלקים

Return type:

List[str]

Parameters:
async static safe_edit_message_text(query, text, reply_markup=None, parse_mode=None)[source]

עריכת טקסט הודעה בבטיחות: מתעלם משגיאת ‘Message is not modified’.

תומך גם במימושי בדיקות שבהם edit_message_text היא פונקציה סינכרונית שמחזירה None (לא awaitable), וגם במימושים אסינכרוניים רגילים.

Return type:

None

Parameters:
  • text (str)

  • parse_mode (str | None)

async static safe_edit_message_reply_markup(query, reply_markup=None)[source]

עריכת מקלדת הודעה בבטיחות: מתעלם משגיאת ‘Message is not modified’.

Return type:

None

static extract_message_text_preserve_markdown(message, *, reconstruct_from_entities=True)[source]

שחזור טקסט ההודעה תוך ניסיון להחזיר את מה שהמשתמש התכוון מבחינת תווי Markdown.

עקרונות:

  • ברירת מחדל: נשתמש ב-text/caption (התוכן הגולמי כפי שנשלח לשרת לאחר עיבוד Markdown). זאת כדי לא לשמור מחרוזת “מרונדרת” (למשל *_name_*), שאינה משקפת קלט משתמש.

  • במידה ו-reconstruct_from_entities=True ויש ישויות עיצוב (bold/italic), ננסה לשחזר תווי Markdown שהיוו כנראה את מקור העיצוב ע”י הוספת תחיליות/סיומות סביב הטקסט שסומן. מיפוי פשוט: bold"__", italic"_". שאר ישויות נשמרות כפי שהן.

  • אם יש כיתוב (caption), נשתמש במקבילות caption_entities.

Return type:

str

Parameters:
class utils.CallbackQueryGuard[source]

Bases: object

Guard גורף ללחיצות כפולות על כפתורי CallbackQuery.

מבוסס על טביעת אצבע של המשתמש/הודעה/הנתון (callback_data) כדי לחסום את אותה פעולה בחלון זמן קצר, בלי לחסום פעולות שונות.

DEFAULT_WINDOW_SECONDS: float = 1.2
static should_block(update, context, window_seconds=None)[source]

בודק האם יש לחסום את העדכון כלחיצה כפולה.

אם זו אותה טביעת אצבע בתוך חלון הזמן – נחסום; אחרת נסמן ונאפשר.

Return type:

bool

Parameters:
  • update (telegram.Update)

  • context (telegram.ext.ContextTypes.DEFAULT_TYPE)

  • window_seconds (float | None)

async static should_block_async(update, context, window_seconds=None)[source]

בודק בצורה אטומית (עם נעילה) אם לחסום לחיצה כפולה של אותו משתמש.

חסימה מבוססת חלון זמן פר-משתמש ועל אותה טביעת אצבע (משתמש/צ׳אט/הודעה/הנתון), כדי למנוע כפילויות אמיתיות בלי לחסום לחיצות שונות ברצף מהיר (UX).

Return type:

bool

Parameters:
  • update (telegram.Update)

  • context (telegram.ext.ContextTypes.DEFAULT_TYPE)

  • window_seconds (float | None)

class utils.AsyncUtils[source]

Bases: object

כלים לעבודה אסינכרונית

async static run_with_timeout(coro, timeout=30.0)[source]

הרצת פונקציה אסינכרונית עם timeout

Parameters:

timeout (float)

async static batch_process(items, process_func, batch_size=10, delay=0.1)[source]

עיבוד פריטים בקבוצות

Return type:

List[Any]

Parameters:
class utils.PerformanceUtils[source]

Bases: object

כלים למדידת ביצועים

static timing_decorator(func)[source]

דקורטור למדידת זמן ביצוע

static measure_time(operation_name)[source]

מדידת זמן עם context manager

Parameters:

operation_name (str)

class utils.ValidationUtils[source]

Bases: object

כלים לוולידציה

static is_valid_filename(filename)[source]

בדיקת תקינות שם קובץ

Return type:

bool

Parameters:

filename (str)

static is_safe_code(code, programming_language)[source]

בדיקה בסיסית של בטיחות קוד

Return type:

Tuple[bool, List[str]]

Parameters:
  • code (str)

  • programming_language (str)

class utils.FileUtils[source]

Bases: object

כלים לעבודה עם קבצים

async static download_file(url, max_size=10485760)[source]

הורדת קובץ מ-URL

Return type:

Optional[bytes]

Parameters:
static get_file_extension(filename)[source]

קבלת סיומת קובץ

Return type:

str

Parameters:

filename (str)

static get_mime_type(filename)[source]

קבלת MIME type של קובץ

Return type:

str

Parameters:

filename (str)

async static create_temp_file(content, suffix='')[source]

יצירת קובץ זמני

Return type:

str

Parameters:
class utils.ConfigUtils[source]

Bases: object

כלים לקונפיגורציה

static load_json_config(file_path, default=None)[source]

טעינת קונפיגורציה מקובץ JSON

Return type:

Dict[str, Any]

Parameters:
static save_json_config(file_path, config)[source]

שמירת קונפיגורציה לקובץ JSON

Return type:

bool

Parameters:
class utils.CacheUtils[source]

Bases: object

כלים לקאש זמני

classmethod set(key, value, ttl=300)[source]

שמירה בקאש עם TTL (שניות)

Parameters:
classmethod get(key, default=None)[source]

קבלה מהקאש

Return type:

Any

Parameters:
classmethod delete(key)[source]

מחיקה מהקאש

Parameters:

key (str)

classmethod clear()[source]

ניקוי כל הקאש

utils.get_memory_usage()[source]

קבלת נתוני זיכרון

Return type:

Dict[str, Any]

utils.setup_logging(level='INFO', log_file=None)[source]

הגדרת לוגים

Return type:

Logger

Parameters:
  • level (str)

  • log_file (str | None)

utils.generate_summary_stats(files_data)[source]

יצירת סיכום סטטיסטיקות

Return type:

Dict[str, Any]

Parameters:

files_data (List[Dict[str, Any]])

utils.detect_language_from_filename(filename)[source]

זיהוי שפת תכנות לפי סיומת הקובץ (Filename-only). נסה קודם את הדטקטור הדומייני כדי לשמור אחידות, ונפילה למיפוי מקומי לתאימות.

Return type:

str

Parameters:

filename (str)

utils.get_language_emoji(language)[source]

מחזיר אימוג’י מתאים לשפת התכנות

Return type:

str

Parameters:

language (str)

class utils.SensitiveDataFilter(name='')[source]

Bases: Filter

מסנן שמטשטש טוקנים ונתונים רגישים בלוגים.

filter(record)[source]

Determine if the specified record is to be logged.

Returns True if the record should be logged, or False otherwise. If deemed appropriate, the record may be modified in-place.

Return type:

bool

Parameters:

record (LogRecord)

utils.install_sensitive_filter()[source]

התקנת המסנן על כל ה-handlers הקיימים.

utils.normalize_code(text, *, strip_bom=True, normalize_newlines=True, replace_nbsp=True, replace_all_space_separators=True, remove_zero_width=True, remove_directional_marks=True, trim_trailing_whitespace=True, remove_other_format_chars=True, remove_escaped_format_escapes=True, remove_variation_selectors=False)[source]

נרמול קוד לפני שמירה.

פעולות עיקריות:

  • הסרת BOM בתחילת הטקסט

  • המרת CRLF/CR ל-LF

  • החלפת רווחים לא-שוברים (NBSP/NNBSP) לרווח רגיל

  • הסרת תווי רוחב-אפס וסימוני כיוון (LRM/RLM/LRE/RLE/PDF/RLO/LRO/LRI/RLI/FSI/PDI)

  • הסרת תווי בקרה (Cc) פרט ל-t, n, r

  • הסרת רווחי סוף שורה

Return type:

str

Parameters:
  • text (str)

  • strip_bom (bool)

  • normalize_newlines (bool)

  • replace_nbsp (bool)

  • replace_all_space_separators (bool)

  • remove_zero_width (bool)

  • remove_directional_marks (bool)

  • trim_trailing_whitespace (bool)

  • remove_other_format_chars (bool)

  • remove_escaped_format_escapes (bool)

  • remove_variation_selectors (bool)