Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -44,21 +44,36 @@ async def wait_for_network(timeout: int = 60) -> bool:
|
|
| 44 |
logger.error("❌ Network not available after timeout")
|
| 45 |
return False
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
# ------------------------------------------------------------
|
| 48 |
# Установка вебхука с повторными попытками
|
| 49 |
# ------------------------------------------------------------
|
| 50 |
async def setup_webhook_with_retry(retries: int = 15, delay: int = 10):
|
| 51 |
"""
|
| 52 |
Устанавливает вебхук, сначала дожидаясь сети.
|
|
|
|
| 53 |
"""
|
| 54 |
# Сначала проверяем сеть (до 60 секунд)
|
| 55 |
if not await wait_for_network(timeout=60):
|
| 56 |
logger.error("❌ Cannot proceed with webhook setup - no network")
|
|
|
|
|
|
|
| 57 |
return
|
| 58 |
|
| 59 |
hf_space = os.getenv("SPACE_ID", "")
|
| 60 |
if not hf_space:
|
| 61 |
-
logger.warning("SPACE_ID not set,
|
|
|
|
| 62 |
return
|
| 63 |
|
| 64 |
webhook_url = f"https://{hf_space}.hf.space/webhook"
|
|
@@ -72,17 +87,16 @@ async def setup_webhook_with_retry(retries: int = 15, delay: int = 10):
|
|
| 72 |
drop_pending_updates=True
|
| 73 |
)
|
| 74 |
logger.info(f"✅ Webhook successfully set (attempt {attempt})")
|
| 75 |
-
# Проверим текущий вебхук
|
| 76 |
webhook_info = await bot.get_webhook_info()
|
| 77 |
logger.info(f"ℹ️ Webhook info: {webhook_info}")
|
| 78 |
return
|
| 79 |
-
|
| 80 |
except Exception as e:
|
| 81 |
logger.error(f"❌ Failed to set webhook (attempt {attempt}/{retries}): {e}")
|
| 82 |
if attempt < retries:
|
| 83 |
await asyncio.sleep(delay)
|
| 84 |
|
| 85 |
-
logger.error("❌ All webhook setup attempts failed")
|
|
|
|
| 86 |
|
| 87 |
# ------------------------------------------------------------
|
| 88 |
# Lifespan
|
|
@@ -91,8 +105,15 @@ async def setup_webhook_with_retry(retries: int = 15, delay: int = 10):
|
|
| 91 |
async def lifespan(app: FastAPI):
|
| 92 |
# Startup
|
| 93 |
logger.info("🚀 Bot starting...")
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
yield
|
| 97 |
# Shutdown
|
| 98 |
logger.info("🛑 Bot shutting down...")
|
|
@@ -115,7 +136,7 @@ async def root():
|
|
| 115 |
<head><title>🎨 AI PhotoStudio Bot</title></head>
|
| 116 |
<body style="font-family: Arial; text-align: center; padding: 50px;">
|
| 117 |
<h1>🚀 AI PhotoStudio Bot is Running!</h1>
|
| 118 |
-
<p>✅ Webhook setup in background</p>
|
| 119 |
<p>📊 Version: 2.0.0</p>
|
| 120 |
<p>⏰ Time: """ + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + """</p>
|
| 121 |
</body>
|
|
@@ -131,7 +152,7 @@ async def health():
|
|
| 131 |
|
| 132 |
@app.post("/webhook")
|
| 133 |
async def telegram_webhook(request: Request):
|
| 134 |
-
"""Получает обновления от Telegram"""
|
| 135 |
try:
|
| 136 |
body = await request.body()
|
| 137 |
update = types.Update.model_validate_json(body.decode())
|
|
|
|
| 44 |
logger.error("❌ Network not available after timeout")
|
| 45 |
return False
|
| 46 |
|
| 47 |
+
# ------------------------------------------------------------
|
| 48 |
+
# Polling (запасной вариант)
|
| 49 |
+
# ------------------------------------------------------------
|
| 50 |
+
async def run_polling():
|
| 51 |
+
"""Запускает polling для получения обновлений"""
|
| 52 |
+
logger.info("🔄 Starting polling as fallback...")
|
| 53 |
+
try:
|
| 54 |
+
await dp.start_polling(bot)
|
| 55 |
+
except Exception as e:
|
| 56 |
+
logger.error(f"❌ Polling error: {e}")
|
| 57 |
+
|
| 58 |
# ------------------------------------------------------------
|
| 59 |
# Установка вебхука с повторными попытками
|
| 60 |
# ------------------------------------------------------------
|
| 61 |
async def setup_webhook_with_retry(retries: int = 15, delay: int = 10):
|
| 62 |
"""
|
| 63 |
Устанавливает вебхук, сначала дожидаясь сети.
|
| 64 |
+
Если не удаётся, запускает polling.
|
| 65 |
"""
|
| 66 |
# Сначала проверяем сеть (до 60 секунд)
|
| 67 |
if not await wait_for_network(timeout=60):
|
| 68 |
logger.error("❌ Cannot proceed with webhook setup - no network")
|
| 69 |
+
logger.info("🔄 Switching to polling as fallback")
|
| 70 |
+
asyncio.create_task(run_polling())
|
| 71 |
return
|
| 72 |
|
| 73 |
hf_space = os.getenv("SPACE_ID", "")
|
| 74 |
if not hf_space:
|
| 75 |
+
logger.warning("SPACE_ID not set, cannot set webhook, switching to polling")
|
| 76 |
+
asyncio.create_task(run_polling())
|
| 77 |
return
|
| 78 |
|
| 79 |
webhook_url = f"https://{hf_space}.hf.space/webhook"
|
|
|
|
| 87 |
drop_pending_updates=True
|
| 88 |
)
|
| 89 |
logger.info(f"✅ Webhook successfully set (attempt {attempt})")
|
|
|
|
| 90 |
webhook_info = await bot.get_webhook_info()
|
| 91 |
logger.info(f"ℹ️ Webhook info: {webhook_info}")
|
| 92 |
return
|
|
|
|
| 93 |
except Exception as e:
|
| 94 |
logger.error(f"❌ Failed to set webhook (attempt {attempt}/{retries}): {e}")
|
| 95 |
if attempt < retries:
|
| 96 |
await asyncio.sleep(delay)
|
| 97 |
|
| 98 |
+
logger.error("❌ All webhook setup attempts failed, switching to polling")
|
| 99 |
+
asyncio.create_task(run_polling())
|
| 100 |
|
| 101 |
# ------------------------------------------------------------
|
| 102 |
# Lifespan
|
|
|
|
| 105 |
async def lifespan(app: FastAPI):
|
| 106 |
# Startup
|
| 107 |
logger.info("🚀 Bot starting...")
|
| 108 |
+
|
| 109 |
+
use_polling = os.getenv("USE_POLLING", "").lower() == "true"
|
| 110 |
+
if use_polling:
|
| 111 |
+
logger.info("📞 USE_POLLING=true, starting polling immediately")
|
| 112 |
+
polling_task = asyncio.create_task(run_polling())
|
| 113 |
+
else:
|
| 114 |
+
# Запускаем задачу установки вебхука (которая может переключиться на polling)
|
| 115 |
+
asyncio.create_task(setup_webhook_with_retry())
|
| 116 |
+
|
| 117 |
yield
|
| 118 |
# Shutdown
|
| 119 |
logger.info("🛑 Bot shutting down...")
|
|
|
|
| 136 |
<head><title>🎨 AI PhotoStudio Bot</title></head>
|
| 137 |
<body style="font-family: Arial; text-align: center; padding: 50px;">
|
| 138 |
<h1>🚀 AI PhotoStudio Bot is Running!</h1>
|
| 139 |
+
<p>✅ Webhook setup in background (fallback to polling if needed)</p>
|
| 140 |
<p>📊 Version: 2.0.0</p>
|
| 141 |
<p>⏰ Time: """ + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + """</p>
|
| 142 |
</body>
|
|
|
|
| 152 |
|
| 153 |
@app.post("/webhook")
|
| 154 |
async def telegram_webhook(request: Request):
|
| 155 |
+
"""Получает обновления от Telegram (если используется webhook)"""
|
| 156 |
try:
|
| 157 |
body = await request.body()
|
| 158 |
update = types.Update.model_validate_json(body.decode())
|