Spaces:
Runtime error
Runtime error
Delete main.py
Browse files
main.py
DELETED
|
@@ -1,1194 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import asyncio
|
| 3 |
-
import logging
|
| 4 |
-
from typing import Optional, List
|
| 5 |
-
from contextlib import asynccontextmanager
|
| 6 |
-
from functools import wraps
|
| 7 |
-
|
| 8 |
-
from fastapi import FastAPI, HTTPException, Response
|
| 9 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
-
from pydantic import BaseModel
|
| 11 |
-
|
| 12 |
-
from dotenv import load_dotenv
|
| 13 |
-
from supabase import create_client, Client
|
| 14 |
-
from postgrest.exceptions import APIError as SupabaseAPIError
|
| 15 |
-
|
| 16 |
-
from aiogram import Bot, Dispatcher, F
|
| 17 |
-
from aiogram.types import Update, Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery, LabeledPrice, PreCheckoutQuery, ContentType
|
| 18 |
-
from aiogram.filters import CommandStart, CommandObject, Command
|
| 19 |
-
from aiogram.fsm.state import State, StatesGroup
|
| 20 |
-
from aiogram.fsm.context import FSMContext
|
| 21 |
-
from aiogram.client.default import DefaultBotProperties
|
| 22 |
-
from aiogram.client.session.aiohttp import AiohttpSession
|
| 23 |
-
from aiogram.exceptions import TelegramRetryAfter, TelegramAPIError
|
| 24 |
-
import aiohttp
|
| 25 |
-
|
| 26 |
-
# --- LOGGING CONFIGURATION ---
|
| 27 |
-
logging.basicConfig(
|
| 28 |
-
level=logging.INFO,
|
| 29 |
-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 30 |
-
)
|
| 31 |
-
logger = logging.getLogger(__name__)
|
| 32 |
-
|
| 33 |
-
# --- CONFIGURATION ---
|
| 34 |
-
load_dotenv()
|
| 35 |
-
BOT_TOKEN = os.getenv("BOT_TOKEN")
|
| 36 |
-
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
| 37 |
-
SUPABASE_KEY = os.getenv("SUPABASE_KEY")
|
| 38 |
-
WEBHOOK_URL = os.getenv("WEBHOOK_URL")
|
| 39 |
-
ADMIN_USERNAME = "astermaneiro"
|
| 40 |
-
ADMIN2_USERNAME = "genxcid21"
|
| 41 |
-
|
| 42 |
-
# Validate configuration
|
| 43 |
-
if not BOT_TOKEN:
|
| 44 |
-
logger.error("❌ BOT_TOKEN not found in environment variables!")
|
| 45 |
-
if not SUPABASE_URL or not SUPABASE_KEY:
|
| 46 |
-
logger.error("❌ Supabase credentials not found!")
|
| 47 |
-
|
| 48 |
-
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 49 |
-
|
| 50 |
-
# Bot will be initialized in lifespan
|
| 51 |
-
bot: Bot = None
|
| 52 |
-
dp = Dispatcher()
|
| 53 |
-
|
| 54 |
-
# --- RETRY DECORATOR FOR SUPABASE ---
|
| 55 |
-
def retry_supabase(max_attempts=3, delay=1.0):
|
| 56 |
-
"""Retry decorator for Supabase operations with exponential backoff."""
|
| 57 |
-
def decorator(func):
|
| 58 |
-
@wraps(func)
|
| 59 |
-
async def wrapper(*args, **kwargs):
|
| 60 |
-
last_exception = None
|
| 61 |
-
for attempt in range(max_attempts):
|
| 62 |
-
try:
|
| 63 |
-
return await func(*args, **kwargs)
|
| 64 |
-
except (SupabaseAPIError, aiohttp.ClientError) as e:
|
| 65 |
-
last_exception = e
|
| 66 |
-
logger.warning(f"Attempt {attempt + 1}/{max_attempts} failed: {e}")
|
| 67 |
-
if attempt < max_attempts - 1:
|
| 68 |
-
await asyncio.sleep(delay * (2 ** attempt))
|
| 69 |
-
logger.error(f"All {max_attempts} attempts failed for {func.__name__}")
|
| 70 |
-
raise last_exception
|
| 71 |
-
return wrapper
|
| 72 |
-
return decorator
|
| 73 |
-
|
| 74 |
-
# --- FSM STATES ---
|
| 75 |
-
|
| 76 |
-
class SupportReply(StatesGroup):
|
| 77 |
-
waiting_for_reply = State()
|
| 78 |
-
|
| 79 |
-
# --- TEMPLATES ---
|
| 80 |
-
|
| 81 |
-
SUPPORT_TEMPLATES = {
|
| 82 |
-
"bug": "Спасибо за сообщение о баге! Мы обязательно рассмотрим его и исправим в ближайшее время.",
|
| 83 |
-
"complaint": "Спасибо за обратную связь! Мы рассмотрим вашу жалобу и примем необходимые меры.",
|
| 84 |
-
"suggestion": "Спасибо за предложение! Мы обязательно рассмотрим его и учтём в будущей разработке."
|
| 85 |
-
}
|
| 86 |
-
|
| 87 |
-
# --- ADMIN HELPERS ---
|
| 88 |
-
|
| 89 |
-
def get_admin_id(username: str) -> Optional[int]:
|
| 90 |
-
"""Get admin ID by username."""
|
| 91 |
-
try:
|
| 92 |
-
# Remove @ if present
|
| 93 |
-
clean_username = username.lstrip('@')
|
| 94 |
-
res = supabase.table("users").select("id").eq("username", clean_username).execute()
|
| 95 |
-
if res.data and len(res.data) > 0:
|
| 96 |
-
return res.data[0]['id']
|
| 97 |
-
print(f"Admin '{username}' not found in database")
|
| 98 |
-
return None
|
| 99 |
-
except Exception as e:
|
| 100 |
-
print(f"Error getting admin ID for '{username}': {e}")
|
| 101 |
-
return None
|
| 102 |
-
|
| 103 |
-
def is_main_admin(user_id: int) -> bool:
|
| 104 |
-
"""Check if user is main admin."""
|
| 105 |
-
admin_id = get_admin_id(ADMIN_USERNAME)
|
| 106 |
-
return user_id == admin_id
|
| 107 |
-
|
| 108 |
-
def is_second_admin(user_id: int) -> bool:
|
| 109 |
-
"""Check if user is second admin."""
|
| 110 |
-
admin2_id = get_admin_id(ADMIN2_USERNAME)
|
| 111 |
-
return user_id == admin2_id
|
| 112 |
-
|
| 113 |
-
def is_any_admin(user_id: int) -> bool:
|
| 114 |
-
"""Check if user is any admin."""
|
| 115 |
-
return is_main_admin(user_id) or is_second_admin(user_id)
|
| 116 |
-
|
| 117 |
-
def can_manage_support(user_id: int) -> bool:
|
| 118 |
-
"""Check if user can manage support (main admin always can, second admin if not blocked)."""
|
| 119 |
-
if is_main_admin(user_id):
|
| 120 |
-
return True
|
| 121 |
-
if is_second_admin(user_id):
|
| 122 |
-
# Check if second admin is blocked from support
|
| 123 |
-
res = supabase.table("users").select("support_blocked").eq("id", user_id).single().execute()
|
| 124 |
-
return not (res.data and res.data.get('support_blocked', False))
|
| 125 |
-
return False
|
| 126 |
-
|
| 127 |
-
# --- HELPER FUNCTIONS ---
|
| 128 |
-
|
| 129 |
-
def check_is_blocked(user_id: int):
|
| 130 |
-
try:
|
| 131 |
-
res = supabase.table("users").select("username, is_blocked").eq("id", user_id).single().execute()
|
| 132 |
-
if res.data:
|
| 133 |
-
# Admin cannot be blocked
|
| 134 |
-
if res.data['username'] == ADMIN_USERNAME: return
|
| 135 |
-
if res.data.get('is_blocked', False):
|
| 136 |
-
raise HTTPException(status_code=403, detail="USER_BLOCKED")
|
| 137 |
-
except HTTPException:
|
| 138 |
-
raise
|
| 139 |
-
except:
|
| 140 |
-
pass
|
| 141 |
-
|
| 142 |
-
def get_folder_tree_text(user_id, folder_id, indent=0):
|
| 143 |
-
items = supabase.table("items").select("*").eq("user_id", user_id).eq("parent_id", folder_id).execute().data
|
| 144 |
-
items.sort(key=lambda x: (x['type'] != 'folder', x['name']))
|
| 145 |
-
|
| 146 |
-
text = ""
|
| 147 |
-
for i, item in enumerate(items, 1):
|
| 148 |
-
prefix = " " * indent
|
| 149 |
-
if item['type'] == 'folder':
|
| 150 |
-
text += f"{prefix}{i}. Папка «{item['name']}»:\n"
|
| 151 |
-
text += get_folder_tree_text(user_id, item['id'], indent + 1)
|
| 152 |
-
else:
|
| 153 |
-
text += f"{prefix}{i}. {item['name']}\n"
|
| 154 |
-
return text
|
| 155 |
-
|
| 156 |
-
async def copy_folder_recursive(source_folder_id, target_user_id, target_parent_id=None):
|
| 157 |
-
"""Recursively copies a folder to another user."""
|
| 158 |
-
folder_res = supabase.table("items").select("*").eq("id", source_folder_id).single().execute()
|
| 159 |
-
if not folder_res.data: return
|
| 160 |
-
|
| 161 |
-
source_folder = folder_res.data
|
| 162 |
-
new_folder_data = {
|
| 163 |
-
"user_id": target_user_id,
|
| 164 |
-
"name": source_folder['name'],
|
| 165 |
-
"type": "folder",
|
| 166 |
-
"parent_id": target_parent_id
|
| 167 |
-
}
|
| 168 |
-
new_folder = supabase.table("items").insert(new_folder_data).execute().data[0]
|
| 169 |
-
|
| 170 |
-
items = supabase.table("items").select("*").eq("parent_id", source_folder_id).execute().data
|
| 171 |
-
|
| 172 |
-
for item in items:
|
| 173 |
-
if item['type'] == 'folder':
|
| 174 |
-
await copy_folder_recursive(item['id'], target_user_id, new_folder['id'])
|
| 175 |
-
else:
|
| 176 |
-
new_file = {
|
| 177 |
-
"user_id": target_user_id,
|
| 178 |
-
"name": item['name'],
|
| 179 |
-
"type": "file",
|
| 180 |
-
"file_id": item['file_id'],
|
| 181 |
-
"size": item['size'],
|
| 182 |
-
"parent_id": new_folder['id']
|
| 183 |
-
}
|
| 184 |
-
supabase.table("items").insert(new_file).execute()
|
| 185 |
-
|
| 186 |
-
async def send_folder_contents(chat_id, folder_id):
|
| 187 |
-
"""Recursively sends files to a chat."""
|
| 188 |
-
items = supabase.table("items").select("*").eq("parent_id", folder_id).execute().data
|
| 189 |
-
items.sort(key=lambda x: (x['type'] != 'folder', x['name']))
|
| 190 |
-
|
| 191 |
-
for item in items:
|
| 192 |
-
if item['type'] == 'folder':
|
| 193 |
-
await bot.send_message(chat_id, f"📂 <b>{item['name']}</b>", parse_mode="HTML")
|
| 194 |
-
await send_folder_contents(chat_id, item['id'])
|
| 195 |
-
else:
|
| 196 |
-
try:
|
| 197 |
-
if item['name'].lower().endswith(('.jpg', '.jpeg', '.png')):
|
| 198 |
-
await bot.send_photo(chat_id, item['file_id'], caption=item['name'])
|
| 199 |
-
elif item['name'].lower().endswith(('.mp4', '.mov')):
|
| 200 |
-
await bot.send_video(chat_id, item['file_id'], caption=item['name'])
|
| 201 |
-
else:
|
| 202 |
-
await bot.send_document(chat_id, item['file_id'], caption=item['name'])
|
| 203 |
-
await asyncio.sleep(0.3) # Anti-flood delay
|
| 204 |
-
except:
|
| 205 |
-
pass
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
# --- PAYMENT LOGIC (STARS) ---
|
| 209 |
-
|
| 210 |
-
@dp.pre_checkout_query()
|
| 211 |
-
async def process_pre_checkout_query(pre_checkout_query: PreCheckoutQuery):
|
| 212 |
-
await bot.answer_pre_checkout_query(pre_checkout_query.id, ok=True)
|
| 213 |
-
|
| 214 |
-
@dp.message(F.content_type == ContentType.SUCCESSFUL_PAYMENT)
|
| 215 |
-
async def successful_payment(message: Message):
|
| 216 |
-
payment_info = message.successful_payment
|
| 217 |
-
await message.answer(f"⭐ Спасибо за поддержку! Получено звёзд: {payment_info.total_amount}")
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
# --- BOT HANDLERS ---
|
| 221 |
-
|
| 222 |
-
@dp.message(CommandStart())
|
| 223 |
-
async def command_start(message: Message, command: CommandObject):
|
| 224 |
-
user_id = message.from_user.id
|
| 225 |
-
|
| 226 |
-
# Logic to fix missing usernames
|
| 227 |
-
username = message.from_user.username
|
| 228 |
-
if not username:
|
| 229 |
-
username = message.from_user.first_name or "User"
|
| 230 |
-
|
| 231 |
-
try:
|
| 232 |
-
supabase.table("users").upsert({"id": user_id, "username": username}).execute()
|
| 233 |
-
except Exception:
|
| 234 |
-
pass
|
| 235 |
-
|
| 236 |
-
args = command.args
|
| 237 |
-
|
| 238 |
-
# 1. FILE SHARING
|
| 239 |
-
if args and args.startswith("file_"):
|
| 240 |
-
processing_message = await message.answer("⏳")
|
| 241 |
-
requested_uuid = args.replace("file_", "")
|
| 242 |
-
try:
|
| 243 |
-
res = supabase.table("items").select("*").eq("id", requested_uuid).limit(1).execute()
|
| 244 |
-
if res.data:
|
| 245 |
-
file_data = res.data[0]
|
| 246 |
-
await processing_message.edit_text(f"📂 Вам отправили файл: <b>{file_data['name']}</b>", parse_mode="HTML")
|
| 247 |
-
if file_data['type'] == 'folder':
|
| 248 |
-
await message.answer("Это папка. Используйте ссылку для папки.")
|
| 249 |
-
return
|
| 250 |
-
try:
|
| 251 |
-
f_id = file_data['file_id']
|
| 252 |
-
name = file_data['name'].lower()
|
| 253 |
-
if name.endswith(('.jpg', '.jpeg', '.png')):
|
| 254 |
-
await message.answer_photo(f_id)
|
| 255 |
-
elif name.endswith(('.mp4', '.mov')):
|
| 256 |
-
await message.answer_video(f_id)
|
| 257 |
-
else:
|
| 258 |
-
await message.answer_document(f_id)
|
| 259 |
-
except Exception:
|
| 260 |
-
await message.answer("Ошибка при отправке файла.")
|
| 261 |
-
else:
|
| 262 |
-
await processing_message.edit_text("Файл не найден.")
|
| 263 |
-
except Exception:
|
| 264 |
-
await processing_message.edit_text("Некорректная ссылка.")
|
| 265 |
-
|
| 266 |
-
# 2. FOLDER SHARING
|
| 267 |
-
elif args and args.startswith("folder_"):
|
| 268 |
-
processing_message = await message.answer("⏳")
|
| 269 |
-
folder_uuid = args.replace("folder_", "")
|
| 270 |
-
try:
|
| 271 |
-
res = supabase.table("items").select("*").eq("id", folder_uuid).eq("type", "folder").limit(1).execute()
|
| 272 |
-
if res.data:
|
| 273 |
-
folder_data = res.data[0]
|
| 274 |
-
kb = InlineKeyboardMarkup(inline_keyboard=[
|
| 275 |
-
[InlineKeyboardButton(text="☁️ Сохранить в облако", callback_data=f"save_{folder_uuid}")],
|
| 276 |
-
[InlineKeyboardButton(text="📥 Выгрузить в чат", callback_data=f"send_{folder_uuid}")],
|
| 277 |
-
[InlineKeyboardButton(text="👀 Посмотреть содержимое", callback_data=f"view_{folder_uuid}")]
|
| 278 |
-
])
|
| 279 |
-
await processing_message.edit_text(
|
| 280 |
-
f"📁 Вам отправили папку «<b>{folder_data['name']}</b>» с файлами.",
|
| 281 |
-
reply_markup=kb,
|
| 282 |
-
parse_mode="HTML"
|
| 283 |
-
)
|
| 284 |
-
else:
|
| 285 |
-
await processing_message.edit_text("Папка не найдена или удалена.")
|
| 286 |
-
except Exception:
|
| 287 |
-
await processing_message.edit_text("Некорректная ссылка на папку.")
|
| 288 |
-
|
| 289 |
-
else:
|
| 290 |
-
await message.answer("Привет! Отправь мне файлы для сохранения или открой Mini App.",
|
| 291 |
-
reply_markup=InlineKeyboardMarkup(inline_keyboard=[
|
| 292 |
-
[InlineKeyboardButton(text="Открыть Tg Cloud", web_app={"url": "https://tg-cloud-frontend.vercel.app"})]
|
| 293 |
-
]))
|
| 294 |
-
|
| 295 |
-
@dp.callback_query(F.data.startswith("save_"))
|
| 296 |
-
async def cb_save_folder(callback: CallbackQuery):
|
| 297 |
-
folder_id = callback.data.split("_")[1]
|
| 298 |
-
user_id = callback.from_user.id
|
| 299 |
-
await callback.answer("Начинаю копирование...")
|
| 300 |
-
try:
|
| 301 |
-
await copy_folder_recursive(folder_id, user_id, None)
|
| 302 |
-
await callback.message.answer("✅ Папка успешно сохранена в ваше облако!")
|
| 303 |
-
except:
|
| 304 |
-
await callback.message.answer("Ошибка при копировании.")
|
| 305 |
-
|
| 306 |
-
@dp.callback_query(F.data.startswith("send_"))
|
| 307 |
-
async def cb_send_folder(callback: CallbackQuery):
|
| 308 |
-
folder_id = callback.data.split("_")[1]
|
| 309 |
-
await callback.answer("Начинаю отправку файлов...")
|
| 310 |
-
await callback.message.answer("⏳ Выгрузка файлов началась...")
|
| 311 |
-
try:
|
| 312 |
-
await send_folder_contents(callback.from_user.id, folder_id)
|
| 313 |
-
await callback.message.answer("✅ Выгрузка завершена.")
|
| 314 |
-
except:
|
| 315 |
-
await callback.message.answer("Ошибка при отправке.")
|
| 316 |
-
|
| 317 |
-
@dp.callback_query(F.data.startswith("view_"))
|
| 318 |
-
async def cb_view_folder(callback: CallbackQuery):
|
| 319 |
-
folder_id = callback.data.split("_")[1]
|
| 320 |
-
await callback.answer()
|
| 321 |
-
|
| 322 |
-
# Get folder info for the owner's user_id
|
| 323 |
-
folder_res = supabase.table("items").select("user_id, name").eq("id", folder_id).single().execute()
|
| 324 |
-
if not folder_res.data:
|
| 325 |
-
await callback.message.answer("Папка не найдена.")
|
| 326 |
-
return
|
| 327 |
-
|
| 328 |
-
tree_text = get_folder_tree_text(folder_res.data['user_id'], folder_id, indent=0)
|
| 329 |
-
msg_text = f"Папка «{folder_res.data['name']}»:\n\n{tree_text}" if tree_text else f"Папка «{folder_res.data['name']}» пуста."
|
| 330 |
-
|
| 331 |
-
if len(msg_text) > 4000: msg_text = msg_text[:4000] + "\n..."
|
| 332 |
-
await callback.message.answer(msg_text)
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
# --- SUPPORT CALLBACKS ---
|
| 336 |
-
|
| 337 |
-
@dp.callback_query(F.data.startswith("rt_"))
|
| 338 |
-
async def cb_reply_template(callback: CallbackQuery, state: FSMContext):
|
| 339 |
-
"""Handle template reply button click."""
|
| 340 |
-
await callback.answer()
|
| 341 |
-
|
| 342 |
-
admin_id = callback.from_user.id
|
| 343 |
-
admin_username = callback.from_user.username or f"ID:{admin_id}"
|
| 344 |
-
|
| 345 |
-
# Parse callback data: rt_{user_id}_{type}
|
| 346 |
-
parts = callback.data.split("_")
|
| 347 |
-
if len(parts) < 3:
|
| 348 |
-
await callback.message.answer("❌ Ошибка обработки запроса")
|
| 349 |
-
return
|
| 350 |
-
|
| 351 |
-
try:
|
| 352 |
-
user_id = int(parts[1])
|
| 353 |
-
support_type = parts[2] if len(parts) > 2 else "complaint"
|
| 354 |
-
except ValueError:
|
| 355 |
-
await callback.message.answer("❌ Ошибка обработки запроса")
|
| 356 |
-
return
|
| 357 |
-
|
| 358 |
-
# Get template
|
| 359 |
-
template = SUPPORT_TEMPLATES.get(support_type, "Спасибо за обратную связь!")
|
| 360 |
-
|
| 361 |
-
# Send template to user with admin signature
|
| 362 |
-
signature = f"\n\n<i>— @{admin_username}</i>" if is_second_admin(admin_id) else ""
|
| 363 |
-
message_text = f"📬 <b>Ответ от поддержки</b>:\n\n{template}{signature}"
|
| 364 |
-
|
| 365 |
-
try:
|
| 366 |
-
await bot.send_message(user_id, message_text, parse_mode="HTML")
|
| 367 |
-
await callback.message.answer(f"✅ Шаблон отправлен пользователю ID: {user_id}")
|
| 368 |
-
|
| 369 |
-
# Notify main admin if second admin responded
|
| 370 |
-
if is_second_admin(admin_id):
|
| 371 |
-
main_admin_id = get_admin_id(ADMIN_USERNAME)
|
| 372 |
-
if main_admin_id:
|
| 373 |
-
await bot.send_message(
|
| 374 |
-
main_admin_id,
|
| 375 |
-
f"📋 <b>Ответ от @{admin_username}</b>:\n\n"
|
| 376 |
-
f"Пользователю ID:{user_id} отправлен шаблон: <i>{support_type}</i>",
|
| 377 |
-
parse_mode="HTML"
|
| 378 |
-
)
|
| 379 |
-
except Exception as e:
|
| 380 |
-
await callback.message.answer(f"❌ Ошибка отправки: {e}")
|
| 381 |
-
|
| 382 |
-
await state.clear()
|
| 383 |
-
|
| 384 |
-
@dp.callback_query(F.data.startswith("rc_"))
|
| 385 |
-
async def cb_reply_custom(callback: CallbackQuery, state: FSMContext):
|
| 386 |
-
"""Handle custom reply button click - set state for waiting admin message."""
|
| 387 |
-
await callback.answer()
|
| 388 |
-
|
| 389 |
-
admin_id = callback.from_user.id
|
| 390 |
-
admin_username = callback.from_user.username or f"ID:{admin_id}"
|
| 391 |
-
|
| 392 |
-
# Parse callback data: rc_{user_id}
|
| 393 |
-
parts = callback.data.split("_")
|
| 394 |
-
if len(parts) < 2:
|
| 395 |
-
await callback.message.answer("❌ Ошибка обработки запроса")
|
| 396 |
-
return
|
| 397 |
-
|
| 398 |
-
try:
|
| 399 |
-
target_user_id = int(parts[1])
|
| 400 |
-
except ValueError:
|
| 401 |
-
await callback.message.answer("❌ Ошибка обработки запроса")
|
| 402 |
-
return
|
| 403 |
-
|
| 404 |
-
# Store target user and admin info in FSM state
|
| 405 |
-
await state.update_data(target_user_id=target_user_id, admin_username=admin_username, admin_id=admin_id)
|
| 406 |
-
await state.set_state(SupportReply.waiting_for_reply)
|
| 407 |
-
|
| 408 |
-
await callback.message.answer(
|
| 409 |
-
"✏️ <b>Режим ответа пользователю</b>\n\n"
|
| 410 |
-
f"Отправьте сообщение, и оно будет переслано пользователю ID: {target_user_id}\n"
|
| 411 |
-
"Для отмены отправьте /cancel",
|
| 412 |
-
parse_mode="HTML"
|
| 413 |
-
)
|
| 414 |
-
|
| 415 |
-
@dp.message(SupportReply.waiting_for_reply)
|
| 416 |
-
async def handle_admin_reply(message: Message, state: FSMContext):
|
| 417 |
-
"""Handle admin's custom reply message."""
|
| 418 |
-
data = await state.get_data()
|
| 419 |
-
target_user_id = data.get("target_user_id")
|
| 420 |
-
admin_username = data.get("admin_username")
|
| 421 |
-
admin_id = data.get("admin_id")
|
| 422 |
-
|
| 423 |
-
if not target_user_id:
|
| 424 |
-
await message.answer("❌ Ошибка: пользователь не указан")
|
| 425 |
-
await state.clear()
|
| 426 |
-
return
|
| 427 |
-
|
| 428 |
-
# Copy the message to preserve all content (text, media, etc.)
|
| 429 |
-
try:
|
| 430 |
-
# Add signature if second admin
|
| 431 |
-
caption = "📬 <b>Ответ от поддержки</b>"
|
| 432 |
-
if is_second_admin(admin_id):
|
| 433 |
-
caption = f"📬 <b>Ответ от поддержки</b>\n<i>— @{admin_username}</i>"
|
| 434 |
-
|
| 435 |
-
await bot.copy_message(
|
| 436 |
-
chat_id=target_user_id,
|
| 437 |
-
from_chat_id=message.chat.id,
|
| 438 |
-
message_id=message.message_id,
|
| 439 |
-
caption=caption,
|
| 440 |
-
parse_mode="HTML"
|
| 441 |
-
)
|
| 442 |
-
await message.answer(f"✅ Сообщение отправлено пользователю ID: {target_user_id}")
|
| 443 |
-
|
| 444 |
-
# Notify main admin if second admin responded
|
| 445 |
-
if is_second_admin(admin_id):
|
| 446 |
-
main_admin_id = get_admin_id(ADMIN_USERNAME)
|
| 447 |
-
if main_admin_id:
|
| 448 |
-
await bot.send_message(
|
| 449 |
-
main_admin_id,
|
| 450 |
-
f"📋 <b>Ответ от @{admin_username}</b>:\n\n"
|
| 451 |
-
f"Пользователю ID:{target_user_id} отправлено сообщение:\n"
|
| 452 |
-
f"<blockquote>{message.text or '📎 Медиафайл'}</blockquote>",
|
| 453 |
-
parse_mode="HTML"
|
| 454 |
-
)
|
| 455 |
-
except Exception as e:
|
| 456 |
-
await message.answer(f"❌ Ошибка отправки: {e}")
|
| 457 |
-
|
| 458 |
-
await state.clear()
|
| 459 |
-
|
| 460 |
-
@dp.message(Command("cancel"))
|
| 461 |
-
async def cmd_cancel(message: Message, state: FSMContext):
|
| 462 |
-
"""Cancel current FSM state."""
|
| 463 |
-
await state.clear()
|
| 464 |
-
await message.answer("✅ Режим ответа отменён")
|
| 465 |
-
|
| 466 |
-
@dp.message(Command("reset_state"))
|
| 467 |
-
async def cmd_reset_state(message: Message, state: FSMContext):
|
| 468 |
-
"""Reset FSM state (useful if bot gets stuck)."""
|
| 469 |
-
await state.clear()
|
| 470 |
-
logger.info(f"FSM state reset for user {message.from_user.id}")
|
| 471 |
-
await message.answer("✅ Состояние сброшено. Попробуйте снова.")
|
| 472 |
-
|
| 473 |
-
@dp.message(Command("status"))
|
| 474 |
-
async def cmd_status(message: Message):
|
| 475 |
-
"""Check bot status and webhook info."""
|
| 476 |
-
status_message = await message.answer("⏳ Проверка статуса...")
|
| 477 |
-
|
| 478 |
-
try:
|
| 479 |
-
bot_info = await bot.get_me()
|
| 480 |
-
webhook_info = await bot.get_webhook_info()
|
| 481 |
-
|
| 482 |
-
status_text = (
|
| 483 |
-
f"🤖 <b>Бот:</b> @{bot_info.username}\n"
|
| 484 |
-
f"✅ <b>Статус:</b> Работает\n\n"
|
| 485 |
-
f"🔗 <b>Webhook:</b>\n"
|
| 486 |
-
f"URL: {webhook_info.url}\n"
|
| 487 |
-
f"Ошибок: {webhook_info.last_error_date or 'Нет'}\n"
|
| 488 |
-
f"Ожидает: {webhook_info.pending_update_count}\n"
|
| 489 |
-
)
|
| 490 |
-
|
| 491 |
-
await status_message.edit_text(status_text, parse_mode="HTML")
|
| 492 |
-
except Exception as e:
|
| 493 |
-
logger.error(f"Status check failed: {e}")
|
| 494 |
-
await status_message.edit_text(f"❌ Ошибка проверки статуса: {e}")
|
| 495 |
-
|
| 496 |
-
# --- ADMIN MANAGEMENT COMMANDS ---
|
| 497 |
-
|
| 498 |
-
@dp.message(Command("support_admins"))
|
| 499 |
-
async def cmd_support_admins(message: Message):
|
| 500 |
-
"""Show support admins status (main admin only)."""
|
| 501 |
-
user_id = message.from_user.id
|
| 502 |
-
|
| 503 |
-
if not is_main_admin(user_id):
|
| 504 |
-
return
|
| 505 |
-
|
| 506 |
-
admin2_id = get_admin_id(ADMIN2_USERNAME)
|
| 507 |
-
if not admin2_id:
|
| 508 |
-
await message.answer("❌ Второй админ ещё не зарегистрирован в базе")
|
| 509 |
-
return
|
| 510 |
-
|
| 511 |
-
# Get status
|
| 512 |
-
res = supabase.table("users").select("support_blocked").eq("id", admin2_id).single().execute()
|
| 513 |
-
is_blocked = res.data.get('support_blocked', False) if res.data else False
|
| 514 |
-
|
| 515 |
-
status_text = "❌ Заблокирован" if is_blocked else "✅ Активен"
|
| 516 |
-
|
| 517 |
-
keyboard = InlineKeyboardMarkup(inline_keyboard=[
|
| 518 |
-
[InlineKeyboardButton(
|
| 519 |
-
text="🔒 Заблокировать" if not is_blocked else "🔓 Разблокировать",
|
| 520 |
-
callback_data=f"toggle_support_{admin2_id}"
|
| 521 |
-
)]
|
| 522 |
-
])
|
| 523 |
-
|
| 524 |
-
await message.answer(
|
| 525 |
-
f"📋 <b>Управление доступом к поддержке</b>\n\n"
|
| 526 |
-
f"Второй админ: @{ADMIN2_USERNAME}\n"
|
| 527 |
-
f"Статус: {status_text}\n\n"
|
| 528 |
-
f"Нажми кнопку, чтобы изменить статус",
|
| 529 |
-
parse_mode="HTML",
|
| 530 |
-
reply_markup=keyboard
|
| 531 |
-
)
|
| 532 |
-
|
| 533 |
-
@dp.callback_query(F.data.startswith("toggle_support_"))
|
| 534 |
-
async def cb_toggle_support_access(callback: CallbackQuery):
|
| 535 |
-
"""Toggle second admin support access."""
|
| 536 |
-
admin_id = callback.from_user.id
|
| 537 |
-
|
| 538 |
-
if not is_main_admin(admin_id):
|
| 539 |
-
await callback.answer("❌ Доступ только для главного админа", show_alert=True)
|
| 540 |
-
return
|
| 541 |
-
|
| 542 |
-
parts = callback.data.split("_")
|
| 543 |
-
if len(parts) < 3:
|
| 544 |
-
await callback.answer("❌ Ошибка", show_alert=True)
|
| 545 |
-
return
|
| 546 |
-
|
| 547 |
-
try:
|
| 548 |
-
target_user_id = int(parts[2])
|
| 549 |
-
except ValueError:
|
| 550 |
-
await callback.answer("❌ Ошибка", show_alert=True)
|
| 551 |
-
return
|
| 552 |
-
|
| 553 |
-
# Get current status
|
| 554 |
-
res = supabase.table("users").select("support_blocked").eq("id", target_user_id).single().execute()
|
| 555 |
-
is_blocked = res.data.get('support_blocked', False) if res.data else False
|
| 556 |
-
new_status = not is_blocked
|
| 557 |
-
|
| 558 |
-
# Update
|
| 559 |
-
supabase.table("users").update({"support_blocked": new_status}).eq("id", target_user_id).execute()
|
| 560 |
-
|
| 561 |
-
status_text = "заблокирован" if new_status else "разблокирован"
|
| 562 |
-
await callback.answer(f"✅ Второй админ {status_text}", show_alert=True)
|
| 563 |
-
|
| 564 |
-
# Update message
|
| 565 |
-
new_status_text = "❌ Заблокирован" if new_status else "✅ Активен"
|
| 566 |
-
new_keyboard = InlineKeyboardMarkup(inline_keyboard=[
|
| 567 |
-
[InlineKeyboardButton(
|
| 568 |
-
text="🔒 Заблокировать" if not new_status else "🔓 Разблокировать",
|
| 569 |
-
callback_data=f"toggle_support_{target_user_id}"
|
| 570 |
-
)]
|
| 571 |
-
])
|
| 572 |
-
|
| 573 |
-
await callback.message.edit_text(
|
| 574 |
-
f"📋 <b>Управление доступом к поддержке</b>\n\n"
|
| 575 |
-
f"Второй админ: @{ADMIN2_USERNAME}\n"
|
| 576 |
-
f"Статус: {new_status_text}\n\n"
|
| 577 |
-
f"Нажми кнопку, чтобы изменить статус",
|
| 578 |
-
parse_mode="HTML",
|
| 579 |
-
reply_markup=new_keyboard
|
| 580 |
-
)
|
| 581 |
-
|
| 582 |
-
@dp.message(Command("notify_old_admin"))
|
| 583 |
-
async def cmd_notify_old_admin(message: Message):
|
| 584 |
-
"""Send notification to old admin Ginlys (main admin only)."""
|
| 585 |
-
user_id = message.from_user.id
|
| 586 |
-
|
| 587 |
-
if not is_main_admin(user_id):
|
| 588 |
-
return
|
| 589 |
-
|
| 590 |
-
old_admin_id = get_admin_id("Ginlys")
|
| 591 |
-
if not old_admin_id:
|
| 592 |
-
await message.answer("❌ Старый админ Ginlys не найден в базе")
|
| 593 |
-
return
|
| 594 |
-
|
| 595 |
-
notification_text = (
|
| 596 |
-
"Здравствуйте, Артур!\n\n"
|
| 597 |
-
"Данным сообщением уведомляем вас о том, что вам предоставлены п��ава администратора в системе Tg Cloud.\n\n"
|
| 598 |
-
"С этого момента вам доступен функционал обработки входящих запросов от пользователей. В вашу компетенцию входит:\n"
|
| 599 |
-
"• Рассмотрение и решение жалоб.\n"
|
| 600 |
-
"• Обработка технических отчетов о багах и ошибках.\n"
|
| 601 |
-
"• Рецензирование предложений по улучшению сервиса.\n\n"
|
| 602 |
-
"Желаем продуктивной работы. Команда Tg Cloud всегда на связи для уточнения рабочих вопросов."
|
| 603 |
-
)
|
| 604 |
-
|
| 605 |
-
try:
|
| 606 |
-
await bot.send_message(old_admin_id, notification_text)
|
| 607 |
-
await message.answer(f"✅ Сообщение отправлено пользователю ID: {old_admin_id}")
|
| 608 |
-
except Exception as e:
|
| 609 |
-
await message.answer(f"❌ Ошибка отправки: {e}")
|
| 610 |
-
|
| 611 |
-
@dp.message(Command("notify_new_admin"))
|
| 612 |
-
async def cmd_notify_new_admin(message: Message):
|
| 613 |
-
"""Send notification to new admin genxcid21 (main admin only)."""
|
| 614 |
-
user_id = message.from_user.id
|
| 615 |
-
|
| 616 |
-
if not is_main_admin(user_id):
|
| 617 |
-
return
|
| 618 |
-
|
| 619 |
-
new_admin_id = get_admin_id(ADMIN2_USERNAME)
|
| 620 |
-
if not new_admin_id:
|
| 621 |
-
await message.answer(f"❌ Новый админ {ADMIN2_USERNAME} не найден в базе")
|
| 622 |
-
return
|
| 623 |
-
|
| 624 |
-
notification_text = (
|
| 625 |
-
"Здравствуйте!\n\n"
|
| 626 |
-
"Данным сообщением уведомляем вас о том, что вам предоставлены права администратора в системе Tg Cloud.\n\n"
|
| 627 |
-
"С этого момента вам доступен функционал обработки входящих запросов от пользователей. В вашу компетенцию входит:\n"
|
| 628 |
-
"• Рассмотрение и решение жалоб.\n"
|
| 629 |
-
"• Обработка технических отчетов о багах и ошибках.\n"
|
| 630 |
-
"• Рецензирование предложений по улучшению сервиса.\n\n"
|
| 631 |
-
"Желаем продуктивной работы. Команда Tg Cloud всегда на связи для уточнения рабочих вопросов."
|
| 632 |
-
)
|
| 633 |
-
|
| 634 |
-
try:
|
| 635 |
-
await bot.send_message(new_admin_id, notification_text)
|
| 636 |
-
await message.answer(f"✅ Сообщение отправлено пользователю ID: {new_admin_id}")
|
| 637 |
-
except Exception as e:
|
| 638 |
-
await message.answer(f"❌ Ошибка отправки: {e}")
|
| 639 |
-
|
| 640 |
-
@dp.message(Command("help"))
|
| 641 |
-
async def cmd_help(message: Message):
|
| 642 |
-
"""Show available commands."""
|
| 643 |
-
user_id = message.from_user.id
|
| 644 |
-
is_main = is_main_admin(user_id)
|
| 645 |
-
|
| 646 |
-
commands = [
|
| 647 |
-
("/start", "Запустить бота / открыть Mini App"),
|
| 648 |
-
("/status", "🔍 Проверить статус бота и webhook"),
|
| 649 |
-
("/reset_state", "🔄 Сбросить зависшее состояние (если бот не отвечает)"),
|
| 650 |
-
]
|
| 651 |
-
|
| 652 |
-
if is_main:
|
| 653 |
-
commands.extend([
|
| 654 |
-
("/support_admins", "Управление доступом второго админа к поддержке"),
|
| 655 |
-
("/notify_new_admin", "Отправить уведомление новому админу"),
|
| 656 |
-
("/notify_old_admin", "Отправить уведомление старому админу"),
|
| 657 |
-
("/help", "Показать этот список команд"),
|
| 658 |
-
])
|
| 659 |
-
|
| 660 |
-
commands_text = "\n".join([f"<b>{cmd}</b> — {desc}" for cmd, desc in commands])
|
| 661 |
-
|
| 662 |
-
await message.answer(
|
| 663 |
-
f"📖 <b>Доступные команды</b>:\n\n{commands_text}",
|
| 664 |
-
parse_mode="HTML"
|
| 665 |
-
)
|
| 666 |
-
|
| 667 |
-
@dp.message(F.document | F.photo | F.video | F.audio)
|
| 668 |
-
async def handle_files(message: Message):
|
| 669 |
-
user_id = message.from_user.id
|
| 670 |
-
|
| 671 |
-
# Check for block
|
| 672 |
-
try: check_is_blocked(user_id)
|
| 673 |
-
except Exception:
|
| 674 |
-
await message.answer("⛔ Ваш аккаунт заблокирован администратором.")
|
| 675 |
-
return
|
| 676 |
-
|
| 677 |
-
file_id = None
|
| 678 |
-
file_name = "Без названия"
|
| 679 |
-
file_size = 0
|
| 680 |
-
thumbnail_id = None
|
| 681 |
-
|
| 682 |
-
if message.document:
|
| 683 |
-
file_id = message.document.file_id
|
| 684 |
-
file_name = message.document.file_name or "doc"
|
| 685 |
-
file_size = message.document.file_size
|
| 686 |
-
elif message.photo:
|
| 687 |
-
file_id = message.photo[-1].file_id
|
| 688 |
-
file_name = f"img_{int(message.date.timestamp())}.jpg"
|
| 689 |
-
file_size = message.photo[-1].file_size
|
| 690 |
-
elif message.video:
|
| 691 |
-
file_id = message.video.file_id
|
| 692 |
-
file_name = message.video.file_name or "video.mp4"
|
| 693 |
-
file_size = message.video.file_size
|
| 694 |
-
if message.video.thumbnail:
|
| 695 |
-
thumbnail_id = message.video.thumbnail.file_id
|
| 696 |
-
elif message.audio:
|
| 697 |
-
file_id = message.audio.file_id
|
| 698 |
-
file_name = message.audio.file_name or f"audio_{int(message.date.timestamp())}.mp3"
|
| 699 |
-
file_size = message.audio.file_size
|
| 700 |
-
|
| 701 |
-
if file_id:
|
| 702 |
-
try:
|
| 703 |
-
new_file = {
|
| 704 |
-
"user_id": user_id,
|
| 705 |
-
"name": file_name,
|
| 706 |
-
"type": "file",
|
| 707 |
-
"file_id": file_id,
|
| 708 |
-
"size": file_size,
|
| 709 |
-
"parent_id": None,
|
| 710 |
-
"thumbnail_id": thumbnail_id
|
| 711 |
-
}
|
| 712 |
-
supabase.table("items").insert(new_file).execute()
|
| 713 |
-
await message.answer(f"💾 Сохранено: {file_name}")
|
| 714 |
-
except Exception as e:
|
| 715 |
-
print(e)
|
| 716 |
-
await message.answer("Ошибка сохранения.")
|
| 717 |
-
|
| 718 |
-
# --- API INITIALIZATION ---
|
| 719 |
-
|
| 720 |
-
@asynccontextmanager
|
| 721 |
-
async def lifespan(app: FastAPI):
|
| 722 |
-
"""Initialize bot and webhook on startup."""
|
| 723 |
-
global aiohttp_session, bot
|
| 724 |
-
|
| 725 |
-
# Create bot with default AiohttpSession (no proxy)
|
| 726 |
-
bot = Bot(token=BOT_TOKEN, session=AiohttpSession())
|
| 727 |
-
|
| 728 |
-
if WEBHOOK_URL:
|
| 729 |
-
try:
|
| 730 |
-
# Set new webhook
|
| 731 |
-
webhook_full_url = f"{WEBHOOK_URL}/webhook"
|
| 732 |
-
logger.info(f"🔗 Setting webhook to: {webhook_full_url}")
|
| 733 |
-
result = await bot.set_webhook(webhook_full_url)
|
| 734 |
-
|
| 735 |
-
if result:
|
| 736 |
-
logger.info(f"✅ Webhook successfully set to {WEBHOOK_URL}/webhook")
|
| 737 |
-
else:
|
| 738 |
-
logger.error("❌ Failed to set webhook")
|
| 739 |
-
|
| 740 |
-
yield
|
| 741 |
-
|
| 742 |
-
# Cleanup on shutdown - only close session, do NOT delete webhook
|
| 743 |
-
logger.info("🔌 Closing bot session on shutdown...")
|
| 744 |
-
await bot.session.close()
|
| 745 |
-
|
| 746 |
-
except Exception as e:
|
| 747 |
-
logger.error(f"❌ Webhook setup error: {e}", exc_info=True)
|
| 748 |
-
# Fall back to polling mode
|
| 749 |
-
logger.info("🔄 Falling back to polling mode...")
|
| 750 |
-
asyncio.create_task(dp.start_polling(bot))
|
| 751 |
-
yield
|
| 752 |
-
await bot.session.close()
|
| 753 |
-
else:
|
| 754 |
-
logger.warning("⚠️ WEBHOOK_URL not set. Starting in polling mode.")
|
| 755 |
-
asyncio.create_task(dp.start_polling(bot))
|
| 756 |
-
yield
|
| 757 |
-
await bot.session.close()
|
| 758 |
-
|
| 759 |
-
app = FastAPI(lifespan=lifespan)
|
| 760 |
-
|
| 761 |
-
app.add_middleware(
|
| 762 |
-
CORSMiddleware,
|
| 763 |
-
allow_origins=["*"],
|
| 764 |
-
allow_credentials=True,
|
| 765 |
-
allow_methods=["*"],
|
| 766 |
-
allow_headers=["*"],
|
| 767 |
-
)
|
| 768 |
-
|
| 769 |
-
# --- REQUEST MODELS ---
|
| 770 |
-
|
| 771 |
-
class AdminRequest(BaseModel):
|
| 772 |
-
admin_id: int
|
| 773 |
-
target_user_id: Optional[int] = None
|
| 774 |
-
|
| 775 |
-
class SupportRequest(BaseModel):
|
| 776 |
-
user_id: int
|
| 777 |
-
type: str
|
| 778 |
-
message: str
|
| 779 |
-
|
| 780 |
-
class DeleteAllRequest(BaseModel):
|
| 781 |
-
user_id: int
|
| 782 |
-
|
| 783 |
-
class FolderRequest(BaseModel):
|
| 784 |
-
user_id: int
|
| 785 |
-
name: str
|
| 786 |
-
parent_id: Optional[str] = None
|
| 787 |
-
|
| 788 |
-
class RenameRequest(BaseModel):
|
| 789 |
-
item_id: str
|
| 790 |
-
new_name: str
|
| 791 |
-
|
| 792 |
-
class ItemRequest(BaseModel):
|
| 793 |
-
item_id: str
|
| 794 |
-
|
| 795 |
-
class DownloadRequest(BaseModel):
|
| 796 |
-
user_id: int
|
| 797 |
-
file_id: str
|
| 798 |
-
file_name: str
|
| 799 |
-
recipient_id: Optional[int] = None
|
| 800 |
-
|
| 801 |
-
class MoveRequest(BaseModel):
|
| 802 |
-
file_id: str
|
| 803 |
-
folder_id: Optional[str]
|
| 804 |
-
|
| 805 |
-
class InvoiceRequest(BaseModel):
|
| 806 |
-
amount: int
|
| 807 |
-
title: str = "Поддержка автора"
|
| 808 |
-
description: str = "Донат на развитие проекта"
|
| 809 |
-
|
| 810 |
-
# --- WEBHOOK ENDPOINT ---
|
| 811 |
-
|
| 812 |
-
@app.post("/webhook")
|
| 813 |
-
async def bot_webhook(update: dict):
|
| 814 |
-
"""
|
| 815 |
-
Endpoint to receive updates from Telegram.
|
| 816 |
-
Added extensive logging and error handling for debugging.
|
| 817 |
-
"""
|
| 818 |
-
try:
|
| 819 |
-
logger.info(f"📥 Received webhook update: {update.get('update_id', 'unknown')}")
|
| 820 |
-
|
| 821 |
-
# Validate update
|
| 822 |
-
if not update:
|
| 823 |
-
logger.warning("⚠️ Empty update received")
|
| 824 |
-
return {"status": "error", "message": "Empty update"}
|
| 825 |
-
|
| 826 |
-
# Create Update object
|
| 827 |
-
try:
|
| 828 |
-
telegram_update = Update.model_validate(update, context={"bot": bot})
|
| 829 |
-
except Exception as e:
|
| 830 |
-
logger.error(f"❌ Failed to parse update: {e}")
|
| 831 |
-
raise HTTPException(status_code=400, detail=f"Invalid update format: {e}")
|
| 832 |
-
|
| 833 |
-
# Get update type for logging
|
| 834 |
-
update_type = "unknown"
|
| 835 |
-
user_id = "unknown"
|
| 836 |
-
if telegram_update.message:
|
| 837 |
-
update_type = f"message ({telegram_update.message.content_type})"
|
| 838 |
-
user_id = telegram_update.message.from_user.id
|
| 839 |
-
elif telegram_update.callback_query:
|
| 840 |
-
update_type = "callback_query"
|
| 841 |
-
user_id = telegram_update.callback_query.from_user.id
|
| 842 |
-
elif telegram_update.edited_message:
|
| 843 |
-
update_type = "edited_message"
|
| 844 |
-
user_id = telegram_update.edited_message.from_user.id
|
| 845 |
-
|
| 846 |
-
logger.info(f"📩 Processing {update_type} from user {user_id}")
|
| 847 |
-
|
| 848 |
-
# Process update
|
| 849 |
-
try:
|
| 850 |
-
await dp.feed_update(bot=bot, update=telegram_update)
|
| 851 |
-
logger.info(f"✅ Update {update.get('update_id', 'unknown')} processed successfully")
|
| 852 |
-
except (TelegramRetryAfter, TelegramAPIError) as e:
|
| 853 |
-
logger.error(f"❌ Telegram API error: {e}")
|
| 854 |
-
# Don't raise - Telegram will retry
|
| 855 |
-
return {"status": "error", "message": str(e)}
|
| 856 |
-
except Exception as e:
|
| 857 |
-
logger.error(f"❌ Handler error: {e}", exc_info=True)
|
| 858 |
-
# Don't raise - log and continue
|
| 859 |
-
return {"status": "error", "message": f"Handler error: {e}"}
|
| 860 |
-
|
| 861 |
-
return {"status": "ok"}
|
| 862 |
-
|
| 863 |
-
except Exception as e:
|
| 864 |
-
logger.error(f"❌ Webhook error: {e}", exc_info=True)
|
| 865 |
-
# Always return OK to prevent Telegram from stopping webhook
|
| 866 |
-
return {"status": "ok", "warning": f"Error logged: {e}"}
|
| 867 |
-
|
| 868 |
-
# --- API ENDPOINTS: ADMIN ---
|
| 869 |
-
|
| 870 |
-
@app.post("/api/admin/users")
|
| 871 |
-
async def get_all_users(req: AdminRequest):
|
| 872 |
-
# Check if user is admin
|
| 873 |
-
admin = supabase.table("users").select("username").eq("id", req.admin_id).single().execute()
|
| 874 |
-
if not admin.data or admin.data['username'] != ADMIN_USERNAME:
|
| 875 |
-
raise HTTPException(403, "Access Denied")
|
| 876 |
-
|
| 877 |
-
users = supabase.table("users").select("*").order("id", desc=True).execute().data
|
| 878 |
-
# Admin is always on top
|
| 879 |
-
users.sort(key=lambda u: u['username'] != ADMIN_USERNAME)
|
| 880 |
-
return users
|
| 881 |
-
|
| 882 |
-
@app.post("/api/admin/block")
|
| 883 |
-
async def toggle_block_user(req: AdminRequest):
|
| 884 |
-
admin = supabase.table("users").select("username").eq("id", req.admin_id).single().execute()
|
| 885 |
-
if not admin.data or admin.data['username'] != ADMIN_USERNAME:
|
| 886 |
-
raise HTTPException(403, "Access Denied")
|
| 887 |
-
|
| 888 |
-
if req.target_user_id == req.admin_id: return {"status": "error"} # Cannot block self
|
| 889 |
-
|
| 890 |
-
curr = supabase.table("users").select("is_blocked").eq("id", req.target_user_id).single().execute()
|
| 891 |
-
new_status = not curr.data.get('is_blocked', False)
|
| 892 |
-
|
| 893 |
-
supabase.table("users").update({"is_blocked": new_status}).eq("id", req.target_user_id).execute()
|
| 894 |
-
return {"status": "ok", "is_blocked": new_status}
|
| 895 |
-
|
| 896 |
-
@app.post("/api/admin/delete_user")
|
| 897 |
-
async def delete_user_admin(req: AdminRequest):
|
| 898 |
-
admin = supabase.table("users").select("username").eq("id", req.admin_id).single().execute()
|
| 899 |
-
if not admin.data or admin.data['username'] != ADMIN_USERNAME:
|
| 900 |
-
raise HTTPException(403, "Access Denied")
|
| 901 |
-
|
| 902 |
-
if req.target_user_id == req.admin_id: return {"status": "error"}
|
| 903 |
-
|
| 904 |
-
supabase.table("items").delete().eq("user_id", req.target_user_id).execute()
|
| 905 |
-
supabase.table("users").delete().eq("id", req.target_user_id).execute()
|
| 906 |
-
return {"status": "ok"}
|
| 907 |
-
|
| 908 |
-
@app.post("/api/admin/toggle_support_access")
|
| 909 |
-
async def toggle_support_access(req: AdminRequest):
|
| 910 |
-
"""Toggle second admin's access to support (main admin only)."""
|
| 911 |
-
admin = supabase.table("users").select("username").eq("id", req.admin_id).single().execute()
|
| 912 |
-
if not admin.data or admin.data['username'] != ADMIN_USERNAME:
|
| 913 |
-
raise HTTPException(403, "Access Denied")
|
| 914 |
-
|
| 915 |
-
# Check if target is second admin
|
| 916 |
-
target = supabase.table("users").select("username").eq("id", req.target_user_id).single().execute()
|
| 917 |
-
if not target.data or target.data['username'] != ADMIN2_USERNAME:
|
| 918 |
-
raise HTTPException(400, detail="Target is not second admin")
|
| 919 |
-
|
| 920 |
-
# Get current status
|
| 921 |
-
curr = supabase.table("users").select("support_blocked").eq("id", req.target_user_id).single().execute()
|
| 922 |
-
new_status = not (curr.data.get('support_blocked', False))
|
| 923 |
-
|
| 924 |
-
# Update support_blocked status
|
| 925 |
-
supabase.table("users").update({"support_blocked": new_status}).eq("id", req.target_user_id).execute()
|
| 926 |
-
return {"status": "ok", "support_blocked": new_status}
|
| 927 |
-
|
| 928 |
-
@app.get("/api/admin/support_status")
|
| 929 |
-
async def get_support_status(admin_id: int):
|
| 930 |
-
"""Get support access status for second admin (main admin only)."""
|
| 931 |
-
admin = supabase.table("users").select("username").eq("id", admin_id).single().execute()
|
| 932 |
-
if not admin.data or admin.data['username'] != ADMIN_USERNAME:
|
| 933 |
-
raise HTTPException(403, "Access Denied")
|
| 934 |
-
|
| 935 |
-
admin2_id = get_admin_id(ADMIN2_USERNAME)
|
| 936 |
-
if not admin2_id:
|
| 937 |
-
return {"admin2_exists": False, "support_blocked": False}
|
| 938 |
-
|
| 939 |
-
curr = supabase.table("users").select("support_blocked").eq("id", admin2_id).single().execute()
|
| 940 |
-
return {
|
| 941 |
-
"admin2_exists": True,
|
| 942 |
-
"admin2_id": admin2_id,
|
| 943 |
-
"support_blocked": curr.data.get('support_blocked', False) if curr.data else False
|
| 944 |
-
}
|
| 945 |
-
|
| 946 |
-
|
| 947 |
-
# --- API ENDPOINTS: CLIENT ---
|
| 948 |
-
|
| 949 |
-
@app.post("/api/support")
|
| 950 |
-
async def handle_support_request(req: SupportRequest):
|
| 951 |
-
try:
|
| 952 |
-
# 1. Get Admin IDs
|
| 953 |
-
admin1_id = get_admin_id(ADMIN_USERNAME)
|
| 954 |
-
admin2_id = get_admin_id(ADMIN2_USERNAME)
|
| 955 |
-
|
| 956 |
-
print(f"Admin IDs: {ADMIN_USERNAME}={admin1_id}, {ADMIN2_USERNAME}={admin2_id}")
|
| 957 |
-
|
| 958 |
-
if not admin1_id:
|
| 959 |
-
print(f"Main admin user '{ADMIN_USERNAME}' not found in database.")
|
| 960 |
-
raise HTTPException(status_code=500, detail="Main admin not configured.")
|
| 961 |
-
|
| 962 |
-
# 2. Get User Info
|
| 963 |
-
user = supabase.table("users").select("username").eq("id", req.user_id).single().execute()
|
| 964 |
-
username = f"@{user.data['username']}" if user.data and user.data.get('username') else f"ID: {req.user_id}"
|
| 965 |
-
|
| 966 |
-
# 3. Format message
|
| 967 |
-
type_map = {
|
| 968 |
-
"bug": "сообщение о баге",
|
| 969 |
-
"complaint": "жалобу",
|
| 970 |
-
"suggestion": "предложение"
|
| 971 |
-
}
|
| 972 |
-
type_str = type_map.get(req.type, "сообщение")
|
| 973 |
-
|
| 974 |
-
message_to_admin = (
|
| 975 |
-
f"⚠️ Пользователь {username} написал {type_str}:\n\n"
|
| 976 |
-
f"<blockquote>{req.message}</blockquote>"
|
| 977 |
-
)
|
| 978 |
-
|
| 979 |
-
# 4. Create inline keyboard with reply options
|
| 980 |
-
keyboard = InlineKeyboardMarkup(inline_keyboard=[
|
| 981 |
-
[InlineKeyboardButton(text="📝 Ответить шаблоном", callback_data=f"rt_{req.user_id}_{req.type}")],
|
| 982 |
-
[InlineKeyboardButton(text="✏️ Написать ответ", callback_data=f"rc_{req.user_id}")]
|
| 983 |
-
])
|
| 984 |
-
|
| 985 |
-
# 5. Send message to both admins
|
| 986 |
-
sent_count = 0
|
| 987 |
-
for admin_id, admin_name in [(admin1_id, ADMIN_USERNAME), (admin2_id, ADMIN2_USERNAME)]:
|
| 988 |
-
if admin_id:
|
| 989 |
-
try:
|
| 990 |
-
await bot.send_message(admin_id, message_to_admin, parse_mode="HTML", reply_markup=keyboard)
|
| 991 |
-
sent_count += 1
|
| 992 |
-
print(f"✅ Support message sent to {admin_name} (ID: {admin_id})")
|
| 993 |
-
except Exception as e:
|
| 994 |
-
print(f"❌ Failed to send to {admin_name} (ID: {admin_id}): {e}")
|
| 995 |
-
else:
|
| 996 |
-
print(f"⚠️ {admin_name} not found in database (ID is None)")
|
| 997 |
-
|
| 998 |
-
print(f"Support message sent to {sent_count}/2 admins from user {req.user_id}")
|
| 999 |
-
return {"status": "ok"}
|
| 1000 |
-
except Exception as e:
|
| 1001 |
-
print(f"Error in /api/support: {e}")
|
| 1002 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 1003 |
-
|
| 1004 |
-
@app.get("/api/profile")
|
| 1005 |
-
async def get_profile_stats(user_id: int):
|
| 1006 |
-
check_is_blocked(user_id)
|
| 1007 |
-
try:
|
| 1008 |
-
res = supabase.table("items").select("type, name, size").eq("user_id", user_id).execute()
|
| 1009 |
-
items = res.data
|
| 1010 |
-
total_files = 0; total_size_bytes = 0
|
| 1011 |
-
count_photos = 0; count_videos = 0; count_docs = 0; count_folders = 0
|
| 1012 |
-
|
| 1013 |
-
for i in items:
|
| 1014 |
-
total_size_bytes += (i['size'] or 0)
|
| 1015 |
-
if i['type'] == 'folder': count_folders += 1
|
| 1016 |
-
else:
|
| 1017 |
-
total_files += 1
|
| 1018 |
-
name = i['name'].lower()
|
| 1019 |
-
if name.endswith(('.jpg', '.jpeg', '.png')): count_photos += 1
|
| 1020 |
-
elif name.endswith(('.mp4', '.mov')): count_videos += 1
|
| 1021 |
-
else: count_docs += 1
|
| 1022 |
-
|
| 1023 |
-
total_size_mb = round(total_size_bytes / (1024 * 1024), 2)
|
| 1024 |
-
return {
|
| 1025 |
-
"total_files": total_files,
|
| 1026 |
-
"total_size_mb": total_size_mb,
|
| 1027 |
-
"counts": {"photos": count_photos, "videos": count_videos, "docs": count_docs, "folders": count_folders}
|
| 1028 |
-
}
|
| 1029 |
-
except Exception as e:
|
| 1030 |
-
raise HTTPException(status_code=500, detail="Stats error")
|
| 1031 |
-
|
| 1032 |
-
@app.get("/api/files")
|
| 1033 |
-
async def get_files(user_id: int, folder_id: str = None, mode: str = 'strict'):
|
| 1034 |
-
check_is_blocked(user_id)
|
| 1035 |
-
query = supabase.table("items").select("*").eq("user_id", user_id)
|
| 1036 |
-
if mode == 'global': query = query.neq("type", "folder")
|
| 1037 |
-
elif mode == 'folders': query = query.eq("type", "folder")
|
| 1038 |
-
elif folder_id and folder_id != "null" and folder_id != "root": query = query.eq("parent_id", folder_id)
|
| 1039 |
-
else: query = query.is_("parent_id", "null")
|
| 1040 |
-
query = query.order("type", desc=True).order("created_at", desc=True)
|
| 1041 |
-
return query.execute().data
|
| 1042 |
-
|
| 1043 |
-
@app.post("/api/delete_all")
|
| 1044 |
-
async def delete_all_data(req: DeleteAllRequest):
|
| 1045 |
-
check_is_blocked(req.user_id)
|
| 1046 |
-
try:
|
| 1047 |
-
supabase.table("items").delete().eq("user_id", req.user_id).execute()
|
| 1048 |
-
return {"status": "ok"}
|
| 1049 |
-
except Exception as e:
|
| 1050 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 1051 |
-
|
| 1052 |
-
@app.post("/api/create_folder")
|
| 1053 |
-
async def create_folder(req: FolderRequest):
|
| 1054 |
-
check_is_blocked(req.user_id)
|
| 1055 |
-
try:
|
| 1056 |
-
parent = req.parent_id
|
| 1057 |
-
if parent == "null" or parent == "": parent = None
|
| 1058 |
-
new_folder = {"user_id": req.user_id, "name": req.name, "type": "folder", "parent_id": parent}
|
| 1059 |
-
supabase.table("items").insert(new_folder).execute()
|
| 1060 |
-
return {"status": "ok"}
|
| 1061 |
-
except Exception as e:
|
| 1062 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 1063 |
-
|
| 1064 |
-
@app.post("/api/rename")
|
| 1065 |
-
async def rename_item(req: RenameRequest):
|
| 1066 |
-
try:
|
| 1067 |
-
supabase.table("items").update({"name": req.new_name}).eq("id", req.item_id).execute()
|
| 1068 |
-
return {"status": "ok"}
|
| 1069 |
-
except Exception as e:
|
| 1070 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 1071 |
-
|
| 1072 |
-
@app.post("/api/delete")
|
| 1073 |
-
async def delete_item(req: ItemRequest):
|
| 1074 |
-
"""Normal deletion: if it's a folder, files are moved to the root."""
|
| 1075 |
-
try:
|
| 1076 |
-
item = supabase.table("items").select("type").eq("id", req.item_id).execute()
|
| 1077 |
-
if item.data and item.data[0]['type'] == 'folder':
|
| 1078 |
-
supabase.table("items").update({"parent_id": None}).eq("parent_id", req.item_id).execute()
|
| 1079 |
-
supabase.table("items").delete().eq("id", req.item_id).execute()
|
| 1080 |
-
return {"status": "deleted"}
|
| 1081 |
-
except Exception as e:
|
| 1082 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 1083 |
-
|
| 1084 |
-
@app.post("/api/delete_folder_recursive")
|
| 1085 |
-
async def delete_folder_recursive_api(req: ItemRequest):
|
| 1086 |
-
"""Recursively deletes a folder with all its contents."""
|
| 1087 |
-
try:
|
| 1088 |
-
async def recursive_del(folder_id):
|
| 1089 |
-
children = supabase.table("items").select("id, type").eq("parent_id", folder_id).execute().data
|
| 1090 |
-
for child in children:
|
| 1091 |
-
if child['type'] == 'folder':
|
| 1092 |
-
await recursive_del(child['id'])
|
| 1093 |
-
else:
|
| 1094 |
-
supabase.table("items").delete().eq("id", child['id']).execute()
|
| 1095 |
-
supabase.table("items").delete().eq("id", folder_id).execute()
|
| 1096 |
-
|
| 1097 |
-
await recursive_del(req.item_id)
|
| 1098 |
-
return {"status": "deleted_recursive"}
|
| 1099 |
-
except Exception as e:
|
| 1100 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 1101 |
-
|
| 1102 |
-
@app.post("/api/download")
|
| 1103 |
-
async def download_file(req: DownloadRequest):
|
| 1104 |
-
target_id = req.recipient_id if req.recipient_id else req.user_id
|
| 1105 |
-
|
| 1106 |
-
if target_id != req.user_id:
|
| 1107 |
-
try:
|
| 1108 |
-
admin_check = supabase.table("users").select("username").eq("id", target_id).single().execute()
|
| 1109 |
-
if not admin_check.data or admin_check.data['username'] != ADMIN_USERNAME:
|
| 1110 |
-
raise HTTPException(status_code=403, detail="Access Denied: Only admin can redirect downloads")
|
| 1111 |
-
except:
|
| 1112 |
-
raise HTTPException(status_code=403, detail="Access Denied")
|
| 1113 |
-
|
| 1114 |
-
if target_id == req.user_id:
|
| 1115 |
-
check_is_blocked(req.user_id)
|
| 1116 |
-
|
| 1117 |
-
try:
|
| 1118 |
-
is_photo = req.file_name.lower().endswith(('.jpg', '.jpeg', '.png'))
|
| 1119 |
-
is_video = req.file_name.lower().endswith(('.mp4', '.mov'))
|
| 1120 |
-
|
| 1121 |
-
if is_photo: await bot.send_photo(target_id, req.file_id, caption="📸")
|
| 1122 |
-
elif is_video: await bot.send_video(target_id, req.file_id, caption="🎥")
|
| 1123 |
-
else: await bot.send_document(target_id, req.file_id, caption="📄")
|
| 1124 |
-
|
| 1125 |
-
return {"status": "ok"}
|
| 1126 |
-
except Exception as e:
|
| 1127 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 1128 |
-
|
| 1129 |
-
@app.get("/api/preview/{file_id}")
|
| 1130 |
-
async def get_preview(file_id: str):
|
| 1131 |
-
try:
|
| 1132 |
-
file_info = await bot.get_file(file_id)
|
| 1133 |
-
url = f"https://api.telegram.org/file/bot{BOT_TOKEN}/{file_info.file_path}"
|
| 1134 |
-
async with aiohttp.ClientSession() as session:
|
| 1135 |
-
async with session.get(url) as resp:
|
| 1136 |
-
if resp.status != 200: raise HTTPException(status_code=404)
|
| 1137 |
-
content = await resp.read()
|
| 1138 |
-
return Response(content=content, media_type="image/jpeg")
|
| 1139 |
-
except Exception as e:
|
| 1140 |
-
raise HTTPException(status_code=404)
|
| 1141 |
-
|
| 1142 |
-
@app.post("/api/move_file")
|
| 1143 |
-
async def move_file(req: MoveRequest):
|
| 1144 |
-
try:
|
| 1145 |
-
supabase.table("items").update({"parent_id": req.folder_id}).eq("id", req.file_id).execute()
|
| 1146 |
-
return {"status": "ok"}
|
| 1147 |
-
except Exception as e:
|
| 1148 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 1149 |
-
|
| 1150 |
-
from datetime import datetime
|
| 1151 |
-
|
| 1152 |
-
@app.post("/api/generate_invoice")
|
| 1153 |
-
async def generate_invoice(req: InvoiceRequest):
|
| 1154 |
-
try:
|
| 1155 |
-
link = await bot.create_invoice_link(
|
| 1156 |
-
title=req.title,
|
| 1157 |
-
description=req.description,
|
| 1158 |
-
payload="donate",
|
| 1159 |
-
provider_token="",
|
| 1160 |
-
currency="XTR",
|
| 1161 |
-
prices=[LabeledPrice(label="Stars", amount=req.amount)]
|
| 1162 |
-
)
|
| 1163 |
-
return {"link": link}
|
| 1164 |
-
except Exception as e:
|
| 1165 |
-
logger.error(f"Error generating invoice: {e}")
|
| 1166 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 1167 |
-
|
| 1168 |
-
@app.head("/health")
|
| 1169 |
-
@app.get("/health")
|
| 1170 |
-
async def health_check():
|
| 1171 |
-
"""
|
| 1172 |
-
Health check endpoint for monitoring.
|
| 1173 |
-
Use this with cron-job.org or uptimerobot.com to prevent Render sleep.
|
| 1174 |
-
Supports both GET and HEAD methods returning status 200.
|
| 1175 |
-
"""
|
| 1176 |
-
try:
|
| 1177 |
-
# Check bot connection
|
| 1178 |
-
bot_info = await bot.get_me()
|
| 1179 |
-
bot_status = "ok"
|
| 1180 |
-
except Exception as e:
|
| 1181 |
-
logger.error(f"Bot health check failed: {e}")
|
| 1182 |
-
bot_status = f"error: {e}"
|
| 1183 |
-
|
| 1184 |
-
return {
|
| 1185 |
-
"status": "ok",
|
| 1186 |
-
"timestamp": datetime.now().isoformat(),
|
| 1187 |
-
"webhook_url": WEBHOOK_URL,
|
| 1188 |
-
"bot_username": bot_info.username if bot_info else None,
|
| 1189 |
-
"bot_status": bot_status
|
| 1190 |
-
}
|
| 1191 |
-
|
| 1192 |
-
@app.get("/")
|
| 1193 |
-
async def root():
|
| 1194 |
-
return {"message": "Tg Cloud v3.0 (Backend)"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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