Spaces:
Sleeping

axeronis commited on
Commit
41be229
·
1 Parent(s): 782696b

feat: download and display incoming media from Telegram

Browse files

- Add download_telegram_file() helper to fetch files via Bot API
- Add get_mime_type() for proper content-type mapping
- Download photos/voice/documents from Telegram webhooks
- Upload to Supabase chat-attachments bucket
- Save media_url, media_type, media_name in Message records
- UI will display images/audio/files instead of just transcribed text

Files changed (1) hide show
  1. backend/app/api/webhook.py +108 -2
backend/app/api/webhook.py CHANGED
@@ -161,6 +161,54 @@ async def send_product_images_if_mentioned(
161
  logger.info(f"📷 Auto-sent image for product: {product.name}")
162
 
163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  router = APIRouter(prefix="/webhook", tags=["Webhooks"])
165
 
166
 
@@ -297,15 +345,73 @@ async def telegram_webhook(
297
  channel="telegram"
298
  )
299
 
300
- # Save user message
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
  user_message = Message(
302
  tenant_id=tenant_id,
303
  conversation_id=conversation.id,
304
  sender_type="user",
305
- content=user_text
 
 
 
306
  )
307
  session.add(user_message)
308
  await session.commit()
 
309
 
310
  # Update lead activity
311
  lead.last_message_at = datetime.utcnow()
 
161
  logger.info(f"📷 Auto-sent image for product: {product.name}")
162
 
163
 
164
+ async def download_telegram_file(bot_token: str, file_id: str) -> tuple[bytes, str]:
165
+ """
166
+ Download file from Telegram Bot API.
167
+ Returns (file_bytes, file_extension)
168
+ """
169
+ async with httpx.AsyncClient() as client:
170
+ # 1. Get file path
171
+ file_info_url = f"https://api.telegram.org/bot{bot_token}/getFile"
172
+ file_response = await client.post(file_info_url, json={"file_id": file_id}, timeout=10.0)
173
+ file_response.raise_for_status()
174
+
175
+ file_data = file_response.json()
176
+ if not file_data.get("ok"):
177
+ raise Exception(f"Telegram getFile failed: {file_data}")
178
+
179
+ file_path = file_data["result"]["file_path"]
180
+
181
+ # 2. Download file
182
+ download_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}"
183
+ download_response = await client.get(download_url, timeout=30.0)
184
+ download_response.raise_for_status()
185
+
186
+ # 3. Extract extension
187
+ file_ext = file_path.split(".")[-1] if "." in file_path else "bin"
188
+
189
+ return download_response.content, file_ext
190
+
191
+
192
+ def get_mime_type(extension: str) -> str:
193
+ """Map file extension to MIME type."""
194
+ mime_map = {
195
+ "jpg": "image/jpeg",
196
+ "jpeg": "image/jpeg",
197
+ "png": "image/png",
198
+ "webp": "image/webp",
199
+ "gif": "image/gif",
200
+ "ogg": "audio/ogg",
201
+ "oga": "audio/ogg",
202
+ "mp3": "audio/mpeg",
203
+ "m4a": "audio/mp4",
204
+ "pdf": "application/pdf",
205
+ "doc": "application/msword",
206
+ "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
207
+ "txt": "text/plain",
208
+ }
209
+ return mime_map.get(extension.lower(), "application/octet-stream")
210
+
211
+
212
  router = APIRouter(prefix="/webhook", tags=["Webhooks"])
213
 
214
 
 
345
  channel="telegram"
346
  )
347
 
348
+ # Download and upload media if present
349
+ media_url = None
350
+ media_type = None
351
+ media_name = None
352
+
353
+ if (voice_file_id or photo_file_id or doc_file_id) and tenant.telegram_bot_token:
354
+ try:
355
+ file_id = voice_file_id or photo_file_id or doc_file_id
356
+
357
+ # 1. Download from Telegram
358
+ logger.info(f"⬇️ Downloading file {file_id[:8]}... from Telegram")
359
+ file_bytes, file_ext = await download_telegram_file(
360
+ tenant.telegram_bot_token,
361
+ file_id
362
+ )
363
+ logger.info(f"✅ Downloaded {len(file_bytes)} bytes, ext: {file_ext}")
364
+
365
+ # 2. Upload to Supabase
366
+ from app.core.supabase import supabase_client
367
+ import time
368
+ import re
369
+
370
+ if supabase_client:
371
+ bucket = "chat-attachments"
372
+ ts = int(time.time())
373
+ safe_name = f"{ts}_{file_id[:12]}.{file_ext}"
374
+ path = f"{tenant_id}/{conversation.id}/{safe_name}"
375
+
376
+ mime_type = get_mime_type(file_ext)
377
+
378
+ logger.info(f"⬆️ Uploading to Supabase: {path}")
379
+ supabase_client.storage.from_(bucket).upload(
380
+ path=path,
381
+ file=file_bytes,
382
+ file_options={"content-type": mime_type}
383
+ )
384
+ media_url = supabase_client.storage.from_(bucket).get_public_url(path)
385
+ logger.info(f"✅ Uploaded to Supabase: {media_url[:50]}...")
386
+
387
+ # 3. Set media metadata
388
+ media_type = mime_type
389
+ if voice_file_id:
390
+ media_name = "voice.ogg"
391
+ elif photo_file_id:
392
+ media_name = f"photo.{file_ext}"
393
+ elif doc_file_id:
394
+ media_name = doc_file_name or f"document.{file_ext}"
395
+ else:
396
+ logger.warning("⚠️ Supabase client not available, media will not be uploaded")
397
+
398
+ except Exception as e:
399
+ logger.error(f"❌ Failed to download/upload media: {e}")
400
+ # Continue without media - at least save the transcribed text
401
+
402
+ # Save user message WITH media fields
403
  user_message = Message(
404
  tenant_id=tenant_id,
405
  conversation_id=conversation.id,
406
  sender_type="user",
407
+ content=user_text,
408
+ media_url=media_url,
409
+ media_type=media_type,
410
+ media_name=media_name
411
  )
412
  session.add(user_message)
413
  await session.commit()
414
+
415
 
416
  # Update lead activity
417
  lead.last_message_at = datetime.utcnow()