handlers.py: добавлен import smtplib, детальное логгирование ошибок

This commit is contained in:
2026-08-14 11:49:25 +07:00
parent ff6216cdf3
commit 7196fe603a
+23 -14
View File
@@ -2,6 +2,7 @@
import os import os
import asyncio import asyncio
import logging import logging
import smtplib
import time import time
from datetime import datetime from datetime import datetime
from email.mime.text import MIMEText from email.mime.text import MIMEText
@@ -102,6 +103,7 @@ def log_and_notify_photo_error(user_id: str, action: str, error_details: str):
async def handle_photo_error(msg: Message, user_id: str, action: str, error_details: str): async def handle_photo_error(msg: Message, user_id: str, action: str, error_details: str):
"""Вызывает системное логирование и выдает заглушку пользователю""" """Вызывает системное логирование и выдает заглушку пользователю"""
logger.error(f"🔥 Ошибка фото-бота для {user_id}, действие: {action}: {error_details}")
await asyncio.to_thread(log_and_notify_photo_error, user_id, action, error_details) await asyncio.to_thread(log_and_notify_photo_error, user_id, action, error_details)
await msg.answer(photo_error_handling(), parse_mode="html") await msg.answer(photo_error_handling(), parse_mode="html")
@@ -218,20 +220,34 @@ async def photo_module_handler(msg: Message):
# --- ПРИЕМ НОВОГО ФОТО --- # --- ПРИЕМ НОВОГО ФОТО ---
if is_attachment: if is_attachment:
file_id = getattr(msg.content, "file_id", None) file_id = getattr(msg.content, "file_id", None)
raw_path = None raw_bytes = None
await msg.answer(PHOTO_PROCESSING_FACE_TEXT, parse_mode="html") await msg.answer(PHOTO_PROCESSING_FACE_TEXT, parse_mode="html")
try: try:
downloaded_file = await states.tc_bot.download_file_by_id(file_id) downloaded_file = await states.tc_bot.download_file_by_id(file_id)
raw_path = downloaded_file logger.info(f"Скачан файл для {user_login}: type={type(downloaded_file)}, len={len(downloaded_file) if isinstance(downloaded_file, (bytes, str)) else 'N/A'}")
# Читаем байты # Скачиваем в байты напрямую
with open(raw_path, 'rb') as f: if isinstance(downloaded_file, bytes):
image_bytes = f.read() raw_bytes = downloaded_file
elif isinstance(downloaded_file, str) and os.path.exists(downloaded_file):
with open(downloaded_file, 'rb') as f:
raw_bytes = f.read()
else:
# Пробуем как путь
raw_path = downloaded_file if isinstance(downloaded_file, str) else None
if raw_path and os.path.exists(raw_path):
with open(raw_path, 'rb') as f:
raw_bytes = f.read()
else:
raise Exception(f"Не удалось получить байты файла: {type(downloaded_file)}")
logger.info(f"Прочитано {len(raw_bytes)} байт для {user_login}")
# Ищем лицо и получаем координаты # Ищем лицо и получаем координаты
coords = await asyncio.to_thread(get_crop_coordinates, image_bytes) coords = await asyncio.to_thread(get_crop_coordinates, raw_bytes)
logger.info(f"get_crop_coordinates вернул: {coords} для {user_login}")
if not coords: if not coords:
await msg.answer( await msg.answer(
@@ -239,8 +255,6 @@ async def photo_module_handler(msg: Message):
f"{EMOJI_DIGITS['0']}В главное меню", f"{EMOJI_DIGITS['0']}В главное меню",
parse_mode="html" parse_mode="html"
) )
if os.path.exists(raw_path):
os.remove(raw_path)
return return
# Генерируем превью # Генерируем превью
@@ -290,11 +304,6 @@ async def photo_module_handler(msg: Message):
parse_mode="html" parse_mode="html"
) )
except Exception as e: except Exception as e:
logger.error(f"🔥 Полная ошибка: {e}", exc_info=True)
await handle_photo_error(msg, user_id, "Скачивание и обработка файла", str(e)) await handle_photo_error(msg, user_id, "Скачивание и обработка файла", str(e))
finally:
if raw_path and os.path.exists(raw_path):
try:
os.remove(raw_path)
except Exception as cleanup_err:
await asyncio.to_thread(log_and_notify_photo_error, user_id, "Очистка временных файлов", str(cleanup_err))
return return