Files
tg_loader/web/utils/bot_client.py
2025-12-04 00:12:56 +03:00

73 lines
2.8 KiB
Python

"""
Utilities for interacting with bot from web interface
"""
import logging
from typing import Optional
from bot.modules.task_scheduler.executor import get_app_client
logger = logging.getLogger(__name__)
async def send_otp_to_user(user_id: int, code: str) -> bool:
"""
Send OTP code to user via Telegram bot
Args:
user_id: User ID
code: OTP code
Returns:
True if successfully sent, False otherwise
"""
try:
app_client = get_app_client()
if not app_client:
logger.warning(f"Bot client not available for sending OTP to user {user_id}")
return False
# Check that client is started and connected
try:
if not hasattr(app_client, 'is_connected') or not app_client.is_connected:
logger.warning(f"Bot client not connected for sending OTP to user {user_id}")
return False
except Exception as check_error:
logger.warning(f"Failed to check bot connection status: {check_error}")
# Continue sending attempt, client might be working
from shared.config import settings
# Form URL for web interface
if settings.WEB_HOST == "0.0.0.0":
login_url = f"localhost:{settings.WEB_PORT}"
else:
login_url = f"{settings.WEB_HOST}:{settings.WEB_PORT}"
message = (
f"🔐 **Ваш код для входа в веб-интерфейс:**\n\n"
f"**`{code}`**\n\n"
f"⏰ Код действителен 10 минут\n\n"
f"🌐 Перейдите на http://{login_url}/admin/login и введите этот код"
)
try:
# Try to send message
result = await app_client.send_message(user_id, message)
logger.info(f"OTP code successfully sent to user {user_id}, message_id: {result.id if result else 'unknown'}")
return True
except Exception as send_error:
error_msg = str(send_error)
logger.error(f"Error sending message to user {user_id}: {error_msg}", exc_info=True)
# Check error type for more informative message
if "chat not found" in error_msg.lower() or "user not found" in error_msg.lower():
logger.error(f"User {user_id} not found or hasn't started dialog with bot")
elif "flood" in error_msg.lower():
logger.error(f"Message sending rate limit exceeded for user {user_id}")
elif "unauthorized" in error_msg.lower():
logger.error(f"Bot not authorized or stopped")
return False
except Exception as e:
logger.error(f"Critical error sending OTP to user {user_id}: {e}", exc_info=True)
return False