Spaces:
Runtime error
Runtime error
Create handlers.py
Browse files- handlers.py +114 -0
handlers.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# handlers.py
|
| 2 |
+
import os
|
| 3 |
+
import asyncio
|
| 4 |
+
import logging
|
| 5 |
+
from typing import List
|
| 6 |
+
|
| 7 |
+
from hydrogram import Client, filters
|
| 8 |
+
from hydrogram.types import Message
|
| 9 |
+
from hydrogram.errors import FloodWait, RPCError
|
| 10 |
+
from hydrogram.handlers import MessageHandler # Explicit import for add_handler
|
| 11 |
+
|
| 12 |
+
from config import Config
|
| 13 |
+
from utils import is_admin
|
| 14 |
+
from processing import process_images_sync
|
| 15 |
+
from main import executor # Import executor from main.py
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
async def handle_photo_message_impl(client: Client, message: Message):
|
| 20 |
+
user = message.from_user
|
| 21 |
+
user_id = user.id
|
| 22 |
+
user_info = f"user_id={user_id}" + (f", username={user.username}" if user.username else "")
|
| 23 |
+
caption = message.caption if message.caption else ""
|
| 24 |
+
message_id = message.id
|
| 25 |
+
chat_id = message.chat.id
|
| 26 |
+
|
| 27 |
+
logger.info(f"ADMIN ACTION (Bot): Received photo with caption from {user_info} (msg_id={message_id}).")
|
| 28 |
+
|
| 29 |
+
temp_user_image_path = os.path.join(Config.OUTPUT_DIR, f"bot_user_{user_id}_{message_id}.jpg")
|
| 30 |
+
file_downloaded = False
|
| 31 |
+
processing_status_message = None
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
if not message.photo: return
|
| 35 |
+
download_start_time = asyncio.get_running_loop().time()
|
| 36 |
+
logger.info(f"Attempting download photo (file_id: {message.photo.file_id})...")
|
| 37 |
+
downloaded_path = await client.download_media(message.photo.file_id, file_name=temp_user_image_path)
|
| 38 |
+
|
| 39 |
+
if downloaded_path and os.path.exists(downloaded_path):
|
| 40 |
+
download_time = asyncio.get_running_loop().time() - download_start_time
|
| 41 |
+
logger.info(f"Photo downloaded to '{downloaded_path}' in {download_time:.2f}s.")
|
| 42 |
+
temp_user_image_path = downloaded_path
|
| 43 |
+
file_downloaded = True
|
| 44 |
+
else:
|
| 45 |
+
logger.error(f"Download failed or file not found: '{temp_user_image_path}'. Path: {downloaded_path}")
|
| 46 |
+
await message.reply_text("β Internal error after download attempt.")
|
| 47 |
+
return
|
| 48 |
+
except FloodWait as e:
|
| 49 |
+
logger.warning(f"Flood wait: {e.value}s during download (msg_id={message_id}).")
|
| 50 |
+
await asyncio.sleep(e.value + 2)
|
| 51 |
+
await message.reply_text(f"β³ Telegram limits hit. Wait {e.value}s & try again.")
|
| 52 |
+
return
|
| 53 |
+
except RPCError as e:
|
| 54 |
+
logger.error(f"RPC error downloading photo (msg_id={message_id}): {e}", exc_info=True)
|
| 55 |
+
await message.reply_text("β Telegram API error downloading image.")
|
| 56 |
+
return
|
| 57 |
+
except Exception as e:
|
| 58 |
+
logger.error(f"Unexpected error downloading photo (msg_id={message_id}): {e}", exc_info=True)
|
| 59 |
+
await message.reply_text("β Unexpected error downloading image.")
|
| 60 |
+
return
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
processing_status_message = await message.reply_text("β³ Processing your image...", quote=True)
|
| 64 |
+
except Exception as e: logger.warning(f"Could not send 'Processing...' message: {e}")
|
| 65 |
+
|
| 66 |
+
message_to_delete_id = processing_status_message.id if processing_status_message else None
|
| 67 |
+
loop = asyncio.get_running_loop()
|
| 68 |
+
generated_images: List[str] = []
|
| 69 |
+
processing_failed = False
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
logger.info(f"Submitting image processing for '{os.path.basename(temp_user_image_path)}'")
|
| 73 |
+
generated_images = await loop.run_in_executor(
|
| 74 |
+
executor, process_images_sync, temp_user_image_path, caption
|
| 75 |
+
)
|
| 76 |
+
except Exception as e:
|
| 77 |
+
processing_failed = True
|
| 78 |
+
logger.error(f"Error during image processing executor call: {e}", exc_info=True)
|
| 79 |
+
error_message = "β Unexpected error during processing."
|
| 80 |
+
if message_to_delete_id:
|
| 81 |
+
try: await client.edit_message_text(chat_id, message_to_delete_id, error_message)
|
| 82 |
+
except Exception as edit_e: logger.warning(f"Could not edit status msg: {edit_e}")
|
| 83 |
+
message_to_delete_id = None
|
| 84 |
+
else: await message.reply_text(error_message)
|
| 85 |
+
|
| 86 |
+
if message_to_delete_id:
|
| 87 |
+
try: await client.delete_messages(chat_id, message_to_delete_id)
|
| 88 |
+
except Exception as del_e: logger.warning(f"Could not delete status msg: {del_e}")
|
| 89 |
+
|
| 90 |
+
if not processing_failed:
|
| 91 |
+
if not generated_images:
|
| 92 |
+
await message.reply_text("π No styled images generated. Check templates?")
|
| 93 |
+
else:
|
| 94 |
+
logger.info(f"Sending {len(generated_images)} images for message {message_id}.")
|
| 95 |
+
for i, img_path in enumerate(generated_images):
|
| 96 |
+
if not os.path.exists(img_path): continue
|
| 97 |
+
caption_text = f"Style {i+1}" if len(generated_images) > 1 else "πΌοΈ Styled image:"
|
| 98 |
+
try:
|
| 99 |
+
await message.reply_photo(photo=img_path, caption=caption_text, quote=True)
|
| 100 |
+
except Exception as e: logger.error(f"Error sending photo '{os.path.basename(img_path)}': {e}", exc_info=True)
|
| 101 |
+
finally:
|
| 102 |
+
try:
|
| 103 |
+
if os.path.exists(img_path): os.remove(img_path)
|
| 104 |
+
except OSError as e: logger.error(f"Error deleting file '{img_path}': {e}")
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
if file_downloaded and os.path.exists(temp_user_image_path):
|
| 108 |
+
os.remove(temp_user_image_path)
|
| 109 |
+
except OSError as e: logger.error(f"Error cleaning user image '{temp_user_image_path}': {e}")
|
| 110 |
+
|
| 111 |
+
def register_handlers(app: Client):
|
| 112 |
+
admin_photo_filter = filters.photo & filters.caption & filters.private & is_admin
|
| 113 |
+
app.add_handler(MessageHandler(handle_photo_message_impl, filters=admin_photo_filter))
|
| 114 |
+
logger.info("Registered admin photo handler for bot.")
|