"""Telegram message utilities.""" import asyncio import logging import os from typing import Optional from aiogram import Bot from aiogram.types import FSInputFile logger = logging.getLogger(__name__) async def send_message_safe( bot: Optional[Bot], chat_id: Optional[int], text: str, **kwargs ): if not bot or not chat_id: return None try: return await bot.send_message(chat_id=chat_id, text=text, **kwargs) except Exception as e: logger.error(f"Failed to send message: {e}") return None async def send_visit_result( bot: Optional[Bot], chat_id: int, visit_num: int, result: dict, delay: int, reading: int, successful: int, failed: int ) -> None: """ Send visit result with optional screenshot. Args: bot: Bot instance chat_id: Target chat ID visit_num: Visit number result: Visit result dictionary delay: Next visit delay reading: Reading time successful: Count of successful visits failed: Count of failed visits """ if not bot: return try: text = ( f"{'✅' if result['success'] else '❌'} **Посещение {visit_num}**\n" f"🌐 `{result.get('final_url', 'N/A')[:60]}`\n" f"📖 Чтение: {reading}с | След. через: {delay}с\n" f"📊 Успешно: {successful} | Ошибок: {failed}" ) screenshot_path = result.get('screenshot_path') if screenshot_path and await asyncio.to_thread(os.path.exists, screenshot_path): photo = FSInputFile(screenshot_path) await bot.send_photo(chat_id=chat_id, photo=photo, caption=text) else: await bot.send_message(chat_id=chat_id, text=text) except Exception as e: logger.error(f"Failed to send visit result: {e}") try: await bot.send_message(chat_id=chat_id, text=text) except Exception as e2: logger.warning(f"Fallback send failed: {e2}")