Spaces:
Running

axeronis commited on
Commit
2b2e573
·
1 Parent(s): b9c53fb

Fix: Save bot token first, graceful degradation if webhook setup fails

Browse files
Files changed (1) hide show
  1. backend/app/api/channels.py +74 -50
backend/app/api/channels.py CHANGED
@@ -49,6 +49,7 @@ async def connect_telegram_bot(
49
  ):
50
  """
51
  Connect Telegram bot to authenticated user's tenant account.
 
52
  """
53
  try:
54
  tenant_id = current_user.tenant_id
@@ -65,63 +66,86 @@ async def connect_telegram_bot(
65
  detail="Неверный формат токена. Токен должен быть вида: 123456:ABC-DEF..."
66
  )
67
 
68
- webhook_base = (settings.TELEGRAM_WEBHOOK_URL or "https://your-domain.com").rstrip("/")
 
69
  if webhook_base.endswith("/api/v1"):
70
  webhook_base = webhook_base[:-7]
71
-
72
- webhook_url = f"{webhook_base}/api/v1/webhook/telegram/{tenant_id}"
73
-
74
- telegram_api_url = f"https://api.telegram.org/bot{bot_token}/setWebhook"
75
-
76
- async with httpx.AsyncClient(timeout=30.0) as client:
77
- bot_info_response = await client.get(
78
- f"https://api.telegram.org/bot{bot_token}/getMe"
79
- )
80
-
81
- if bot_info_response.status_code != 200:
82
- raise HTTPException(
83
- status_code=400,
84
- detail="Неверный токен бота. Проверьте токен и попробуйте снова."
85
- )
86
-
87
- bot_data = bot_info_response.json()
88
- if not bot_data.get("ok"):
89
- raise HTTPException(
90
- status_code=400,
91
- detail="Не удалось подключиться к боту. Проверьте токен."
92
- )
93
-
94
- bot_username = bot_data.get("result", {}).get("username", "Unknown")
95
-
96
- webhook_response = await client.post(
97
- telegram_api_url,
98
- json={
99
- "url": webhook_url,
100
- "allowed_updates": ["message", "edited_message"],
101
- "drop_pending_updates": True
102
- }
103
- )
104
-
105
- webhook_data = webhook_response.json()
106
-
107
- if not webhook_data.get("ok"):
108
- error_description = webhook_data.get("description", "Unknown error")
109
- raise HTTPException(
110
- status_code=500,
111
- detail=f"Ошибка при установке webhook: {error_description}"
112
- )
113
 
 
114
  tenant.telegram_bot_token = bot_token
115
  tenant.webhook_url = webhook_url
116
  session.add(tenant)
117
  await session.commit()
118
-
119
- return TelegramConnectResponse(
120
- ok=True,
121
- status="connected",
122
- webhook_url=webhook_url,
123
- message=f"✅ Бот @{bot_username} успешно подключен! Webhook установлен."
124
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
  except HTTPException:
127
  raise
 
49
  ):
50
  """
51
  Connect Telegram bot to authenticated user's tenant account.
52
+ Saves token first, then attempts webhook setup (graceful degradation if network issues).
53
  """
54
  try:
55
  tenant_id = current_user.tenant_id
 
66
  detail="Неверный формат токена. Токен должен быть вида: 123456:ABC-DEF..."
67
  )
68
 
69
+ # Build webhook URL
70
+ webhook_base = (settings.TELEGRAM_WEBHOOK_URL or "https://axeronis-microfunnel-api.hf.space").rstrip("/")
71
  if webhook_base.endswith("/api/v1"):
72
  webhook_base = webhook_base[:-7]
73
+ webhook_url = f"{webhook_base}/api/v1/webhook/telegram-notify/{tenant_id}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
+ # ALWAYS save token first (before any network calls)
76
  tenant.telegram_bot_token = bot_token
77
  tenant.webhook_url = webhook_url
78
  session.add(tenant)
79
  await session.commit()
80
+ logger.info(f"✅ Bot token saved for tenant {tenant_id}")
81
+
82
+ # Now attempt to verify token and set webhook (best-effort)
83
+ bot_username = "Unknown"
84
+ webhook_set = False
85
+ network_error = False
86
+
87
+ try:
88
+ async with httpx.AsyncClient(timeout=15.0) as client:
89
+ # Verify bot token
90
+ bot_info_response = await client.get(
91
+ f"https://api.telegram.org/bot{bot_token}/getMe"
92
+ )
93
+
94
+ if bot_info_response.status_code == 200:
95
+ bot_data = bot_info_response.json()
96
+ if bot_data.get("ok"):
97
+ bot_username = bot_data.get("result", {}).get("username", "Unknown")
98
+
99
+ # Set webhook
100
+ webhook_response = await client.post(
101
+ f"https://api.telegram.org/bot{bot_token}/setWebhook",
102
+ json={
103
+ "url": webhook_url,
104
+ "allowed_updates": ["message", "edited_message", "my_chat_member"],
105
+ "drop_pending_updates": True
106
+ }
107
+ )
108
+ webhook_data = webhook_response.json()
109
+ webhook_set = webhook_data.get("ok", False)
110
+ else:
111
+ # Invalid token - rollback
112
+ tenant.telegram_bot_token = None
113
+ tenant.webhook_url = None
114
+ session.add(tenant)
115
+ await session.commit()
116
+ raise HTTPException(
117
+ status_code=400,
118
+ detail="Неверный токен бота. Проверьте токен и попро��уйте снова."
119
+ )
120
+
121
+ except (httpx.ConnectError, httpx.TimeoutException, OSError) as e:
122
+ # Network error (DNS, timeout, etc.) - token is saved, webhook not set
123
+ network_error = True
124
+ logger.warning(f"⚠️ Network error during webhook setup: {e}. Token saved, manual webhook needed.")
125
+
126
+ # Return appropriate response
127
+ if webhook_set:
128
+ return TelegramConnectResponse(
129
+ ok=True,
130
+ status="connected",
131
+ webhook_url=webhook_url,
132
+ message=f"✅ Бот @{bot_username} успешно подключен! Webhook установлен."
133
+ )
134
+ elif network_error:
135
+ # Token saved but webhook not set due to network issues
136
+ return TelegramConnectResponse(
137
+ ok=True,
138
+ status="partial",
139
+ webhook_url=webhook_url,
140
+ message=f"⚠️ Токен сохранен! Webhook не установлен автоматически (сетевая ошибка). Установите вручную: https://api.telegram.org/bot{bot_token}/setWebhook?url={webhook_url}"
141
+ )
142
+ else:
143
+ return TelegramConnectResponse(
144
+ ok=True,
145
+ status="connected",
146
+ webhook_url=webhook_url,
147
+ message=f"✅ Бот @{bot_username} подключен! Если не работает, установите webhook вручную."
148
+ )
149
 
150
  except HTTPException:
151
  raise