83 lines
2.2 KiB
Python
83 lines
2.2 KiB
Python
"""Telegram message utilities."""
|
||
|
||
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
|
||
) -> None:
|
||
"""
|
||
Safely send message to Telegram.
|
||
|
||
Args:
|
||
bot: Bot instance
|
||
chat_id: Target chat ID
|
||
text: Message text
|
||
**kwargs: Additional arguments for send_message
|
||
"""
|
||
if not bot or not chat_id:
|
||
return
|
||
|
||
try:
|
||
await bot.send_message(chat_id=chat_id, text=text, **kwargs)
|
||
except Exception as e:
|
||
logger.error(f"Failed to send message: {e}")
|
||
|
||
|
||
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 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}") |